task_url stringlengths 30 116 | task_name stringlengths 2 86 | task_description stringlengths 0 14.4k | language_url stringlengths 2 53 | language_name stringlengths 1 52 | code stringlengths 0 61.9k |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/Left_factorials | Left factorials | Left factorials, !n, may refer to either subfactorials or to factorial sums;
the same notation can be confusingly seen being used for the two different definitions.
Sometimes, subfactorials (also known as derangements) may use any of the notations:
!n`
!n
n¡
(It may not be vis... | #Java | Java | import java.math.BigInteger;
public class LeftFac{
public static BigInteger factorial(BigInteger n){
BigInteger ans = BigInteger.ONE;
for(BigInteger x = BigInteger.ONE; x.compareTo(n) <= 0; x = x.add(BigInteger.ONE)){
ans = ans.multiply(x);
}
return ans;
}
public static BigInteger leftFact(BigInteger ... |
http://rosettacode.org/wiki/Linear_congruential_generator | Linear congruential generator | The linear congruential generator is a very simple example of a random number generator.
All linear congruential generators use this formula:
r
n
+
1
=
a
×
r
n
+
c
(
mod
m
)
{\displaystyle r_{n+1}=a\times r_{n}+c{\pmod {m}}}
Where:
r
0
{\displaystyle r_{0}}
is a seed.
r
1
... | #FreeBASIC | FreeBASIC | ' version 04-11-2016
' compile with: fbc -s console
' to seed BSD_lcg(seed > -1)
' to get random number BSD_lcg(-1) or BSD_lcg() or just BSD_lcg
Function BSD_lcg(seed As UInteger = -1) As UInteger
Static As UInteger bsd_state
If seed <> -1 Then
bsd_state = seed Mod 2 ^ 31
Else
bsd_stat... |
http://rosettacode.org/wiki/Leonardo_numbers | Leonardo numbers |
Leonardo numbers are also known as the Leonardo series.
The Leonardo numbers are a sequence of numbers defined by:
L(0) = 1 [1st equation]
L(1) = 1 [2nd equation]
L(n) = L(n-1) + L(n-2) + 1 ... | #Run_BASIC | Run BASIC | sqliteconnect #mem, ":memory:"
#mem execute("CREATE TABLE lno (name,L0,L1,ad)")
#mem execute("INSERT INTO lno VALUES('Leonardo',1,1,1),('Fibonacci',0,1,0);")
#mem execute("SELECT * FROM lno")
for j = 1 to 2
#row = #mem #nextrow()
name$ = #row name$()
L0 = #row L0()
L1 = #row L1()
ad = #row ad()
print :print n... |
http://rosettacode.org/wiki/Leonardo_numbers | Leonardo numbers |
Leonardo numbers are also known as the Leonardo series.
The Leonardo numbers are a sequence of numbers defined by:
L(0) = 1 [1st equation]
L(1) = 1 [2nd equation]
L(n) = L(n-1) + L(n-2) + 1 ... | #Rust | Rust | fn leonardo(mut n0: u32, mut n1: u32, add: u32) -> impl std::iter::Iterator<Item = u32> {
std::iter::from_fn(move || {
let n = n0;
n0 = n1;
n1 += n + add;
Some(n)
})
}
fn main() {
println!("First 25 Leonardo numbers:");
for i in leonardo(1, 1, 1).take(25) {
prin... |
http://rosettacode.org/wiki/Leap_year | Leap year | Task
Determine whether a given year is a leap year in the Gregorian calendar.
See also
Leap year (wiki)
| #Bash | Bash |
#!/bin/bash
is_leap_year () # Define function named is_leap_year
{
declare -i year=$1 # declare integer variable "year" and set it to function parm 1
echo -n "$year ($2)-> " # print the year passed in, but do not go to the next line
if (( $year % 4 == 0 )) # if year not dividable by 4, then not a leap y... |
http://rosettacode.org/wiki/Last_letter-first_letter | Last letter-first letter | A certain children's game involves starting with a word in a particular category. Each participant in turn says a word, but that word must begin with the final letter of the previous word. Once a word has been given, it cannot be repeated. If an opponent cannot give a word in the category, they fall out of the ga... | #BBC_BASIC | BBC BASIC | DIM names$(69)
names$() = "audino", "bagon", "baltoy", "banette", \
\ "bidoof", "braviary", "bronzor", "carracosta", "charmeleon", \
\ "cresselia", "croagunk", "darmanitan", "deino", "emboar", \
\ "emolga", "exeggcute", "gabite", "girafarig", "gulpin", \
\ "haxorus", "heatmor", "heat... |
http://rosettacode.org/wiki/Largest_number_divisible_by_its_digits | Largest number divisible by its digits | Task
Find the largest base 10 integer whose digits are all different, and is evenly divisible by each of its individual digits.
These numbers are also known as Lynch-Bell numbers, numbers n such that the
(base ten) digits are all different (and do not include zero) and n is divisible by each of it... | #360_Assembly | 360 Assembly | * Largest number divisible by its digits - base10 - 05/05/2020
LANUDIDO CSECT
USING LANUDIDO,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
SAVE (14,12) save previous context
ST R13,4(R15) l... |
http://rosettacode.org/wiki/Largest_number_divisible_by_its_digits | Largest number divisible by its digits | Task
Find the largest base 10 integer whose digits are all different, and is evenly divisible by each of its individual digits.
These numbers are also known as Lynch-Bell numbers, numbers n such that the
(base ten) digits are all different (and do not include zero) and n is divisible by each of it... | #ALGOL_68 | ALGOL 68 | BEGIN # find the largest decimal integer with unique digits, divisible by its digits #
INT magic = 9 * 8 * 7; # see analysis in the Raku sample #
INT high = 9876432 OVER magic * magic;
BOOL found := FALSE;
FOR i FROM high BY - magic TO magic WHILE NOT found DO
IF INT d1 = i MOD 10;
... |
http://rosettacode.org/wiki/Largest_proper_divisor_of_n | Largest proper divisor of n | Task
a(1) = 1; for n > 1, a(n) = largest proper divisor of n, where n < 101 .
| #Arturo | Arturo | loop split.every:10 [1] ++ map 2..100 'x -> last chop factors x 'row [
print map to [:string] row 'r -> pad r 5
] |
http://rosettacode.org/wiki/Largest_proper_divisor_of_n | Largest proper divisor of n | Task
a(1) = 1; for n > 1, a(n) = largest proper divisor of n, where n < 101 .
| #AWK | AWK |
# syntax: GAWK -f LARGEST_PROPER_DIVISOR_OF_N.AWK
# converted from C
BEGIN {
start = 1
stop = 100
for (i=start; i<=stop; i++) {
printf("%3d%1s",largest_proper_divisor(i),++count%10?"":"\n")
}
printf("\nLargest proper divisor of n %d-%d\n",start,stop)
exit(0)
}
function largest_proper_div... |
http://rosettacode.org/wiki/Least_common_multiple | Least common multiple | Least common multiple
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Compute the least common multiple (LCM) of two integers.
Given m and n, the least common multiple is the smallest positive integer that has both m and n as factor... | #ATS | ATS | #define ATS_DYNLOADFLAG 0 (* No initialization is needed. *)
#include "share/atspre_define.hats"
#include "share/atspre_staload.hats"
(********************************************************************)
(* *)
(* Declarations. ... |
http://rosettacode.org/wiki/Latin_Squares_in_reduced_form | Latin Squares in reduced form | A Latin Square is in its reduced form if the first row and first column contain items in their natural order. The order n is the number of items. For any given n there is a set of reduced Latin Squares whose size increases rapidly with n. g is a number which identifies a unique element within the set of reduced Latin S... | #Go | Go | package main
import (
"fmt"
"sort"
)
type matrix [][]int
// generate derangements of first n numbers, with 'start' in first place.
func dList(n, start int) (r matrix) {
start-- // use 0 basing
a := make([]int, n)
for i := range a {
a[i] = i
}
a[0], a[start] = start, a[0]
so... |
http://rosettacode.org/wiki/Law_of_cosines_-_triples | Law of cosines - triples | The Law of cosines states that for an angle γ, (gamma) of any triangle, if the sides adjacent to the angle are A and B and the side opposite is C; then the lengths of the sides are related by this formula:
A2 + B2 - 2ABcos(γ) = C2
Specific angles
For an angle of of 90º this becomes the more familiar ... | #Haskell | Haskell | import qualified Data.Map.Strict as Map
import qualified Data.Set as Set
import Data.Monoid ((<>))
triangles
:: (Map.Map Int Int -> Int -> Int -> Int -> Int -> Maybe Int)
-> Int
-> [(Int, Int, Int)]
triangles f n =
let mapRoots = Map.fromList $ ((,) =<< (^ 2)) <$> [1 .. n]
in Set.elems $
foldr
(... |
http://rosettacode.org/wiki/Levenshtein_distance | Levenshtein distance |
This page uses content from Wikipedia. The original article was at Levenshtein distance. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In information theory and computer science, the Levenshtein ... | #CoffeeScript | CoffeeScript | levenshtein = (str1, str2) ->
# more of less ported simple algorithm from JS
m = str1.length
n = str2.length
d = []
return n unless m
return m unless n
d[i] = [i] for i in [0..m]
d[0][j] = j for j in [1..n]
for i in [1..m]
for j in [1..n]
if str1[i-1] is str2[j-1]
d[i][j] =... |
http://rosettacode.org/wiki/Letter_frequency | Letter frequency | Task
Open a text file and count the occurrences of each letter.
Some of these programs count all characters (including punctuation),
but some only count letters A to Z.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequen... | #BBC_BASIC | BBC BASIC | DIM cnt%(255)
file% = OPENIN("C:\unixdict.txt")
IF file%=0 ERROR 100, "Could not open file"
REPEAT
A$ = GET$#file%
L% = LEN(A$)
IF L% THEN
FOR I% = 1 TO L%
cnt%(ASCMID$(A$,I%)) += 1
NEXT
ENDIF
UNTIL EOF#file%
CLOSE #... |
http://rosettacode.org/wiki/List_comprehensions | List comprehensions | A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name.
Some attributes of a list comprehension are:
They should be distinct from (nested) for loops and the use of map and filter functio... | #Phix | Phix | global function new_dict(integer pool_only=0)
global procedure destroy_dict(integer tid, integer justclear=0)
global procedure setd(object key, object data, integer tid=1)
global function getd(object key, integer tid=1)
global procedure destroy_dict(integer tid, integer justclear=0)
global function getd_index(object ke... |
http://rosettacode.org/wiki/Loops/For | Loops/For | “For” loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code.
Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers.
... | #XBasic | XBasic |
PROGRAM "for"
DECLARE FUNCTION Entry()
FUNCTION Entry()
FOR i% = 1 TO 5
FOR j% = 1 TO i%
PRINT "*";
NEXT j%
PRINT
NEXT i%
END FUNCTION
END PROGRAM
|
http://rosettacode.org/wiki/Left_factorials | Left factorials | Left factorials, !n, may refer to either subfactorials or to factorial sums;
the same notation can be confusingly seen being used for the two different definitions.
Sometimes, subfactorials (also known as derangements) may use any of the notations:
!n`
!n
n¡
(It may not be vis... | #jq | jq | def left_factorial:
reduce range(1; .+1) as $i
# state: [i!, !i]
([1,0]; .[1] += .[0] | .[0] *= $i)
| .[1]; |
http://rosettacode.org/wiki/Left_factorials | Left factorials | Left factorials, !n, may refer to either subfactorials or to factorial sums;
the same notation can be confusingly seen being used for the two different definitions.
Sometimes, subfactorials (also known as derangements) may use any of the notations:
!n`
!n
n¡
(It may not be vis... | #Julia | Julia | leftfactorial(n::Integer) = n ≤ 0 ? zero(n) : sum(factorial, 0:n-1)
@show leftfactorial.(0:10)
@show ndigits.(leftfactorial.(big.(1000:1000:10_000))) |
http://rosettacode.org/wiki/Linear_congruential_generator | Linear congruential generator | The linear congruential generator is a very simple example of a random number generator.
All linear congruential generators use this formula:
r
n
+
1
=
a
×
r
n
+
c
(
mod
m
)
{\displaystyle r_{n+1}=a\times r_{n}+c{\pmod {m}}}
Where:
r
0
{\displaystyle r_{0}}
is a seed.
r
1
... | #F.C5.8Drmul.C3.A6 | Fōrmulæ | package main
import "fmt"
// basic linear congruential generator
func lcg(a, c, m, seed uint32) func() uint32 {
r := seed
return func() uint32 {
r = (a*r + c) % m
return r
}
}
// microsoft generator has extra division step
func msg(seed uint32) func() uint32 {
g := lcg(214013, 2531... |
http://rosettacode.org/wiki/Leonardo_numbers | Leonardo numbers |
Leonardo numbers are also known as the Leonardo series.
The Leonardo numbers are a sequence of numbers defined by:
L(0) = 1 [1st equation]
L(1) = 1 [2nd equation]
L(n) = L(n-1) + L(n-2) + 1 ... | #Scala | Scala | def leo( n:Int, n1:Int=1, n2:Int=1, addnum:Int=1 ) : BigInt = n match {
case 0 => n1
case 1 => n2
case n => leo(n - 1, n1, n2, addnum) + leo(n - 2, n1, n2, addnum) + addnum
}
{
println( "The first 25 Leonardo Numbers:")
(0 until 25) foreach { n => print( leo(n) + " " ) }
println( "\n\nThe first 25 Fibonacci N... |
http://rosettacode.org/wiki/Leonardo_numbers | Leonardo numbers |
Leonardo numbers are also known as the Leonardo series.
The Leonardo numbers are a sequence of numbers defined by:
L(0) = 1 [1st equation]
L(1) = 1 [2nd equation]
L(n) = L(n-1) + L(n-2) + 1 ... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
const proc: leonardo (in var integer: l0, in var integer: l1, in integer: add, in integer: count) is func
local
var integer: temp is 0;
begin
for count do
write(" " <& l0);
temp := l0 + l1 + add;
l0 := l1;
l1 := temp;
end for;
writeln;
end func;
... |
http://rosettacode.org/wiki/Leap_year | Leap year | Task
Determine whether a given year is a leap year in the Gregorian calendar.
See also
Leap year (wiki)
| #BASIC | BASIC | FOR Y = 1750 TO 2021: PRINT MID$ ( STR$ (Y) + " ",1,5 * (Y / 4 = INT (Y / 4)) * ((Y / 100 < > INT (Y / 100)) + (Y / 400 = INT (Y / 400))));: NEXT |
http://rosettacode.org/wiki/Last_letter-first_letter | Last letter-first letter | A certain children's game involves starting with a word in a particular category. Each participant in turn says a word, but that word must begin with the final letter of the previous word. Once a word has been given, it cannot be repeated. If an opponent cannot give a word in the category, they fall out of the ga... | #Bracmat | Bracmat | ( audino bagon baltoy banette bidoof braviary bronzor
carracosta charmeleon cresselia croagunk darmanitan deino
emboar emolga exeggcute gabite girafarig gulpin haxorus
heatmor heatran ivysaur jellicent jumpluff kangaskhan
kricketune landorus ledyba loudred lumineon lunatone machamp
magnezone mamos... |
http://rosettacode.org/wiki/Largest_number_divisible_by_its_digits | Largest number divisible by its digits | Task
Find the largest base 10 integer whose digits are all different, and is evenly divisible by each of its individual digits.
These numbers are also known as Lynch-Bell numbers, numbers n such that the
(base ten) digits are all different (and do not include zero) and n is divisible by each of it... | #Arturo | Arturo | lynchBell?: function [num][
hset: new []
loop digits num 'd [
if d=0 -> return false
if or? [0 <> mod num d]
[contains? hset d] -> return false
'hset ++ d
unique 'hset
]
return true
]
Magic: 9 * 8 * 7
High: ((from.hex "9876432") / Magic) * Magic
loop ra... |
http://rosettacode.org/wiki/Largest_proper_divisor_of_n | Largest proper divisor of n | Task
a(1) = 1; for n > 1, a(n) = largest proper divisor of n, where n < 101 .
| #BASIC | BASIC | 10 DEFINT A-Z
20 FOR I=1 TO 100
30 IF I=1 THEN PRINT " 1";: GOTO 70
40 FOR J=I-1 TO 1 STEP -1
50 IF I MOD J=0 THEN PRINT USING "###";J;: GOTO 70
60 NEXT J
70 IF I MOD 10=0 THEN PRINT
80 NEXT I |
http://rosettacode.org/wiki/Largest_proper_divisor_of_n | Largest proper divisor of n | Task
a(1) = 1; for n > 1, a(n) = largest proper divisor of n, where n < 101 .
| #BASIC256 | BASIC256 | print "El mayor divisor propio de n es:\n"
print " 1 1 ";
for i = 3 to 100
for j = i-1 to 1 step -1
If i % j = 0 then
print " "; j; " ";
exit for
end if
next j
if i % 10 = 0 then print
next i
end |
http://rosettacode.org/wiki/Largest_proper_divisor_of_n | Largest proper divisor of n | Task
a(1) = 1; for n > 1, a(n) = largest proper divisor of n, where n < 101 .
| #BCPL | BCPL | get "libhdr"
let lpd(n) = valof
for i = n<=1 -> 1, n-1 to 1 by -1
if n rem i=0 resultis i
let start() be
for i=1 to 100
$( writed(lpd(i), 3)
if i rem 10=0 then wrch('*N')
$) |
http://rosettacode.org/wiki/Least_common_multiple | Least common multiple | Least common multiple
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Compute the least common multiple (LCM) of two integers.
Given m and n, the least common multiple is the smallest positive integer that has both m and n as factor... | #AutoHotkey | AutoHotkey | LCM(Number1,Number2)
{
If (Number1 = 0 || Number2 = 0)
Return
Var := Number1 * Number2
While, Number2
Num := Number2, Number2 := Mod(Number1,Number2), Number1 := Num
Return, Var // Number1
}
Num1 = 12
Num2 = 18
MsgBox % LCM(Num1,Num2) |
http://rosettacode.org/wiki/Latin_Squares_in_reduced_form | Latin Squares in reduced form | A Latin Square is in its reduced form if the first row and first column contain items in their natural order. The order n is the number of items. For any given n there is a set of reduced Latin Squares whose size increases rapidly with n. g is a number which identifies a unique element within the set of reduced Latin S... | #Haskell | Haskell | import Data.List (permutations, (\\))
import Control.Monad (foldM, forM_)
latinSquares :: Eq a => [a] -> [[[a]]]
latinSquares [] = []
latinSquares set = map reverse <$> squares
where
squares = foldM addRow firstRow perm
perm = tail (groupedPermutations set)
firstRow = pure <$> set
addRow tbl rows = ... |
http://rosettacode.org/wiki/Law_of_cosines_-_triples | Law of cosines - triples | The Law of cosines states that for an angle γ, (gamma) of any triangle, if the sides adjacent to the angle are A and B and the side opposite is C; then the lengths of the sides are related by this formula:
A2 + B2 - 2ABcos(γ) = C2
Specific angles
For an angle of of 90º this becomes the more familiar ... | #J | J | load 'trig stats'
RHS=: *: NB. right-hand-side of Cosine Law
LHS=: +/@:*:@] - cos@rfd@[ * 2 * */@] NB. Left-hand-side of Cosine Law
solve=: 4 :0
adjsides=. >: 2 combrep y
oppside=. >: i. y
idx=. (RHS oppside) i. x LHS"1 adjsides
adjsides ((#~ idx ~: #) ,. ({~ idx -. #)@]) oppsid... |
http://rosettacode.org/wiki/Law_of_cosines_-_triples | Law of cosines - triples | The Law of cosines states that for an angle γ, (gamma) of any triangle, if the sides adjacent to the angle are A and B and the side opposite is C; then the lengths of the sides are related by this formula:
A2 + B2 - 2ABcos(γ) = C2
Specific angles
For an angle of of 90º this becomes the more familiar ... | #Java | Java |
public class LawOfCosines {
public static void main(String[] args) {
generateTriples(13);
generateTriples60(10000);
}
private static void generateTriples(int max) {
for ( int coeff : new int[] {0, -1, 1} ) {
int count = 0;
System.out.printf("Max side len... |
http://rosettacode.org/wiki/Levenshtein_distance | Levenshtein distance |
This page uses content from Wikipedia. The original article was at Levenshtein distance. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In information theory and computer science, the Levenshtein ... | #Common_Lisp | Common Lisp | (defun levenshtein (a b)
(let* ((la (length a))
(lb (length b))
(rec (make-array (list (1+ la) (1+ lb)) :initial-element nil)))
(labels ((leven (x y)
(cond
((zerop x) y)
((zerop y) x)
((aref rec x y) (aref rec x y))
... |
http://rosettacode.org/wiki/Letter_frequency | Letter frequency | Task
Open a text file and count the occurrences of each letter.
Some of these programs count all characters (including punctuation),
but some only count letters A to Z.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequen... | #BCPL | BCPL | get "libhdr"
let start() be
$( let count = vec 255
let file = findinput("unixdict.txt")
for i = 0 to 255 do i!count := 0
selectinput(file)
$( let ch = rdch()
if ch = endstreamch then break
ch!count := ch!count + 1
$) repeat
for i = 'A' to 'Z' do
$( let n = i!count ... |
http://rosettacode.org/wiki/List_comprehensions | List comprehensions | A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name.
Some attributes of a list comprehension are:
They should be distinct from (nested) for loops and the use of map and filter functio... | #Picat | Picat | pyth(N) = [[A,B,C] : A in 1..N, B in A..N, C in B..N, A**2 + B**2 == C**2]. |
http://rosettacode.org/wiki/Loops/For | Loops/For | “For” loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code.
Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers.
... | #XBS | XBS | const repChar:string = "*";
const maxIters = 5;
for(i=1;maxIters;1){
set str:string = "";
for(o=1;i;1){
str+=repChar;
}
log(str);
} |
http://rosettacode.org/wiki/Left_factorials | Left factorials | Left factorials, !n, may refer to either subfactorials or to factorial sums;
the same notation can be confusingly seen being used for the two different definitions.
Sometimes, subfactorials (also known as derangements) may use any of the notations:
!n`
!n
n¡
(It may not be vis... | #Kotlin | Kotlin | // version 1.0.6
import java.math.BigInteger
fun leftFactorial(n: Int): BigInteger {
if (n == 0) return BigInteger.ZERO
var fact = BigInteger.ONE
var sum = fact
for (i in 1 until n) {
fact *= BigInteger.valueOf(i.toLong())
sum += fact
}
return sum
}
fun main(args: A... |
http://rosettacode.org/wiki/Linear_congruential_generator | Linear congruential generator | The linear congruential generator is a very simple example of a random number generator.
All linear congruential generators use this formula:
r
n
+
1
=
a
×
r
n
+
c
(
mod
m
)
{\displaystyle r_{n+1}=a\times r_{n}+c{\pmod {m}}}
Where:
r
0
{\displaystyle r_{0}}
is a seed.
r
1
... | #Go | Go | package main
import "fmt"
// basic linear congruential generator
func lcg(a, c, m, seed uint32) func() uint32 {
r := seed
return func() uint32 {
r = (a*r + c) % m
return r
}
}
// microsoft generator has extra division step
func msg(seed uint32) func() uint32 {
g := lcg(214013, 2531... |
http://rosettacode.org/wiki/Leonardo_numbers | Leonardo numbers |
Leonardo numbers are also known as the Leonardo series.
The Leonardo numbers are a sequence of numbers defined by:
L(0) = 1 [1st equation]
L(1) = 1 [2nd equation]
L(n) = L(n-1) + L(n-2) + 1 ... | #Sidef | Sidef | func 𝑳(n, 𝑳0 = 1, 𝑳1 = 1, 𝑳add = 1) {
{ (𝑳0, 𝑳1) = (𝑳1, 𝑳0 + 𝑳1 + 𝑳add) } * n
return 𝑳0
}
say "The first 25 Leonardo numbers:"
say 25.of { 𝑳(_) }
say "\nThe first 25 numbers using 𝑳0 of 0, 𝑳1 of 1, and adder of 0:"
say 25.of { 𝑳(_, 0, 1, 0) } |
http://rosettacode.org/wiki/Leonardo_numbers | Leonardo numbers |
Leonardo numbers are also known as the Leonardo series.
The Leonardo numbers are a sequence of numbers defined by:
L(0) = 1 [1st equation]
L(1) = 1 [2nd equation]
L(n) = L(n-1) + L(n-2) + 1 ... | #Swift | Swift | struct Leonardo: Sequence, IteratorProtocol {
private let add : Int
private var n0: Int
private var n1: Int
init(n0: Int = 1, n1: Int = 1, add: Int = 1) {
self.n0 = n0
self.n1 = n1
self.add = add
}
mutating func next() -> Int? {
let n = n0
n0 = n1
... |
http://rosettacode.org/wiki/Leap_year | Leap year | Task
Determine whether a given year is a leap year in the Gregorian calendar.
See also
Leap year (wiki)
| #Batch_File | Batch File | @echo off
::The Main Thing...
for %%x in (1900 2046 2012 1600 1800 2031 1952) do (
call :leap %%x
)
echo.
pause
exit/b
::/The Main Thing...
::The Function...
:leap
set year=%1
set /a op1=%year%%%4
set /a op2=%year%%%100
set /a op3=%year%%%400
if not "%op1%"=="0" (goto :no)
if not "%op2%"=="0" (goto :yes)
if not "%op... |
http://rosettacode.org/wiki/Last_letter-first_letter | Last letter-first letter | A certain children's game involves starting with a word in a particular category. Each participant in turn says a word, but that word must begin with the final letter of the previous word. Once a word has been given, it cannot be repeated. If an opponent cannot give a word in the category, they fall out of the ga... | #C | C | #include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <inttypes.h>
typedef struct {
uint16_t index;
char last_char, first_char;
} Ref;
Ref* longest_path_refs;
size_t longest_path_refs_len;
Ref* refs;
size_t refs_len;
size_t n_solutions;
const char** longest_path;
size_t longest_path_len;... |
http://rosettacode.org/wiki/Largest_number_divisible_by_its_digits | Largest number divisible by its digits | Task
Find the largest base 10 integer whose digits are all different, and is evenly divisible by each of its individual digits.
These numbers are also known as Lynch-Bell numbers, numbers n such that the
(base ten) digits are all different (and do not include zero) and n is divisible by each of it... | #AWK | AWK | # Usage: gawk -f LARGEST_NUMBER_DIVISIBLE_BY_ITS_DIGITS_10.AWK
BEGIN {
base = 10
comdiv = 12
startn = 9876543
stopn = 1000000
solve(startn, stopn)
}
function solve(startn, stopn, n, d) {
for (n = startn - startn % comdiv; n > stopn; n -= comdiv) {
if (hasuniqedigits(n)) {
... |
http://rosettacode.org/wiki/Largest_proper_divisor_of_n | Largest proper divisor of n | Task
a(1) = 1; for n > 1, a(n) = largest proper divisor of n, where n < 101 .
| #BQN | BQN | (1⌈´↕×0=↕|⊢)¨ ∘‿10⥊1+↕100 |
http://rosettacode.org/wiki/Largest_proper_divisor_of_n | Largest proper divisor of n | Task
a(1) = 1; for n > 1, a(n) = largest proper divisor of n, where n < 101 .
| #C | C | #include <stdio.h>
unsigned int lpd(unsigned int n) {
if (n<=1) return 1;
int i;
for (i=n-1; i>0; i--)
if (n%i == 0) return i;
}
int main() {
int i;
for (i=1; i<=100; i++) {
printf("%3d", lpd(i));
if (i % 10 == 0) printf("\n");
}
return 0;
} |
http://rosettacode.org/wiki/Least_common_multiple | Least common multiple | Least common multiple
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Compute the least common multiple (LCM) of two integers.
Given m and n, the least common multiple is the smallest positive integer that has both m and n as factor... | #AutoIt | AutoIt |
Func _LCM($a, $b)
Local $c, $f, $m = $a, $n = $b
$c = 1
While $c <> 0
$f = Int($a / $b)
$c = $a - $b * $f
If $c <> 0 Then
$a = $b
$b = $c
EndIf
WEnd
Return $m * $n / $b
EndFunc ;==>_LCM
|
http://rosettacode.org/wiki/Latin_Squares_in_reduced_form | Latin Squares in reduced form | A Latin Square is in its reduced form if the first row and first column contain items in their natural order. The order n is the number of items. For any given n there is a set of reduced Latin Squares whose size increases rapidly with n. g is a number which identifies a unique element within the set of reduced Latin S... | #J | J |
redlat=: {{
perms=: (A.&i.~ !)~ y
sqs=. i.1 1,y
for_j.}.i.y do.
p=. (j={."1 perms)#perms
sel=.-.+./"1 p +./@:="1/"2 sqs
sqs=.(#~ 1-0*/ .="1{:"2),/sqs,"2 1 sel#"2 p
end.
}}
|
http://rosettacode.org/wiki/Latin_Squares_in_reduced_form | Latin Squares in reduced form | A Latin Square is in its reduced form if the first row and first column contain items in their natural order. The order n is the number of items. For any given n there is a set of reduced Latin Squares whose size increases rapidly with n. g is a number which identifies a unique element within the set of reduced Latin S... | #Java | Java |
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class LatinSquaresInReducedForm {
public static void main(String[] args) {
System.out.printf("Reduced latin squares of order 4:%n");
for ( LatinSquare square : getReducedLatinSquares... |
http://rosettacode.org/wiki/Law_of_cosines_-_triples | Law of cosines - triples | The Law of cosines states that for an angle γ, (gamma) of any triangle, if the sides adjacent to the angle are A and B and the side opposite is C; then the lengths of the sides are related by this formula:
A2 + B2 - 2ABcos(γ) = C2
Specific angles
For an angle of of 90º this becomes the more familiar ... | #JavaScript | JavaScript | (() => {
'use strict';
// main :: IO ()
const main = () => {
const
f90 = dct => x2 => dct[x2],
f60 = dct => (x2, ab) => dct[x2 - ab],
f120 = dct => (x2, ab) => dct[x2 + ab],
f60unequal = dct => (x2, ab, a, b) =>
(a !== b) ? (
... |
http://rosettacode.org/wiki/Levenshtein_distance | Levenshtein distance |
This page uses content from Wikipedia. The original article was at Levenshtein distance. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In information theory and computer science, the Levenshtein ... | #Crystal | Crystal | require "levenshtein"
puts Levenshtein.distance("kitten", "sitting")
puts Levenshtein.distance("rosettacode", "raisethysword")
|
http://rosettacode.org/wiki/Letter_frequency | Letter frequency | Task
Open a text file and count the occurrences of each letter.
Some of these programs count all characters (including punctuation),
but some only count letters A to Z.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequen... | #Bracmat | Bracmat | (lc=
counts c
. fil$(!arg,r) {open file for reading}
& 0:?counts
& whl
' ( fil$:?c {read a byte}
& ( !c:(~<A:~>Z|~<a:~>z)
| 0
)
+ !counts
: ?counts {simply add any fou... |
http://rosettacode.org/wiki/List_comprehensions | List comprehensions | A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name.
Some attributes of a list comprehension are:
They should be distinct from (nested) for loops and the use of map and filter functio... | #PicoLisp | PicoLisp | (de pythag (N)
(job '((X . 1) (Y . 1) (Z . 0))
(loop
(when (> (inc 'Z) N)
(when (> (inc 'Y) N)
(setq Y (inc 'X)) )
(setq Z Y) )
(T (> X N))
(T (= (+ (* X X) (* Y Y)) (* Z Z))
(list X Y Z) ) ) ) )
(while (pythag 20)
(println @) ) |
http://rosettacode.org/wiki/Loops/For | Loops/For | “For” loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code.
Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers.
... | #XLISP | XLISP | (DO ((I 1 (+ I 1))) ((> I 5))
(DO ((J 0 (+ J 1))) ((= J I))
(DISPLAY "*"))
(NEWLINE)) |
http://rosettacode.org/wiki/Left_factorials | Left factorials | Left factorials, !n, may refer to either subfactorials or to factorial sums;
the same notation can be confusingly seen being used for the two different definitions.
Sometimes, subfactorials (also known as derangements) may use any of the notations:
!n`
!n
n¡
(It may not be vis... | #Lambdatalk | Lambdatalk |
'''1) defining !n'''
{def !n // the main function's name
{def !n.mem {A.new 0 1 2}} // initializing a global array
// memorizing the computed values of !n
{def !n.set ... |
http://rosettacode.org/wiki/Linear_congruential_generator | Linear congruential generator | The linear congruential generator is a very simple example of a random number generator.
All linear congruential generators use this formula:
r
n
+
1
=
a
×
r
n
+
c
(
mod
m
)
{\displaystyle r_{n+1}=a\times r_{n}+c{\pmod {m}}}
Where:
r
0
{\displaystyle r_{0}}
is a seed.
r
1
... | #Haskell | Haskell | bsd = tail . iterate (\n -> (n * 1103515245 + 12345) `mod` 2^31)
msr = map (`div` 2^16) . tail . iterate (\n -> (214013 * n + 2531011) `mod` 2^31)
main = do
print $ take 10 $ bsd 0 -- can take seeds other than 0, of course
print $ take 10 $ msr 0 |
http://rosettacode.org/wiki/Leonardo_numbers | Leonardo numbers |
Leonardo numbers are also known as the Leonardo series.
The Leonardo numbers are a sequence of numbers defined by:
L(0) = 1 [1st equation]
L(1) = 1 [2nd equation]
L(n) = L(n-1) + L(n-2) + 1 ... | #VBA | VBA |
Option Explicit
Private Sub LeonardoNumbers()
Dim L, MyString As String
Debug.Print "First 25 Leonardo numbers :"
L = Leo_Numbers(25, 1, 1, 1)
MyString = Join(L, "; ")
Debug.Print MyString
Debug.Print "First 25 Leonardo numbers from 0, 1 with add number = 0"
L = Leo_Numbers(25, 0, 1, 0)
... |
http://rosettacode.org/wiki/Leonardo_numbers | Leonardo numbers |
Leonardo numbers are also known as the Leonardo series.
The Leonardo numbers are a sequence of numbers defined by:
L(0) = 1 [1st equation]
L(1) = 1 [2nd equation]
L(n) = L(n-1) + L(n-2) + 1 ... | #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Iterator Function Leonardo(Optional L0 = 1, Optional L1 = 1, Optional add = 1) As IEnumerable(Of Integer)
While True
Yield L0
Dim t = L0 + L1 + add
L0 = L1
L1 = t
End While
End Function
Sub Main()
Console.WriteLine(St... |
http://rosettacode.org/wiki/Leap_year | Leap year | Task
Determine whether a given year is a leap year in the Gregorian calendar.
See also
Leap year (wiki)
| #BCPL | BCPL | get "libhdr"
let leap(year) = year rem 400 = 0 | (year rem 4 = 0 & year rem 100 ~= 0)
let start() be
$( let years = table 1899, 1900, 1901, 1902, 1903, 1904, 1905, 1999,
2000, 2001, 2002, 2003, 2004, 2021, 2022
for i = 0 to 14 do
writef("%N %S a leap year.*N",
yea... |
http://rosettacode.org/wiki/Last_Friday_of_each_month | Last Friday of each month | Task
Write a program or a script that returns the date of the last Fridays of each month of a given year.
The year may be given through any simple input method in your language (command line, std in, etc).
Example of an expected output:
./last_fridays 2012
2012-01-27
2012-02-24
2012-03-30
2012-04-27
2012-05-25
20... | #360_Assembly | 360 Assembly | * Last Friday of each month 17/07/2016
LASTFRI CSECT
USING LASTFRI,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
STM R14,R12,12(R13) prolog
ST R13,4(R15) " <-
ST R15,8(R13) ... |
http://rosettacode.org/wiki/Last_letter-first_letter | Last letter-first letter | A certain children's game involves starting with a word in a particular category. Each participant in turn says a word, but that word must begin with the final letter of the previous word. Once a word has been given, it cannot be repeated. If an opponent cannot give a word in the category, they fall out of the ga... | #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string pokemon_names = @"audino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon
cresselia croag... |
http://rosettacode.org/wiki/Largest_int_from_concatenated_ints | Largest int from concatenated ints | Task
Given a set of positive integers, write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this integer.
Use the following two sets of integers as tests and show your program output here.
{1, 34, 3, 98, 9, 76, 45, 4}
{54,... | #11l | 11l | F maxnum(x)
V maxlen = String(max(x)).len
R sorted((x.map(v -> String(v))), key' i -> i * (@maxlen * 2 I/ i.len), reverse' 1B).join(‘’)
L(numbers) [[212, 21221], [1, 34, 3, 98, 9, 76, 45, 4], [54, 546, 548, 60]]
print("Numbers: #.\n Largest integer: #15".format(numbers, maxnum(numbers))) |
http://rosettacode.org/wiki/Largest_number_divisible_by_its_digits | Largest number divisible by its digits | Task
Find the largest base 10 integer whose digits are all different, and is evenly divisible by each of its individual digits.
These numbers are also known as Lynch-Bell numbers, numbers n such that the
(base ten) digits are all different (and do not include zero) and n is divisible by each of it... | #BASIC256 | BASIC256 |
arraybase 1
for n = 9867000 to 9867400
dim numbers(9) fill 0
flag = true : flag2 = true : flag3 = true
cadena = string(n)
for m = 1 to length(cadena)
if int(mid(cadena,m,1)) > 0 then
numbers[int(mid(cadena,m,1))] += 1
else
flag2 = false
end if
next m
if flag2 = true then
for p = 1 to 9
i... |
http://rosettacode.org/wiki/Largest_number_divisible_by_its_digits | Largest number divisible by its digits | Task
Find the largest base 10 integer whose digits are all different, and is evenly divisible by each of its individual digits.
These numbers are also known as Lynch-Bell numbers, numbers n such that the
(base ten) digits are all different (and do not include zero) and n is divisible by each of it... | #C | C |
#include<stdio.h>
int main()
{
int num = 9876432,diff[] = {4,2,2,2},i,j,k=0;
char str[10];
start:snprintf(str,10,"%d",num);
for(i=0;str[i+1]!=00;i++){
if(str[i]=='0'||str[i]=='5'||num%(str[i]-'0')!=0){
num -= diff[k];
k = (k+1)%4;
goto start;
}
for(j=i+1;str[j]!=00;j++)
if(str[i]=... |
http://rosettacode.org/wiki/Largest_proper_divisor_of_n | Largest proper divisor of n | Task
a(1) = 1; for n > 1, a(n) = largest proper divisor of n, where n < 101 .
| #C.2B.2B | C++ | #include <cassert>
#include <iomanip>
#include <iostream>
int largest_proper_divisor(int n) {
assert(n > 0);
if ((n & 1) == 0)
return n >> 1;
for (int p = 3; p * p <= n; p += 2) {
if (n % p == 0)
return n / p;
}
return 1;
}
int main() {
for (int n = 1; n < 101; ++... |
http://rosettacode.org/wiki/Least_common_multiple | Least common multiple | Least common multiple
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Compute the least common multiple (LCM) of two integers.
Given m and n, the least common multiple is the smallest positive integer that has both m and n as factor... | #AWK | AWK | # greatest common divisor
function gcd(m, n, t) {
# Euclid's method
while (n != 0) {
t = m
m = n
n = t % n
}
return m
}
# least common multiple
function lcm(m, n, r) {
if (m == 0 || n == 0)
return 0
r = m * n / gcd(m, n)
return r < 0 ? -r : r
}
# Read two integers from each line of input.
# Pri... |
http://rosettacode.org/wiki/Latin_Squares_in_reduced_form | Latin Squares in reduced form | A Latin Square is in its reduced form if the first row and first column contain items in their natural order. The order n is the number of items. For any given n there is a set of reduced Latin Squares whose size increases rapidly with n. g is a number which identifies a unique element within the set of reduced Latin S... | #jq | jq | def count(s): reduce s as $x (0; .+1);
def factorial: reduce range(2;.+1) as $i (1; . * $i);
def permutations:
if length == 0 then []
else
range(0;length) as $i
| [.[$i]] + (del(.[$i])|permutations)
end ;
|
http://rosettacode.org/wiki/Latin_Squares_in_reduced_form | Latin Squares in reduced form | A Latin Square is in its reduced form if the first row and first column contain items in their natural order. The order n is the number of items. For any given n there is a set of reduced Latin Squares whose size increases rapidly with n. g is a number which identifies a unique element within the set of reduced Latin S... | #Julia | Julia | using Combinatorics
clash(row2, row1::Vector{Int}) = any(i -> row1[i] == row2[i], 1:length(row2))
clash(row, rows::Vector{Vector{Int}}) = any(r -> clash(row, r), rows)
permute_onefixed(i, n) = map(vec -> vcat(i, vec), permutations(filter(x -> x != i, 1:n)))
filter_permuted(rows, i, n) = filter(v -> !clash(v, ro... |
http://rosettacode.org/wiki/Law_of_cosines_-_triples | Law of cosines - triples | The Law of cosines states that for an angle γ, (gamma) of any triangle, if the sides adjacent to the angle are A and B and the side opposite is C; then the lengths of the sides are related by this formula:
A2 + B2 - 2ABcos(γ) = C2
Specific angles
For an angle of of 90º this becomes the more familiar ... | #jq | jq | def squares(n):
reduce range(1; 1+n) as $i ({}; .[$i*$i|tostring] = $i);
# if count, then just count
def solve(angle; maxLen; allowSame; count):
squares(maxLen) as $squares
| def qsqrt($n):
$squares[$n|tostring] as $sqrt
| if $sqrt then $sqrt else null end;
reduce range(1; maxLen+1) as $a ({};
... |
http://rosettacode.org/wiki/Law_of_cosines_-_triples | Law of cosines - triples | The Law of cosines states that for an angle γ, (gamma) of any triangle, if the sides adjacent to the angle are A and B and the side opposite is C; then the lengths of the sides are related by this formula:
A2 + B2 - 2ABcos(γ) = C2
Specific angles
For an angle of of 90º this becomes the more familiar ... | #Julia | Julia | sqdict(n) = Dict([(x*x, x) for x in 1:n])
numnotsame(arrarr) = sum(map(x -> !all(y -> y == x[1], x), arrarr))
function filtertriangles(N)
sqd = sqdict(N)
t60 = Vector{Vector{Int}}()
t90 = Vector{Vector{Int}}()
t120 = Vector{Vector{Int}}()
for x in 1:N, y in 1:x
xsq, ysq, xy = (x*x, y*y, x*... |
http://rosettacode.org/wiki/Levenshtein_distance | Levenshtein distance |
This page uses content from Wikipedia. The original article was at Levenshtein distance. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In information theory and computer science, the Levenshtein ... | #D | D | void main() {
import std.stdio, std.algorithm;
levenshteinDistance("kitten", "sitting").writeln;
} |
http://rosettacode.org/wiki/Letter_frequency | Letter frequency | Task
Open a text file and count the occurrences of each letter.
Some of these programs count all characters (including punctuation),
but some only count letters A to Z.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequen... | #C | C | /* declare array */
int frequency[26];
int ch;
FILE* txt_file = fopen ("a_text_file.txt", "rt");
/* init the freq table: */
for (ch = 0; ch < 26; ch++)
frequency[ch] = 0;
while (1) {
ch = fgetc(txt_file);
if (ch == EOF) break; /* end of file or read error. EOF is typically -1 */
/* assuming ASCII... |
http://rosettacode.org/wiki/List_comprehensions | List comprehensions | A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name.
Some attributes of a list comprehension are:
They should be distinct from (nested) for loops and the use of map and filter functio... | #Prolog | Prolog | % We need operators
:- op(700, xfx, <-).
:- op(450, xfx, ..).
:- op(1100, yfx, &).
% use for explicit list usage
my_bind(V, [H|_]) :- V = H.
my_bind(V, [_|T]) :- my_bind(V, T).
% we need to define the intervals of numbers
Vs <- M..N :-
integer(M),
integer(N),
M =< N,
between(M, N, Vs).
% for explicit l... |
http://rosettacode.org/wiki/Loops/For | Loops/For | “For” loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code.
Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers.
... | #XPL0 | XPL0 | code ChOut=8, CrLf=9;
int I, J;
for I:= 1 to 5 do
[for J:= 1 to I do
ChOut(0, ^*);
CrLf(0);
] |
http://rosettacode.org/wiki/Left_factorials | Left factorials | Left factorials, !n, may refer to either subfactorials or to factorial sums;
the same notation can be confusingly seen being used for the two different definitions.
Sometimes, subfactorials (also known as derangements) may use any of the notations:
!n`
!n
n¡
(It may not be vis... | #Lua | Lua | -- Lua bindings for GNU bc
require("bc")
-- Return table of factorials from 0 to n
function facsUpTo (n)
local f, fList = bc.number(1), {}
fList[0] = 1
for i = 1, n do
f = bc.mul(f, i)
fList[i] = f
end
return fList
end
-- Return left factorial of n
function leftFac (n)
local ... |
http://rosettacode.org/wiki/Linear_congruential_generator | Linear congruential generator | The linear congruential generator is a very simple example of a random number generator.
All linear congruential generators use this formula:
r
n
+
1
=
a
×
r
n
+
c
(
mod
m
)
{\displaystyle r_{n+1}=a\times r_{n}+c{\pmod {m}}}
Where:
r
0
{\displaystyle r_{0}}
is a seed.
r
1
... | #Icon_and_Unicon | Icon and Unicon | link printf
procedure main()
printf(" BSD MS\n")
every 1 to 10 do
printf("%10s %10s\n",rand_BSD(),rand_MS())
end
procedure srand_BSD(x) #: seed random
static seed
return seed := \x | \seed | 0 # parm or seed or zero if none
end
procedure rand_BSD() #: lcrn... |
http://rosettacode.org/wiki/Leonardo_numbers | Leonardo numbers |
Leonardo numbers are also known as the Leonardo series.
The Leonardo numbers are a sequence of numbers defined by:
L(0) = 1 [1st equation]
L(1) = 1 [2nd equation]
L(n) = L(n-1) + L(n-2) + 1 ... | #Vlang | Vlang | fn leonardo(n int, l0 int, l1 int, add int) []int {
mut leo := []int{len: n}
leo[0] = l0
leo[1] = l1
for i := 2; i < n; i++ {
leo[i] = leo[i - 1] + leo[i - 2] + add
}
return leo
}
fn main() {
println("The first 25 Leonardo numbers with L[0] = 1, L[1] = 1 and add number = 1 are:")
... |
http://rosettacode.org/wiki/Leonardo_numbers | Leonardo numbers |
Leonardo numbers are also known as the Leonardo series.
The Leonardo numbers are a sequence of numbers defined by:
L(0) = 1 [1st equation]
L(1) = 1 [2nd equation]
L(n) = L(n-1) + L(n-2) + 1 ... | #Wren | Wren | var leonardo = Fn.new { |first, add, limit|
var leo = List.filled(limit, 0)
leo[0] = first[0]
leo[1] = first[1]
for (i in 2...limit) leo[i] = leo[i-1] + leo[i-2] + add
return leo
}
System.print("The first 25 Leonardo numbers with L(0) = 1, L(1) = 1 and Add = 1 are:")
for (l in leonardo.call([1, 1]... |
http://rosettacode.org/wiki/Leap_year | Leap year | Task
Determine whether a given year is a leap year in the Gregorian calendar.
See also
Leap year (wiki)
| #Befunge | Befunge | 0"2("*:3-:1-:2-:"^"-v<
v*%"d"\!%4::,,"is".:<|
>\45*:*%!+#v_ "ton"vv<
v"ear."+550<,,,,*84<$#
>"y pael a ">:#,_$:#@^ |
http://rosettacode.org/wiki/Last_Friday_of_each_month | Last Friday of each month | Task
Write a program or a script that returns the date of the last Fridays of each month of a given year.
The year may be given through any simple input method in your language (command line, std in, etc).
Example of an expected output:
./last_fridays 2012
2012-01-27
2012-02-24
2012-03-30
2012-04-27
2012-05-25
20... | #Action.21 | Action! | ;https://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week#Sakamoto.27s_methods
BYTE FUNC DayOfWeek(INT y BYTE m,d) ;1<=m<=12, y>1752
BYTE ARRAY t=[0 3 2 5 0 3 5 1 4 6 2 4]
BYTE res
IF m<3 THEN
y==-1
FI
res=(y+y/4-y/100+y/400+t(m-1)+d) MOD 7
RETURN (res)
BYTE FUNC IsLeapYear(INT y)
IF y MOD... |
http://rosettacode.org/wiki/Lah_numbers | Lah numbers | Lah numbers, sometimes referred to as Stirling numbers of the third kind, are coefficients of polynomial expansions expressing rising factorials in terms of falling factorials.
Unsigned Lah numbers count the number of ways a set of n elements can be partitioned into k non-empty linearly ordered subsets.
Lah numbers a... | #11l | 11l | F lah(BigInt n, BigInt k)
I k == 1
R factorial(n)
I k == n
R BigInt(1)
I k > n
R BigInt(0)
I k < 1 | n < 1
R BigInt(0)
R (factorial(n) * factorial(n - 1)) I/ (factorial(k) * factorial(k - 1)) I/ factorial(n - k)
print(‘Unsigned Lah numbers: L(n, k):’)
print(‘n/k ’, end' ‘ ’)
L(i... |
http://rosettacode.org/wiki/Last_letter-first_letter | Last letter-first letter | A certain children's game involves starting with a word in a particular category. Each participant in turn says a word, but that word must begin with the final letter of the previous word. Once a word has been given, it cannot be repeated. If an opponent cannot give a word in the category, they fall out of the ga... | #C.2B.2B | C++ | #include <iostream>
#include <string>
#include <vector>
struct last_letter_first_letter {
size_t max_path_length = 0;
size_t max_path_length_count = 0;
std::vector<std::string> max_path_example;
void search(std::vector<std::string>& names, size_t offset) {
if (offset > max_path_length) {
... |
http://rosettacode.org/wiki/Largest_int_from_concatenated_ints | Largest int from concatenated ints | Task
Given a set of positive integers, write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this integer.
Use the following two sets of integers as tests and show your program output here.
{1, 34, 3, 98, 9, 76, 45, 4}
{54,... | #Ada | Ada | function Order(Left, Right: Natural) return Boolean is
( (Img(Left) & Img(Right)) > (Img(Right) & Img(Left)) ); |
http://rosettacode.org/wiki/Largest_number_divisible_by_its_digits | Largest number divisible by its digits | Task
Find the largest base 10 integer whose digits are all different, and is evenly divisible by each of its individual digits.
These numbers are also known as Lynch-Bell numbers, numbers n such that the
(base ten) digits are all different (and do not include zero) and n is divisible by each of it... | #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
namespace LargestNumber {
class Program {
static bool ChkDec(int num) {
HashSet<int> set = new HashSet<int>();
return num.ToString()
.Select(c => c - '0')
.All(d => (d != 0) && (num... |
http://rosettacode.org/wiki/Largest_proper_divisor_of_n | Largest proper divisor of n | Task
a(1) = 1; for n > 1, a(n) = largest proper divisor of n, where n < 101 .
| #Cowgol | Cowgol | include "cowgol.coh";
sub print3(n: uint8) is
print_char(' ');
if n>9 then
print_char('0' + n/10);
else
print_char(' ');
end if;
print_char('0' + n%10);
end sub;
sub lpd(n: uint8): (r: uint8) is
if n <= 1 then
r := 1;
else
r := n - 1;
while r > 0 l... |
http://rosettacode.org/wiki/Largest_proper_divisor_of_n | Largest proper divisor of n | Task
a(1) = 1; for n > 1, a(n) = largest proper divisor of n, where n < 101 .
| #Draco | Draco | proc nonrec lpd(word n) word:
word d;
if n=1 then
1
else
d := n-1;
while n % d /= 0 do d := d-1 od;
d
fi
corp
proc nonrec main() void:
word n;
for n from 1 upto 100 do
write(lpd(n):3);
if n%10 = 0 then writeln() fi
od
corp |
http://rosettacode.org/wiki/Largest_proper_divisor_of_n | Largest proper divisor of n | Task
a(1) = 1; for n > 1, a(n) = largest proper divisor of n, where n < 101 .
| #F.23 | F# |
// Largest proper divisor of n: Nigel Galloway. June 2nd., 2021
let fN g=let rec fN n=let i=Seq.head n in match(g/i,g%i) with (1,_)->1 |(n,0)->n |_->fN(Seq.tail n) in fN(Seq.initInfinite((+)2))
seq{yield 1; yield! seq{2..100}|>Seq.map fN}|>Seq.iter(printf "%d "); printfn ""
|
http://rosettacode.org/wiki/Least_common_multiple | Least common multiple | Least common multiple
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Compute the least common multiple (LCM) of two integers.
Given m and n, the least common multiple is the smallest positive integer that has both m and n as factor... | #BASIC | BASIC | 10 DEF FN MOD(A) = INT((A / B - INT(A / B)) * B + .05) * SGN(A / B)
20 INPUT"M=";M%
30 INPUT"N=";N%
40 GOSUB 100
50 PRINT R
60 END
100 REM LEAST COMMON MULTIPLE M% N%
110 R = 0
120 IF M% = 0 OR N% = 0 THEN RETURN
130 A% = M% : B% = N% : GOSUB 200"GCD
140 R = ABS(M%*N%)/R
150 RETURN
200 REM GCD ITERATIVE EUCLID A% B... |
http://rosettacode.org/wiki/Least_common_multiple | Least common multiple | Least common multiple
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Compute the least common multiple (LCM) of two integers.
Given m and n, the least common multiple is the smallest positive integer that has both m and n as factor... | #BASIC256 | BASIC256 | function mcm (m, n)
if m = 0 or n = 0 then return 0
if m < n then
t = m : m = n : n = t
end if
cont = 0
do
cont += 1
until (m * cont) mod n = 0
return m * cont
end function
print "lcm( 12, 18) = "; mcm( 12, -18)
print "lcm( 15, 12) = "; mcm( 15, 12)
print "lcm(-10, -14) = "; mcm(-10, -14)
print "lcm( ... |
http://rosettacode.org/wiki/Latin_Squares_in_reduced_form | Latin Squares in reduced form | A Latin Square is in its reduced form if the first row and first column contain items in their natural order. The order n is the number of items. For any given n there is a set of reduced Latin Squares whose size increases rapidly with n. g is a number which identifies a unique element within the set of reduced Latin S... | #Kotlin | Kotlin | typealias Matrix = MutableList<MutableList<Int>>
fun dList(n: Int, sp: Int): Matrix {
val start = sp - 1 // use 0 basing
val a = generateSequence(0) { it + 1 }.take(n).toMutableList()
a[start] = a[0].also { a[0] = a[start] }
a.subList(1, a.size).sort()
val first = a[1]
// recursive closure... |
http://rosettacode.org/wiki/Law_of_cosines_-_triples | Law of cosines - triples | The Law of cosines states that for an angle γ, (gamma) of any triangle, if the sides adjacent to the angle are A and B and the side opposite is C; then the lengths of the sides are related by this formula:
A2 + B2 - 2ABcos(γ) = C2
Specific angles
For an angle of of 90º this becomes the more familiar ... | #Kotlin | Kotlin | // Version 1.2.70
val squares13 = mutableMapOf<Int, Int>()
val squares10000 = mutableMapOf<Int, Int>()
class Trio(val a: Int, val b: Int, val c: Int) {
override fun toString() = "($a $b $c)"
}
fun init() {
for (i in 1..13) squares13.put(i * i, i)
for (i in 1..10000) squares10000.put(i * i, i)
}
fun ... |
http://rosettacode.org/wiki/Levenshtein_distance | Levenshtein distance |
This page uses content from Wikipedia. The original article was at Levenshtein distance. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In information theory and computer science, the Levenshtein ... | #Delphi | Delphi |
program Levenshtein_distanceTest;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils,
Math;
function Levenshtein_distance(s, t: string): integer;
var
d: array of array of integer;
i, j, cost: integer;
begin
SetLength(d, Length(s) + 1);
for i := Low(d) to High(d) do
begin
SetLength(d[i], Leng... |
http://rosettacode.org/wiki/Letter_frequency | Letter frequency | Task
Open a text file and count the occurrences of each letter.
Some of these programs count all characters (including punctuation),
but some only count letters A to Z.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequen... | #C.23 | C# | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Program
{
static SortedDictionary<TItem, int> GetFrequencies<TItem>(IEnumerable<TItem> items)
{
var dictionary = new SortedDictionary<TItem, int>();
foreach (var item in items)
{
if (d... |
http://rosettacode.org/wiki/List_comprehensions | List comprehensions | A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name.
Some attributes of a list comprehension are:
They should be distinct from (nested) for loops and the use of map and filter functio... | #Python | Python | [(x,y,z) for x in xrange(1,n+1) for y in xrange(x,n+1) for z in xrange(y,n+1) if x**2 + y**2 == z**2] |
http://rosettacode.org/wiki/Loops/For | Loops/For | “For” loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code.
Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers.
... | #Z80_Assembly | Z80 Assembly | org &4000 ; put code at memory address 0x4000
wr_char equ &bb5a ; write ASCII character in register A to screen
; (jumps into CPC ROM)
; put registers on stack so we can return to BASIC later
push bc
push de
push hl
ld b,5 ; loop from 5 to 1
row:
push bc ; save outer loop variable
; calculate inner loop... |
http://rosettacode.org/wiki/Left_factorials | Left factorials | Left factorials, !n, may refer to either subfactorials or to factorial sums;
the same notation can be confusingly seen being used for the two different definitions.
Sometimes, subfactorials (also known as derangements) may use any of the notations:
!n`
!n
n¡
(It may not be vis... | #Maple | Maple | left_factorial := n -> add(k!, k = 1 .. n - 1);
seq(left_factorial(i), i = 1 .. 10);
seq(left_factorial(i), i = 20 .. 110, 10);
seq(length(left_factorial(i)), i = 1000 .. 10000, 1000); |
http://rosettacode.org/wiki/Left_factorials | Left factorials | Left factorials, !n, may refer to either subfactorials or to factorial sums;
the same notation can be confusingly seen being used for the two different definitions.
Sometimes, subfactorials (also known as derangements) may use any of the notations:
!n`
!n
n¡
(It may not be vis... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | left[n_] := left[n] = Sum[k!, {k, 0, n - 1}]
Print["left factorials 0 through 10:"]
Print[left /@ Range[0, 10] // TableForm]
Print["left factorials 20 through 110, by tens:"]
Print[left /@ Range[20, 110, 10] // TableForm]
Print["Digits in left factorials 1,000 through 10,000, by thousands:"]
Print[Length[IntegerDigits[... |
http://rosettacode.org/wiki/Linear_congruential_generator | Linear congruential generator | The linear congruential generator is a very simple example of a random number generator.
All linear congruential generators use this formula:
r
n
+
1
=
a
×
r
n
+
c
(
mod
m
)
{\displaystyle r_{n+1}=a\times r_{n}+c{\pmod {m}}}
Where:
r
0
{\displaystyle r_{0}}
is a seed.
r
1
... | #J | J | lcg=: adverb define
0 m lcg y NB. default seed of 0
:
'a c mod'=. x: m
}. (mod | c + a * ])^:(<y+1) x
)
rand_bsd=: (1103515245 12345 , <.2^31) lcg
rand_ms=: (2^16) <.@:%~ (214013 2531011 , <.2^31) lcg |
http://rosettacode.org/wiki/Leonardo_numbers | Leonardo numbers |
Leonardo numbers are also known as the Leonardo series.
The Leonardo numbers are a sequence of numbers defined by:
L(0) = 1 [1st equation]
L(1) = 1 [2nd equation]
L(n) = L(n-1) + L(n-2) + 1 ... | #Yabasic | Yabasic | limit = 25
sub leonardo(L0, L1, suma, texto$)
local i
print "Numeros de " + texto$, " (", L0, ",", L1, ",", suma, "):"
for i = 1 to limit
if i = 1 then print L0, " ";
elsif i = 2 then print L1, " ";
else
print L0 + L1 + suma, " ";
tmp = L0
L0 = L1
L1 = tmp + L1 + suma
endif
next i
print chr$(... |
http://rosettacode.org/wiki/Leonardo_numbers | Leonardo numbers |
Leonardo numbers are also known as the Leonardo series.
The Leonardo numbers are a sequence of numbers defined by:
L(0) = 1 [1st equation]
L(1) = 1 [2nd equation]
L(n) = L(n-1) + L(n-2) + 1 ... | #XPL0 | XPL0 | int N, L, L0, L1, Add;
[Text(0, "Enter L(0), L(1), Add: ");
L0:= IntIn(0);
L1:= IntIn(0);
Add:= IntIn(0);
IntOut(0, L0); ChOut(0, ^ );
IntOut(0, L1); ChOut(0, ^ );
for N:= 3 to 25 do
[L:= L1 + L0 + Add;
IntOut(0, L); ChOut(0, ^ );
L0:= L1;
L1:= L;
];
] |
http://rosettacode.org/wiki/Leap_year | Leap year | Task
Determine whether a given year is a leap year in the Gregorian calendar.
See also
Leap year (wiki)
| #Bracmat | Bracmat | ( leap-year
=
. mod$(!arg.100):0
& `(mod$(!arg.400):0) { The backtick skips the remainder of the OR operation,
even if the tested condition fails. }
| mod$(!arg.4):0
)
& 1600 1700 1899 1900 2000 2006 2012:?tests
& whl
' ( !tests:%?test ?tests
& ( le... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.