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/Fast_Fourier_transform
Fast Fourier transform
Task Calculate the   FFT   (Fast Fourier Transform)   of an input sequence. The most general case allows for complex numbers at the input and results in a sequence of equal length, again of complex numbers. If you need to restrict yourself to real numbers, the output should be the magnitude   (i.e.:   sqrt(re2 + im2))   of the complex result. The classic version is the recursive Cooley–Tukey FFT. Wikipedia has pseudo-code for that. Further optimizations are possible but not required.
#FreeBASIC
FreeBASIC
'Graphic fast Fourier transform demo, 'press any key for the next image. '131072 samples: the FFT is fast indeed.   'screen resolution const dW = 800, dH = 600 '-------------------------------------- type samples declare constructor (byval p as integer)   'sw = 0 forward transform 'sw = 1 reverse transform declare sub FFT (byval sw as integer)   'draw mythical birds declare sub oiseau ()   'plot frequency and amplitude declare sub famp ()   'plot transformed samples declare sub bird ()   as double x(any), y(any) as integer fl, m, n, n2 end type   constructor samples (byval p as integer) m = p 'number of points n = 1 shl p n2 = n shr 1 'real and complex values redim x(n - 1), y(n - 1) end constructor     '-------------------------------------- 'in-place complex-to-complex FFT adapted from '[ http://paulbourke.net/miscellaneous/dft/ ]   sub samples.FFT (byval sw as integer) dim as double c1, c2, t1, t2, u1, u2, v dim as integer i, j = 0, k, L, l1, l2   'bit reversal sorting for i = 0 to n - 2 if i < j then swap x(i), x(j) swap y(i), y(j) end if   k = n2 while k <= j j -= k: k shr= 1 wend j += k next i   'initial cosine & sine c1 = -1.0 c2 = 0.0 'loop for each stage l2 = 1 for L = 1 to m l1 = l2: l2 shl= 1   'initial vertex u1 = 1.0 u2 = 0.0 'loop for each sub DFT for k = 1 to l1 'butterfly dance for i = k - 1 to n - 1 step l2 j = i + l1 t1 = u1 * x(j) - u2 * y(j) t2 = u1 * y(j) + u2 * x(j) x(j) = x(i) - t1 y(j) = y(i) - t2 x(i) += t1 y(i) += t2 next i   'next polygon vertex v = u1 * c1 - u2 * c2 u2 = u1 * c2 + u2 * c1 u1 = v next k   'half-angle sine c2 = sqr((1.0 - c1) * .5) if sw = 0 then c2 = -c2 'half-angle cosine c1 = sqr((1.0 + c1) * .5) next L   'scaling for reverse transform if sw then for i = 0 to n - 1 x(i) /= n y(i) /= n next i end if end sub   '-------------------------------------- 'Gumowski-Mira attractors "Oiseaux mythiques" '[ http://www.atomosyd.net/spip.php?article98 ]   sub samples.oiseau dim as double a, b, c, t, u, v, w dim as integer dx, y0, dy, i, k   'bounded non-linearity if fl then a = -0.801 dx = 20: y0 =-1: dy = 12 else a = -0.492 dx = 17: y0 =-3: dy = 14 end if window (-dx, y0-dy)-(dx, y0+dy)   'dissipative coefficient b = 0.967 c = 2 - 2 * a   u = 1: v = 0.517: w = 1   for i = 0 to n - 1 t = u u = b * v + w w = a * u + c * u * u / (1 + u * u) v = w - t   'remove bias t = u - 1.830 x(i) = t y(i) = v k = 5 + point(t, v) pset (t, v), 1 + k mod 14 next i sleep end sub   '-------------------------------------- sub samples.famp dim as double a, s, f = n / dW dim as integer i, k window   k = iif(fl, dW / 5, dW / 3) for i = k to dW step k line (i, 0)-(i, dH), 1 next i   a = 0 k = 0: s = f - 1 for i = 0 to n - 1 a += x(i) * x(i) + y(i) * y(i)   if i > s then a = log(1 + a / f) * 0.045 if k then line -(k, (1 - a) * dH), 15 else pset(0, (1 - a) * dH), 15 end if   a = 0 k += 1: s += f end if next i sleep end sub   sub samples.bird dim as integer dx, y0, dy, i, k   if fl then dx = 20: y0 =-1: dy = 12 else dx = 17: y0 =-3: dy = 14 end if window (-dx, y0-dy)-(dx, y0+dy)   for i = 0 to n - 1 k = 2 + point(x(i), y(i)) pset (x(i), y(i)), 1 + k mod 14 next i sleep end sub   'main '-------------------------------------- dim as integer i, p = 17 'n = 2 ^ p dim as samples z = p   screenres dW, dH, 4, 1   for i = 0 to 1 z.fl = i z.oiseau   'forward z.FFT(0)   'amplitude plot with peaks at the '± winding numbers of the orbits. z.famp   'reverse z.FFT(1)   z.bird cls next i end
http://rosettacode.org/wiki/Factors_of_a_Mersenne_number
Factors of a Mersenne number
A Mersenne number is a number in the form of 2P-1. If P is prime, the Mersenne number may be a Mersenne prime (if P is not prime, the Mersenne number is also not prime). In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before starting a, potentially lengthy, Lucas-Lehmer test. There are very efficient algorithms for determining if a number divides 2P-1 (or equivalently, if 2P mod (the number) = 1). Some languages already have built-in implementations of this exponent-and-mod operation (called modPow or similar). The following is how to implement this modPow yourself: For example, let's compute 223 mod 47. Convert the exponent 23 to binary, you get 10111. Starting with square = 1, repeatedly square it. Remove the top bit of the exponent, and if it's 1 multiply square by the base of the exponentiation (2), then compute square modulo 47. Use the result of the modulo from the last step as the initial value of square in the next step: remove optional square top bit multiply by 2 mod 47 ──────────── ─────── ───────────── ────── 1*1 = 1 1 0111 1*2 = 2 2 2*2 = 4 0 111 no 4 4*4 = 16 1 11 16*2 = 32 32 32*32 = 1024 1 1 1024*2 = 2048 27 27*27 = 729 1 729*2 = 1458 1 Since 223 mod 47 = 1, 47 is a factor of 2P-1. (To see this, subtract 1 from both sides: 223-1 = 0 mod 47.) Since we've shown that 47 is a factor, 223-1 is not prime. Further properties of Mersenne numbers allow us to refine the process even more. Any factor q of 2P-1 must be of the form 2kP+1, k being a positive integer or zero. Furthermore, q must be 1 or 7 mod 8. Finally any potential factor q must be prime. As in other trial division algorithms, the algorithm stops when 2kP+1 > sqrt(N). These primality tests only work on Mersenne numbers where P is prime. For example, M4=15 yields no factors using these techniques, but factors into 3 and 5, neither of which fit 2kP+1. Task Using the above method find a factor of 2929-1 (aka M929) Related tasks   count in factors   prime decomposition   factors of an integer   Sieve of Eratosthenes   primality by trial division   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division See also   Computers in 1948: 2127 - 1       (Note:   This video is no longer available because the YouTube account associated with this video has been terminated.)
#Elixir
Elixir
defmodule Mersenne do def mersenne_factor(p) do limit = :math.sqrt(:math.pow(2, p) - 1) mersenne_loop(p, limit, 1) end   defp mersenne_loop(p, limit, k) when (2*k*p - 1) > limit, do: nil defp mersenne_loop(p, limit, k) do q = 2*k*p + 1 if prime?(q) and rem(q,8) in [1,7] and trial_factor(2,p,q), do: q, else: mersenne_loop(p, limit, k+1) end   defp trial_factor(base, exp, mod) do Integer.digits(exp, 2) |> Enum.reduce(1, fn bit,square -> (square * square * (if bit==1, do: base, else: 1)) |> rem(mod) end) == 1 end   def check_mersenne(p) do IO.write "M#{p} = 2**#{p}-1 is " f = mersenne_factor(p) IO.puts if f, do: "composite with factor #{f}", else: "prime" end   def prime?(n), do: prime?(n, :math.sqrt(n), 2)   defp prime?(_, limit, i) when limit < i, do: true defp prime?(n, limit, i) do if rem(n,i) == 0, do: false, else: prime?(n, limit, i+1) end end   [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,929] |> Enum.each(fn p -> Mersenne.check_mersenne(p) end)
http://rosettacode.org/wiki/Factors_of_a_Mersenne_number
Factors of a Mersenne number
A Mersenne number is a number in the form of 2P-1. If P is prime, the Mersenne number may be a Mersenne prime (if P is not prime, the Mersenne number is also not prime). In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before starting a, potentially lengthy, Lucas-Lehmer test. There are very efficient algorithms for determining if a number divides 2P-1 (or equivalently, if 2P mod (the number) = 1). Some languages already have built-in implementations of this exponent-and-mod operation (called modPow or similar). The following is how to implement this modPow yourself: For example, let's compute 223 mod 47. Convert the exponent 23 to binary, you get 10111. Starting with square = 1, repeatedly square it. Remove the top bit of the exponent, and if it's 1 multiply square by the base of the exponentiation (2), then compute square modulo 47. Use the result of the modulo from the last step as the initial value of square in the next step: remove optional square top bit multiply by 2 mod 47 ──────────── ─────── ───────────── ────── 1*1 = 1 1 0111 1*2 = 2 2 2*2 = 4 0 111 no 4 4*4 = 16 1 11 16*2 = 32 32 32*32 = 1024 1 1 1024*2 = 2048 27 27*27 = 729 1 729*2 = 1458 1 Since 223 mod 47 = 1, 47 is a factor of 2P-1. (To see this, subtract 1 from both sides: 223-1 = 0 mod 47.) Since we've shown that 47 is a factor, 223-1 is not prime. Further properties of Mersenne numbers allow us to refine the process even more. Any factor q of 2P-1 must be of the form 2kP+1, k being a positive integer or zero. Furthermore, q must be 1 or 7 mod 8. Finally any potential factor q must be prime. As in other trial division algorithms, the algorithm stops when 2kP+1 > sqrt(N). These primality tests only work on Mersenne numbers where P is prime. For example, M4=15 yields no factors using these techniques, but factors into 3 and 5, neither of which fit 2kP+1. Task Using the above method find a factor of 2929-1 (aka M929) Related tasks   count in factors   prime decomposition   factors of an integer   Sieve of Eratosthenes   primality by trial division   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division See also   Computers in 1948: 2127 - 1       (Note:   This video is no longer available because the YouTube account associated with this video has been terminated.)
#Erlang
Erlang
  -module(mersene2). -export([prime/1,modpow/3,mf/1]).   mf(P) -> merseneFactor(P,math:sqrt(math:pow(2,P)-1),2).   merseneFactor(P,Limit,Acc) when Acc >= Limit -> io:write("None found"); merseneFactor(P,Limit,Acc) -> Q = 2 * P * Acc + 1, Isprime = prime(Q), Mod = modpow(2,P,Q),   if Isprime == false -> merseneFactor(P,Limit,Acc+1);   Q rem 8 =/= 1 andalso Q rem 8 =/= 7 -> merseneFactor(P,Limit,Acc+1);   Mod == 1 -> io:format("M~w is composite with Factor: ~w~n",[P,Q]);   true -> merseneFactor(P,Limit,Acc+1) end.   modpow(B, E, M) -> modpow(B, E, M, 1).   modpow(_B, E, _M, R) when E =< 0 -> R; modpow(B, E, M, R) -> R1 = case E band 1 =:= 1 of true -> (R * B) rem M; false -> R end, modpow( (B*B) rem M, E bsr 1, M, R1).   prime(N) -> divisors(N, N-1).   divisors(N, 1) -> true; divisors(N, C) -> case N rem C =:= 0 of true -> false; false -> divisors(N, C-1) end.  
http://rosettacode.org/wiki/Farey_sequence
Farey sequence
The   Farey sequence   Fn   of order   n   is the sequence of completely reduced fractions between   0   and   1   which, when in lowest terms, have denominators less than or equal to   n,   arranged in order of increasing size. The   Farey sequence   is sometimes incorrectly called a   Farey series. Each Farey sequence:   starts with the value   0   (zero),   denoted by the fraction     0 1 {\displaystyle {\frac {0}{1}}}   ends with the value   1   (unity),   denoted by the fraction   1 1 {\displaystyle {\frac {1}{1}}} . The Farey sequences of orders   1   to   5   are: F 1 = 0 1 , 1 1 {\displaystyle {\bf {\it {F}}}_{1}={\frac {0}{1}},{\frac {1}{1}}} F 2 = 0 1 , 1 2 , 1 1 {\displaystyle {\bf {\it {F}}}_{2}={\frac {0}{1}},{\frac {1}{2}},{\frac {1}{1}}} F 3 = 0 1 , 1 3 , 1 2 , 2 3 , 1 1 {\displaystyle {\bf {\it {F}}}_{3}={\frac {0}{1}},{\frac {1}{3}},{\frac {1}{2}},{\frac {2}{3}},{\frac {1}{1}}} F 4 = 0 1 , 1 4 , 1 3 , 1 2 , 2 3 , 3 4 , 1 1 {\displaystyle {\bf {\it {F}}}_{4}={\frac {0}{1}},{\frac {1}{4}},{\frac {1}{3}},{\frac {1}{2}},{\frac {2}{3}},{\frac {3}{4}},{\frac {1}{1}}} F 5 = 0 1 , 1 5 , 1 4 , 1 3 , 2 5 , 1 2 , 3 5 , 2 3 , 3 4 , 4 5 , 1 1 {\displaystyle {\bf {\it {F}}}_{5}={\frac {0}{1}},{\frac {1}{5}},{\frac {1}{4}},{\frac {1}{3}},{\frac {2}{5}},{\frac {1}{2}},{\frac {3}{5}},{\frac {2}{3}},{\frac {3}{4}},{\frac {4}{5}},{\frac {1}{1}}} Task   Compute and show the Farey sequence for orders   1   through   11   (inclusive).   Compute and display the   number   of fractions in the Farey sequence for order   100   through   1,000   (inclusive)   by hundreds.   Show the fractions as   n/d   (using the solidus [or slash] to separate the numerator from the denominator). The length   (the number of fractions)   of a Farey sequence asymptotically approaches: 3 × n2   ÷   π {\displaystyle \pi } 2 See also   OEIS sequence   A006842 numerators of Farey series of order 1, 2, ···   OEIS sequence   A006843 denominators of Farey series of order 1, 2, ···   OEIS sequence   A005728 number of fractions in Farey series of order n   MathWorld entry   Farey sequence   Wikipedia   entry   Farey sequence
#langur
langur
val .farey = f(.n) { var .a, .b, .c, .d = 0, 1, 1, .n while[=[[0, 1]]] .c <= .n { val .k = (.n + .b) // .d .a, .b, .c, .d = .c, .d, .k x .c - .a, .k x .d - .b _while ~= [[.a, .b]] } }   writeln "Farey sequence for orders 1 through 11" for .i of 11 { writeln $"\.i:2;: ", join " ", map(f $"\.f[1];/\.f[2];", .farey(.i)) }
http://rosettacode.org/wiki/Farey_sequence
Farey sequence
The   Farey sequence   Fn   of order   n   is the sequence of completely reduced fractions between   0   and   1   which, when in lowest terms, have denominators less than or equal to   n,   arranged in order of increasing size. The   Farey sequence   is sometimes incorrectly called a   Farey series. Each Farey sequence:   starts with the value   0   (zero),   denoted by the fraction     0 1 {\displaystyle {\frac {0}{1}}}   ends with the value   1   (unity),   denoted by the fraction   1 1 {\displaystyle {\frac {1}{1}}} . The Farey sequences of orders   1   to   5   are: F 1 = 0 1 , 1 1 {\displaystyle {\bf {\it {F}}}_{1}={\frac {0}{1}},{\frac {1}{1}}} F 2 = 0 1 , 1 2 , 1 1 {\displaystyle {\bf {\it {F}}}_{2}={\frac {0}{1}},{\frac {1}{2}},{\frac {1}{1}}} F 3 = 0 1 , 1 3 , 1 2 , 2 3 , 1 1 {\displaystyle {\bf {\it {F}}}_{3}={\frac {0}{1}},{\frac {1}{3}},{\frac {1}{2}},{\frac {2}{3}},{\frac {1}{1}}} F 4 = 0 1 , 1 4 , 1 3 , 1 2 , 2 3 , 3 4 , 1 1 {\displaystyle {\bf {\it {F}}}_{4}={\frac {0}{1}},{\frac {1}{4}},{\frac {1}{3}},{\frac {1}{2}},{\frac {2}{3}},{\frac {3}{4}},{\frac {1}{1}}} F 5 = 0 1 , 1 5 , 1 4 , 1 3 , 2 5 , 1 2 , 3 5 , 2 3 , 3 4 , 4 5 , 1 1 {\displaystyle {\bf {\it {F}}}_{5}={\frac {0}{1}},{\frac {1}{5}},{\frac {1}{4}},{\frac {1}{3}},{\frac {2}{5}},{\frac {1}{2}},{\frac {3}{5}},{\frac {2}{3}},{\frac {3}{4}},{\frac {4}{5}},{\frac {1}{1}}} Task   Compute and show the Farey sequence for orders   1   through   11   (inclusive).   Compute and display the   number   of fractions in the Farey sequence for order   100   through   1,000   (inclusive)   by hundreds.   Show the fractions as   n/d   (using the solidus [or slash] to separate the numerator from the denominator). The length   (the number of fractions)   of a Farey sequence asymptotically approaches: 3 × n2   ÷   π {\displaystyle \pi } 2 See also   OEIS sequence   A006842 numerators of Farey series of order 1, 2, ···   OEIS sequence   A006843 denominators of Farey series of order 1, 2, ···   OEIS sequence   A005728 number of fractions in Farey series of order n   MathWorld entry   Farey sequence   Wikipedia   entry   Farey sequence
#Lua
Lua
-- Return farey sequence of order n function farey (n) local a, b, c, d, k = 0, 1, 1, n local farTab = {{a, b}} while c <= n do k = math.floor((n + b) / d) a, b, c, d = c, d, k * c - a, k * d - b table.insert(farTab, {a, b}) end return farTab end   -- Main procedure for i = 1, 11 do io.write(i .. ": ") for _, frac in pairs(farey(i)) do io.write(frac[1] .. "/" .. frac[2] .. " ") end print() end for i = 100, 1000, 100 do print(i .. ": " .. #farey(i) .. " items") end
http://rosettacode.org/wiki/Fairshare_between_two_and_more
Fairshare between two and more
The Thue-Morse sequence is a sequence of ones and zeros that if two people take turns in the given order, the first persons turn for every '0' in the sequence, the second for every '1'; then this is shown to give a fairer, more equitable sharing of resources. (Football penalty shoot-outs for example, might not favour the team that goes first as much if the penalty takers take turns according to the Thue-Morse sequence and took 2^n penalties) The Thue-Morse sequence of ones-and-zeroes can be generated by: "When counting in binary, the digit sum modulo 2 is the Thue-Morse sequence" Sharing fairly between two or more Use this method: When counting base b, the digit sum modulo b is the Thue-Morse sequence of fairer sharing between b people. Task Counting from zero;   using a function/method/routine to express an integer count in base b, sum the digits modulo b to produce the next member of the Thue-Morse fairshare series for b people. Show the first 25 terms of the fairshare sequence:   For two people:   For three people   For five people   For eleven people Related tasks   Non-decimal radices/Convert   Thue-Morse See also   A010060, A053838, A053840: The On-Line Encyclopedia of Integer Sequences® (OEIS®)
#Vlang
Vlang
fn fairshare(n int, base int) []int { mut res := []int{len: n} for i in 0..n { mut j := i mut sum := 0 for j > 0 { sum += j % base j /= base } res[i] = sum % base } return res }   fn turns(n int, fss []int) string { mut m := map[int]int{} for fs in fss { m[fs]++ } mut m2 := map[int]int{} for _,v in m { m2[v]++ } mut res := []int{} mut sum := 0 for k, v in m2 { sum += v res << k } if sum != n { return "only $sum have a turn" } res.sort() mut res2 := []string{len: res.len} for i,_ in res { res2[i] = '${res[i]}' } return res2.join(" or ") }   fn main() { for base in [2, 3, 5, 11] { println("${base:2} : ${fairshare(25, base):2}") } println("\nHow many times does each get a turn in 50000 iterations?") for base in [191, 1377, 49999, 50000, 50001] { t := turns(base, fairshare(50000, base)) println(" With $base people: $t") } }
http://rosettacode.org/wiki/Fairshare_between_two_and_more
Fairshare between two and more
The Thue-Morse sequence is a sequence of ones and zeros that if two people take turns in the given order, the first persons turn for every '0' in the sequence, the second for every '1'; then this is shown to give a fairer, more equitable sharing of resources. (Football penalty shoot-outs for example, might not favour the team that goes first as much if the penalty takers take turns according to the Thue-Morse sequence and took 2^n penalties) The Thue-Morse sequence of ones-and-zeroes can be generated by: "When counting in binary, the digit sum modulo 2 is the Thue-Morse sequence" Sharing fairly between two or more Use this method: When counting base b, the digit sum modulo b is the Thue-Morse sequence of fairer sharing between b people. Task Counting from zero;   using a function/method/routine to express an integer count in base b, sum the digits modulo b to produce the next member of the Thue-Morse fairshare series for b people. Show the first 25 terms of the fairshare sequence:   For two people:   For three people   For five people   For eleven people Related tasks   Non-decimal radices/Convert   Thue-Morse See also   A010060, A053838, A053840: The On-Line Encyclopedia of Integer Sequences® (OEIS®)
#Wren
Wren
import "/fmt" for Fmt import "/sort" for Sort   var fairshare = Fn.new { |n, base| var res = List.filled(n, 0) for (i in 0...n) { var j = i var sum = 0 while (j > 0) { sum = sum + (j%base) j = (j/base).floor } res[i] = sum % base } return res }   var turns = Fn.new { |n, fss| var m = {} for (fs in fss) { var k = m[fs] if (!k) { m[fs] = 1 } else { m[fs] = k + 1 } } var m2 = {} for (k in m.keys) { var v = m[k] var k2 = m2[v] if (!k2) { m2[v] = 1 } else { m2[v] = k2 + 1 } } var res = [] var sum = 0 for (k in m2.keys) { var v = m2[k] sum = sum + v res.add(k) } if (sum != n) return "only %(sum) have a turn" Sort.quick(res) var res2 = List.filled(res.count, "") for (i in 0...res.count) res2[i] = res[i].toString return res2.join(" or ") }   for (base in [2, 3, 5, 11]) { Fmt.print("$2d : $2d", base, fairshare.call(25, base)) } System.print("\nHow many times does each get a turn in 50,000 iterations?") for (base in [191, 1377, 49999, 50000, 50001]) { var t = turns.call(base, fairshare.call(50000, base)) Fmt.print(" With $5d people: $s", base, t) }
http://rosettacode.org/wiki/Faulhaber%27s_triangle
Faulhaber's triangle
Named after Johann Faulhaber, the rows of Faulhaber's triangle are the coefficients of polynomials that represent sums of integer powers, which are extracted from Faulhaber's formula: ∑ k = 1 n k p = 1 p + 1 ∑ j = 0 p ( p + 1 j ) B j n p + 1 − j {\displaystyle \sum _{k=1}^{n}k^{p}={1 \over p+1}\sum _{j=0}^{p}{p+1 \choose j}B_{j}n^{p+1-j}} where B n {\displaystyle B_{n}} is the nth-Bernoulli number. The first 5 rows of Faulhaber's triangle, are: 1 1/2 1/2 1/6 1/2 1/3 0 1/4 1/2 1/4 -1/30 0 1/3 1/2 1/5 Using the third row of the triangle, we have: ∑ k = 1 n k 2 = 1 6 n + 1 2 n 2 + 1 3 n 3 {\displaystyle \sum _{k=1}^{n}k^{2}={1 \over 6}n+{1 \over 2}n^{2}+{1 \over 3}n^{3}} Task show the first 10 rows of Faulhaber's triangle. using the 18th row of Faulhaber's triangle, compute the sum: ∑ k = 1 1000 k 17 {\displaystyle \sum _{k=1}^{1000}k^{17}} (extra credit). See also Bernoulli numbers Evaluate binomial coefficients Faulhaber's formula (Wikipedia) Faulhaber's triangle (PDF)
#Phix
Phix
with javascript_semantics include builtins\pfrac.e -- (0.8.0+) function bernoulli(integer n) sequence a = {} for m=0 to n do a = append(a,{1,m+1}) for j=m to 1 by -1 do a[j] = frac_mul({j,1},frac_sub(a[j+1],a[j])) end for end for if n!=1 then return a[1] end if return frac_uminus(a[1]) end function function binomial(integer n, k) if n<0 or k<0 or n<k then ?9/0 end if if n=0 or k=0 then return 1 end if atom num = 1, denom = 1 for i=k+1 to n do num *= i end for for i=2 to n-k do denom *= i end for return num / denom end function function faulhaber_triangle(integer p, bool asString=true) sequence coeffs = repeat(frac_zero,p+1) for j=0 to p do frac coeff = frac_mul({binomial(p+1,j),p+1},bernoulli(j)) coeffs[p-j+1] = iff(asString?sprintf("%5s",{frac_sprint(coeff)}):coeff) end for return coeffs end function for i=0 to 9 do printf(1,"%s\n",{join(faulhaber_triangle(i)," ")}) end for puts(1,"\n") if platform()!=JS then sequence row18 = faulhaber_triangle(17,false) frac res = frac_zero atom t1 = time()+1 integer lim = 1000 for k=1 to lim do bigatom nn = BA_ONE for i=1 to length(row18) do res = frac_add(res,frac_mul(row18[i],{nn,1})) nn = ba_mul(nn,lim) end for if time()>t1 then printf(1,"calculating, k=%d...\r",k) t1 = time()+1 end if end for printf(1,"%s \n",{frac_sprint(res)}) end if
http://rosettacode.org/wiki/Faulhaber%27s_formula
Faulhaber's formula
In mathematics,   Faulhaber's formula,   named after Johann Faulhaber,   expresses the sum of the p-th powers of the first n positive integers as a (p + 1)th-degree polynomial function of n,   the coefficients involving Bernoulli numbers. Task Generate the first 10 closed-form expressions, starting with p = 0. Related tasks   Bernoulli numbers.   evaluate binomial coefficients. See also   The Wikipedia entry:   Faulhaber's formula.   The Wikipedia entry:   Bernoulli numbers.   The Wikipedia entry:   binomial coefficients.
#Phix
Phix
with javascript_semantics include builtins\pfrac.e -- (0.8.0+) function bernoulli(integer n) sequence a = {} for m=0 to n do a = append(a,{1,m+1}) for j=m to 1 by -1 do a[j] = frac_mul({j,1},frac_sub(a[j+1],a[j])) end for end for if n!=1 then return a[1] end if return frac_uminus(a[1]) end function function binomial(integer n, k) if n<0 or k<0 or n<k then ?9/0 end if if n=0 or k=0 then return 1 end if integer num = 1, denom = 1 for i=k+1 to n do num *= i end for for i=2 to n-k do denom *= i end for return num / denom end function procedure faulhaber(integer p) string res = sprintf("%d : ", p) frac q = {1, p+1} for j=0 to p do frac bj = bernoulli(j) if frac_ne(bj,frac_zero) then frac coeff = frac_mul({binomial(p+1,j),p+1},bj) string s = frac_sprint(coeff) if j=0 then if s="1" then s = "" end if else if s[1]='-' then s[1..1] = " - " else s[1..0] = " + " end if end if res &= s&"n" integer pwr = p+1-j if pwr>1 then res &= sprintf("^%d", pwr) end if end if end for printf(1,"%s\n",{res}) end procedure for i=0 to 9 do faulhaber(i) end for
http://rosettacode.org/wiki/Fibonacci_n-step_number_sequences
Fibonacci n-step number sequences
These number series are an expansion of the ordinary Fibonacci sequence where: For n = 2 {\displaystyle n=2} we have the Fibonacci sequence; with initial values [ 1 , 1 ] {\displaystyle [1,1]} and F k 2 = F k − 1 2 + F k − 2 2 {\displaystyle F_{k}^{2}=F_{k-1}^{2}+F_{k-2}^{2}} For n = 3 {\displaystyle n=3} we have the tribonacci sequence; with initial values [ 1 , 1 , 2 ] {\displaystyle [1,1,2]} and F k 3 = F k − 1 3 + F k − 2 3 + F k − 3 3 {\displaystyle F_{k}^{3}=F_{k-1}^{3}+F_{k-2}^{3}+F_{k-3}^{3}} For n = 4 {\displaystyle n=4} we have the tetranacci sequence; with initial values [ 1 , 1 , 2 , 4 ] {\displaystyle [1,1,2,4]} and F k 4 = F k − 1 4 + F k − 2 4 + F k − 3 4 + F k − 4 4 {\displaystyle F_{k}^{4}=F_{k-1}^{4}+F_{k-2}^{4}+F_{k-3}^{4}+F_{k-4}^{4}} ... For general n > 2 {\displaystyle n>2} we have the Fibonacci n {\displaystyle n} -step sequence - F k n {\displaystyle F_{k}^{n}} ; with initial values of the first n {\displaystyle n} values of the ( n − 1 ) {\displaystyle (n-1)} 'th Fibonacci n {\displaystyle n} -step sequence F k n − 1 {\displaystyle F_{k}^{n-1}} ; and k {\displaystyle k} 'th value of this n {\displaystyle n} 'th sequence being F k n = ∑ i = 1 ( n ) F k − i ( n ) {\displaystyle F_{k}^{n}=\sum _{i=1}^{(n)}{F_{k-i}^{(n)}}} For small values of n {\displaystyle n} , Greek numeric prefixes are sometimes used to individually name each series. Fibonacci n {\displaystyle n} -step sequences n {\displaystyle n} Series name Values 2 fibonacci 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ... 3 tribonacci 1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ... 4 tetranacci 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ... 5 pentanacci 1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ... 6 hexanacci 1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ... 7 heptanacci 1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ... 8 octonacci 1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ... 9 nonanacci 1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ... 10 decanacci 1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ... Allied sequences can be generated where the initial values are changed: The Lucas series sums the two preceding values like the fibonacci series for n = 2 {\displaystyle n=2} but uses [ 2 , 1 ] {\displaystyle [2,1]} as its initial values. Task Write a function to generate Fibonacci n {\displaystyle n} -step number sequences given its initial values and assuming the number of initial values determines how many previous values are summed to make the next number of the series. Use this to print and show here at least the first ten members of the Fibo/tribo/tetra-nacci and Lucas sequences. Related tasks   Fibonacci sequence   Wolfram Mathworld   Hofstadter Q sequence‎   Leonardo numbers Also see   Lucas Numbers - Numberphile (Video)   Tribonacci Numbers (and the Rauzy Fractal) - Numberphile (Video)   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#ERRE
ERRE
  PROGRAM FIBON   ! ! for rosettacode.org !   DIM F[20]   PROCEDURE FIB(TIPO$,F$) FOR I%=0 TO 20 DO F[I%]=0 END FOR B=0 LOOP Q=INSTR(F$,",") B=B+1 IF Q=0 THEN F[B]=VAL(F$) EXIT ELSE F[B]=VAL(MID$(F$,1,Q-1)) F$=MID$(F$,Q+1) END IF END LOOP   PRINT(TIPO$;" =>";) FOR I=B TO 14+B DO IF I<>B THEN PRINT(",";) END IF PRINT(F[I-B+1];) FOR J=(I-B)+1 TO I DO F[I+1]=F[I+1]+F[J] END FOR END FOR PRINT END PROCEDURE   BEGIN PRINT(CHR$(12);) ! CLS FIB("Fibonacci","1,1") FIB("Tribonacci","1,1,2") FIB("Tetranacci","1,1,2,4") FIB("Lucas","2,1") END PROGRAM  
http://rosettacode.org/wiki/Find_common_directory_path
Find common directory path
Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories. Test your routine using the forward slash '/' character as the directory separator and the following three strings as input paths: '/home/user1/tmp/coverage/test' '/home/user1/tmp/covert/operator' '/home/user1/tmp/coven/members' Note: The resultant path should be the valid directory '/home/user1/tmp' and not the longest common string '/home/user1/tmp/cove'. If your language has a routine that performs this function (even if it does not have a changeable separator character), then mention it as part of the task. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Seed7
Seed7
$ include "seed7_05.s7i";   const func integer: commonLen (in array string: names, in char: sep) is func result var integer: result is -1; local var integer: index is 0; var integer: pos is 1; begin if length(names) <> 0 then repeat for index range 1 to length(names) do if pos > length(names[index]) or names[index][pos] <> names[1][pos] then decr(pos); while pos >= 1 and names[1][pos] <> sep do decr(pos); end while; if pos > 1 then decr(pos); end if; result := pos; end if; end for; incr(pos); until result <> -1; end if; end func;   const proc: main is func local var integer: length is 0; const array string: names is [] ("/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members") begin length := commonLen(names, '/'); if length = 0 then writeln("No common path"); else writeln("Common path: " <& names[1][.. length]); end if; end func;
http://rosettacode.org/wiki/Find_common_directory_path
Find common directory path
Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories. Test your routine using the forward slash '/' character as the directory separator and the following three strings as input paths: '/home/user1/tmp/coverage/test' '/home/user1/tmp/covert/operator' '/home/user1/tmp/coven/members' Note: The resultant path should be the valid directory '/home/user1/tmp' and not the longest common string '/home/user1/tmp/cove'. If your language has a routine that performs this function (even if it does not have a changeable separator character), then mention it as part of the task. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Sidef
Sidef
var dirs = %w( /home/user1/tmp/coverage/test /home/user1/tmp/covert/operator /home/user1/tmp/coven/members );   var unique_pref = dirs.map{.split('/')}.abbrev.min_by{.len}; var common_dir = [unique_pref, unique_pref.pop][0].join('/'); say common_dir; # => /home/user1/tmp
http://rosettacode.org/wiki/Filter
Filter
Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
#Fantom
Fantom
  class Main { Void main () { items := [1, 2, 3, 4, 5, 6, 7, 8] // create a new list with just the even numbers evens := items.findAll |i| { i.isEven } // display the result echo (evens.join(",")) } }  
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) The   FizzBuzz   problem was presented as the lowest level of comprehension required to illustrate adequacy. Also see   (a blog)   dont-overthink-fizzbuzz   (a blog)   fizzbuzz-the-programmers-stairway-to-heaven
#Inform_6
Inform 6
[ Main i; for(i = 1: i <= 100: i++) { if(i % 3 == 0) print "Fizz"; if(i % 5 == 0) print "Buzz"; if(i % 3 ~= 0 && i % 5 ~= 0) print i;   print "^"; } ];
http://rosettacode.org/wiki/File_size
File size
Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
#Tcl
Tcl
file size input.txt file size /input.txt
http://rosettacode.org/wiki/File_size
File size
Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
#Toka
Toka
" input.txt" "R" file.open dup file.size . file.close " /input.txt" "R" file.open dup file.size . file.close
http://rosettacode.org/wiki/File_size
File size
Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
#TorqueScript
TorqueScript
%File = new FileObject(); %File.openForRead("input.txt");   while(!%File.isEOF()) { %Length += strLen(%File.readLine()); }   %File.close(); %File.delete();
http://rosettacode.org/wiki/File_input/output
File input/output
File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file into a variable   how to write a variable's contents into a file Oneliners that skip the intermediate variable are of secondary interest — operating systems have copy commands for that.
#Logo
Logo
to copy :from :to openread :from openwrite :to setread :from setwrite :to until [eof?] [print readrawline] closeall end   copy "input.txt "output.txt
http://rosettacode.org/wiki/File_input/output
File input/output
File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file into a variable   how to write a variable's contents into a file Oneliners that skip the intermediate variable are of secondary interest — operating systems have copy commands for that.
#Lua
Lua
  inFile = io.open("input.txt", "r") data = inFile:read("*all") -- may be abbreviated to "*a"; -- other options are "*line", -- or the number of characters to read. inFile:close()   outFile = io.open("output.txt", "w") outfile:write(data) outfile:close()   -- Oneliner version: io.open("output.txt", "w"):write(io.open("input.txt", "r"):read("*a"))  
http://rosettacode.org/wiki/Fibonacci_word
Fibonacci word
The   Fibonacci Word   may be created in a manner analogous to the   Fibonacci Sequence   as described here: Define   F_Word1   as   1 Define   F_Word2   as   0 Form     F_Word3   as   F_Word2     concatenated with   F_Word1   i.e.:   01 Form     F_Wordn   as   F_Wordn-1   concatenated with   F_wordn-2 Task Perform the above steps for     n = 37. You may display the first few but not the larger values of   n. {Doing so will get the task's author into trouble with them what be (again!).} Instead, create a table for   F_Words   1   to   37   which shows:   The number of characters in the word   The word's Entropy Related tasks   Fibonacci word/fractal   Entropy   Entropy/Narcissist
#PureBasic
PureBasic
EnableExplicit Define fwx$, n.i NewMap uchar.i()   Macro RowPrint(ns,ls,es,ws) Print(RSet(ns,4," ")+RSet(ls,12," ")+" "+es+" ") : If Len(ws)<55 : PrintN(ws) : Else : PrintN("...") : EndIf EndMacro   Procedure.d nlog2(x.d) : ProcedureReturn Log(x)/Log(2) : EndProcedure   Procedure countchar(s$, Map uchar()) If Len(s$) uchar(Left(s$,1))=CountString(s$,Left(s$,1)) : s$=RemoveString(s$,Left(s$,1)) ProcedureReturn countchar(s$, uchar()) EndIf EndProcedure   Procedure.d ce(fw$) Define e.d Shared uchar() countchar(fw$,uchar()) ForEach uchar() : e-uchar()/Len(fw$)*nlog2(uchar()/Len(fw$)) : Next ProcedureReturn e EndProcedure   Procedure.s fw(n.i,a$="0",b$="1",m.i=2) Select n : Case 1 : ProcedureReturn a$ : Case 2 : ProcedureReturn b$ : EndSelect If m<n : ProcedureReturn fw(n,b$+a$,a$,m+1) : EndIf ProcedureReturn Mid(a$,3)+ReverseString(Left(a$,2)) EndProcedure   OpenConsole() PrintN(" N Length Entropy Word") For n=1 To 37 : fwx$=fw(n) : RowPrint(Str(n),Str(Len(fwx$)),StrD(ce(fwx$),15),fwx$) : Next Input()
http://rosettacode.org/wiki/FASTA_format
FASTA format
In bioinformatics, long character strings are often encoded in a format called FASTA. A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line. Task Write a program that reads a FASTA file such as: >Rosetta_Example_1 THERECANBENOSPACE >Rosetta_Example_2 THERECANBESEVERAL LINESBUTTHEYALLMUST BECONCATENATED Output: Rosetta_Example_1: THERECANBENOSPACE Rosetta_Example_2: THERECANBESEVERALLINESBUTTHEYALLMUSTBECONCATENATED Note that a high-quality implementation will not hold the entire file in memory at once; real FASTA files can be multiple gigabytes in size.
#XPL0
XPL0
proc Echo; \Echo line of characters from file to screen int Ch; def LF=$0A, EOF=$1A; [loop [Ch:= ChIn(3); case Ch of EOF: exit; LF: quit other ChOut(0, Ch); ]; ];   int Ch; [FSet(FOpen("fasta.txt", 0), ^i); loop [Ch:= ChIn(3); if Ch = ^> then [CrLf(0); Echo; Text(0, ": "); ] else ChOut(0, Ch); Echo; ]; ]
http://rosettacode.org/wiki/FASTA_format
FASTA format
In bioinformatics, long character strings are often encoded in a format called FASTA. A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line. Task Write a program that reads a FASTA file such as: >Rosetta_Example_1 THERECANBENOSPACE >Rosetta_Example_2 THERECANBESEVERAL LINESBUTTHEYALLMUST BECONCATENATED Output: Rosetta_Example_1: THERECANBENOSPACE Rosetta_Example_2: THERECANBESEVERALLINESBUTTHEYALLMUSTBECONCATENATED Note that a high-quality implementation will not hold the entire file in memory at once; real FASTA files can be multiple gigabytes in size.
#zkl
zkl
fcn fasta(data){ // a lazy cruise through a FASTA file fcn(w){ // one string at a time, -->False garbage at front of file line:=w.next().strip(); if(line[0]==">") w.pump(line[1,*]+": ",'wrap(l){ if(l[0]==">") { w.push(l); Void.Stop } else l.strip() }) }.fp(data.walker()) : Utils.Helpers.wap(_); }
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: Fn = Fn+2 - Fn+1, if n<0 support for negative     n     in the solution is optional. Related tasks   Fibonacci n-step number sequences‎   Leonardo numbers References   Wikipedia, Fibonacci number   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#Ada
Ada
with Ada.Text_IO, Ada.Command_Line;   procedure Fib is   X: Positive := Positive'Value(Ada.Command_Line.Argument(1));   function Fib(P: Positive) return Positive is begin if P <= 2 then return 1; else return Fib(P-1) + Fib(P-2); end if; end Fib;   begin Ada.Text_IO.Put("Fibonacci(" & Integer'Image(X) & " ) = "); Ada.Text_IO.Put_Line(Integer'Image(Fib(X))); end Fib;
http://rosettacode.org/wiki/Factors_of_an_integer
Factors of an integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Compute the   factors   of a positive integer. These factors are the positive integers by which the number being factored can be divided to yield a positive integer result. (Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty;   this task does not require handling of either of these cases). Note that every prime number has two factors:   1   and itself. Related tasks   count in factors   prime decomposition   Sieve of Eratosthenes   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division   sequence: smallest number greater than previous term with exactly n divisors
#AppleScript
AppleScript
-- integerFactors :: Int -> [Int] on integerFactors(n) if n = 1 then {1} else if 1 > n then missing value else set realRoot to n ^ (1 / 2) set intRoot to realRoot as integer set blnPerfectSquare to intRoot = realRoot   -- isFactor :: Int -> Bool script isFactor on |λ|(x) (n mod x) = 0 end |λ| end script   -- Factors up to square root of n, set lows to filter(isFactor, enumFromTo(1, intRoot))   -- integerQuotient :: Int -> Int script integerQuotient on |λ|(x) (n / x) as integer end |λ| end script   -- and quotients of these factors beyond the square root. lows & map(integerQuotient, ¬ items (1 + (blnPerfectSquare as integer)) thru -1 of reverse of lows) end if end integerFactors   --------------------------- TEST ------------------------- on run   integerFactors(120)   --> {1, 2, 3, 4, 5, 6, 8, 10, 12, 15, 20, 24, 30, 40, 60, 120} end run     -------------------- GENERIC FUNCTIONS -------------------   -- enumFromTo :: Int -> Int -> [Int] on enumFromTo(m, n) if n < m then set d to -1 else set d to 1 end if set lst to {} repeat with i from m to n by d set end of lst to i end repeat return lst end enumFromTo   -- filter :: (a -> Bool) -> [a] -> [a] on filter(f, xs) tell mReturn(f) set lst to {} set lng to length of xs repeat with i from 1 to lng set v to item i of xs if |λ|(v, i, xs) then set end of lst to v end repeat return lst end tell end filter   -- map :: (a -> b) -> [a] -> [b] on map(f, xs) tell mReturn(f) set lng to length of xs set lst to {} repeat with i from 1 to lng set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell end map   -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script on mReturn(f) if class of f is script then f else script property |λ| : f end script end if end mReturn
http://rosettacode.org/wiki/Fast_Fourier_transform
Fast Fourier transform
Task Calculate the   FFT   (Fast Fourier Transform)   of an input sequence. The most general case allows for complex numbers at the input and results in a sequence of equal length, again of complex numbers. If you need to restrict yourself to real numbers, the output should be the magnitude   (i.e.:   sqrt(re2 + im2))   of the complex result. The classic version is the recursive Cooley–Tukey FFT. Wikipedia has pseudo-code for that. Further optimizations are possible but not required.
#Frink
Frink
a = FFT[[1,1,1,1,0,0,0,0], 1, -1] println[joinln[format[a, 1, 5]]]  
http://rosettacode.org/wiki/Factors_of_a_Mersenne_number
Factors of a Mersenne number
A Mersenne number is a number in the form of 2P-1. If P is prime, the Mersenne number may be a Mersenne prime (if P is not prime, the Mersenne number is also not prime). In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before starting a, potentially lengthy, Lucas-Lehmer test. There are very efficient algorithms for determining if a number divides 2P-1 (or equivalently, if 2P mod (the number) = 1). Some languages already have built-in implementations of this exponent-and-mod operation (called modPow or similar). The following is how to implement this modPow yourself: For example, let's compute 223 mod 47. Convert the exponent 23 to binary, you get 10111. Starting with square = 1, repeatedly square it. Remove the top bit of the exponent, and if it's 1 multiply square by the base of the exponentiation (2), then compute square modulo 47. Use the result of the modulo from the last step as the initial value of square in the next step: remove optional square top bit multiply by 2 mod 47 ──────────── ─────── ───────────── ────── 1*1 = 1 1 0111 1*2 = 2 2 2*2 = 4 0 111 no 4 4*4 = 16 1 11 16*2 = 32 32 32*32 = 1024 1 1 1024*2 = 2048 27 27*27 = 729 1 729*2 = 1458 1 Since 223 mod 47 = 1, 47 is a factor of 2P-1. (To see this, subtract 1 from both sides: 223-1 = 0 mod 47.) Since we've shown that 47 is a factor, 223-1 is not prime. Further properties of Mersenne numbers allow us to refine the process even more. Any factor q of 2P-1 must be of the form 2kP+1, k being a positive integer or zero. Furthermore, q must be 1 or 7 mod 8. Finally any potential factor q must be prime. As in other trial division algorithms, the algorithm stops when 2kP+1 > sqrt(N). These primality tests only work on Mersenne numbers where P is prime. For example, M4=15 yields no factors using these techniques, but factors into 3 and 5, neither of which fit 2kP+1. Task Using the above method find a factor of 2929-1 (aka M929) Related tasks   count in factors   prime decomposition   factors of an integer   Sieve of Eratosthenes   primality by trial division   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division See also   Computers in 1948: 2127 - 1       (Note:   This video is no longer available because the YouTube account associated with this video has been terminated.)
#Factor
Factor
USING: combinators.short-circuit interpolate io kernel locals math math.bits math.functions math.primes sequences ; IN: rosetta-code.mersenne-factors   : mod-pow-step ( square bit m -- square' ) [ [ sq ] [ [ 2 * ] when ] bi* ] dip mod ;   :: mod-pow ( m q -- n ) 1 :> s! m make-bits <reversed> [ s swap q mod-pow-step s! ] each s ;   : halt-search? ( m q N -- ? ) dupd > [ { [ nip 8 mod [ 1 ] [ 7 ] bi [ = ] 2bi@ or ] [ mod-pow 1 = ] [ nip prime? ] } 2&& ] dip or ;   :: find-mersenne-factor ( m -- factor/f ) 1  :> k! 2 m * 1 +  :> q!  ! the tentative factor. 2 m ^ sqrt :> N  ! upper bound on search. [ m q N halt-search? ] [ k 1 + k! 2 k * m * 1 + q! ] until q N > f q ? ;   : test-mersenne ( m -- ) dup find-mersenne-factor [ [I M${1} is not prime: factor ${0} found.I] ] [ [I No factor found for M${}.I] ] if* nl ;   929 test-mersenne
http://rosettacode.org/wiki/Factors_of_a_Mersenne_number
Factors of a Mersenne number
A Mersenne number is a number in the form of 2P-1. If P is prime, the Mersenne number may be a Mersenne prime (if P is not prime, the Mersenne number is also not prime). In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before starting a, potentially lengthy, Lucas-Lehmer test. There are very efficient algorithms for determining if a number divides 2P-1 (or equivalently, if 2P mod (the number) = 1). Some languages already have built-in implementations of this exponent-and-mod operation (called modPow or similar). The following is how to implement this modPow yourself: For example, let's compute 223 mod 47. Convert the exponent 23 to binary, you get 10111. Starting with square = 1, repeatedly square it. Remove the top bit of the exponent, and if it's 1 multiply square by the base of the exponentiation (2), then compute square modulo 47. Use the result of the modulo from the last step as the initial value of square in the next step: remove optional square top bit multiply by 2 mod 47 ──────────── ─────── ───────────── ────── 1*1 = 1 1 0111 1*2 = 2 2 2*2 = 4 0 111 no 4 4*4 = 16 1 11 16*2 = 32 32 32*32 = 1024 1 1 1024*2 = 2048 27 27*27 = 729 1 729*2 = 1458 1 Since 223 mod 47 = 1, 47 is a factor of 2P-1. (To see this, subtract 1 from both sides: 223-1 = 0 mod 47.) Since we've shown that 47 is a factor, 223-1 is not prime. Further properties of Mersenne numbers allow us to refine the process even more. Any factor q of 2P-1 must be of the form 2kP+1, k being a positive integer or zero. Furthermore, q must be 1 or 7 mod 8. Finally any potential factor q must be prime. As in other trial division algorithms, the algorithm stops when 2kP+1 > sqrt(N). These primality tests only work on Mersenne numbers where P is prime. For example, M4=15 yields no factors using these techniques, but factors into 3 and 5, neither of which fit 2kP+1. Task Using the above method find a factor of 2929-1 (aka M929) Related tasks   count in factors   prime decomposition   factors of an integer   Sieve of Eratosthenes   primality by trial division   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division See also   Computers in 1948: 2127 - 1       (Note:   This video is no longer available because the YouTube account associated with this video has been terminated.)
#Forth
Forth
: prime? ( odd -- ? ) 3 begin 2dup dup * >= while 2dup mod 0= if 2drop false exit then 2 + repeat 2drop true ;   : 2-exp-mod { e m -- 2^e mod m } 1 0 30 do e 1 i lshift >= if dup * e 1 i lshift and if 2* then m mod then -1 +loop ;   : factor-mersenne ( exponent -- factor ) 16384 over / dup 2 < abort" Exponent too large!" 1 do dup i * 2* 1+ ( q ) dup prime? if dup 7 and dup 1 = swap 7 = or if 2dup 2-exp-mod 1 = if nip unloop exit then then then drop loop drop 0 ;   929 factor-mersenne . \ 13007 4423 factor-mersenne . \ 0
http://rosettacode.org/wiki/Farey_sequence
Farey sequence
The   Farey sequence   Fn   of order   n   is the sequence of completely reduced fractions between   0   and   1   which, when in lowest terms, have denominators less than or equal to   n,   arranged in order of increasing size. The   Farey sequence   is sometimes incorrectly called a   Farey series. Each Farey sequence:   starts with the value   0   (zero),   denoted by the fraction     0 1 {\displaystyle {\frac {0}{1}}}   ends with the value   1   (unity),   denoted by the fraction   1 1 {\displaystyle {\frac {1}{1}}} . The Farey sequences of orders   1   to   5   are: F 1 = 0 1 , 1 1 {\displaystyle {\bf {\it {F}}}_{1}={\frac {0}{1}},{\frac {1}{1}}} F 2 = 0 1 , 1 2 , 1 1 {\displaystyle {\bf {\it {F}}}_{2}={\frac {0}{1}},{\frac {1}{2}},{\frac {1}{1}}} F 3 = 0 1 , 1 3 , 1 2 , 2 3 , 1 1 {\displaystyle {\bf {\it {F}}}_{3}={\frac {0}{1}},{\frac {1}{3}},{\frac {1}{2}},{\frac {2}{3}},{\frac {1}{1}}} F 4 = 0 1 , 1 4 , 1 3 , 1 2 , 2 3 , 3 4 , 1 1 {\displaystyle {\bf {\it {F}}}_{4}={\frac {0}{1}},{\frac {1}{4}},{\frac {1}{3}},{\frac {1}{2}},{\frac {2}{3}},{\frac {3}{4}},{\frac {1}{1}}} F 5 = 0 1 , 1 5 , 1 4 , 1 3 , 2 5 , 1 2 , 3 5 , 2 3 , 3 4 , 4 5 , 1 1 {\displaystyle {\bf {\it {F}}}_{5}={\frac {0}{1}},{\frac {1}{5}},{\frac {1}{4}},{\frac {1}{3}},{\frac {2}{5}},{\frac {1}{2}},{\frac {3}{5}},{\frac {2}{3}},{\frac {3}{4}},{\frac {4}{5}},{\frac {1}{1}}} Task   Compute and show the Farey sequence for orders   1   through   11   (inclusive).   Compute and display the   number   of fractions in the Farey sequence for order   100   through   1,000   (inclusive)   by hundreds.   Show the fractions as   n/d   (using the solidus [or slash] to separate the numerator from the denominator). The length   (the number of fractions)   of a Farey sequence asymptotically approaches: 3 × n2   ÷   π {\displaystyle \pi } 2 See also   OEIS sequence   A006842 numerators of Farey series of order 1, 2, ···   OEIS sequence   A006843 denominators of Farey series of order 1, 2, ···   OEIS sequence   A005728 number of fractions in Farey series of order n   MathWorld entry   Farey sequence   Wikipedia   entry   Farey sequence
#Maple
Maple
#Displays terms in Farey_sequence of order n farey_sequence := proc(n) local a,b,c,d,k; a,b,c,d := 0,1,1,n; printf("%d/%d", a,b); while c <= n do k := iquo(n+b,d); a,b,c,d := c,d,c*k-a,d*k-b; printf(", %d/%d", a,b) end do; printf("\n"); end proc:   #Returns the length of a Farey sequence farey_len := proc(n) return 1 + add(NumberTheory:-Totient(k), k=1..n); end proc;   for i to 11 do farey_sequence(i); end do; printf("\n"); for j from 100 to 1000 by 100 do printf("%d\n", farey_len(j)); end do;
http://rosettacode.org/wiki/Farey_sequence
Farey sequence
The   Farey sequence   Fn   of order   n   is the sequence of completely reduced fractions between   0   and   1   which, when in lowest terms, have denominators less than or equal to   n,   arranged in order of increasing size. The   Farey sequence   is sometimes incorrectly called a   Farey series. Each Farey sequence:   starts with the value   0   (zero),   denoted by the fraction     0 1 {\displaystyle {\frac {0}{1}}}   ends with the value   1   (unity),   denoted by the fraction   1 1 {\displaystyle {\frac {1}{1}}} . The Farey sequences of orders   1   to   5   are: F 1 = 0 1 , 1 1 {\displaystyle {\bf {\it {F}}}_{1}={\frac {0}{1}},{\frac {1}{1}}} F 2 = 0 1 , 1 2 , 1 1 {\displaystyle {\bf {\it {F}}}_{2}={\frac {0}{1}},{\frac {1}{2}},{\frac {1}{1}}} F 3 = 0 1 , 1 3 , 1 2 , 2 3 , 1 1 {\displaystyle {\bf {\it {F}}}_{3}={\frac {0}{1}},{\frac {1}{3}},{\frac {1}{2}},{\frac {2}{3}},{\frac {1}{1}}} F 4 = 0 1 , 1 4 , 1 3 , 1 2 , 2 3 , 3 4 , 1 1 {\displaystyle {\bf {\it {F}}}_{4}={\frac {0}{1}},{\frac {1}{4}},{\frac {1}{3}},{\frac {1}{2}},{\frac {2}{3}},{\frac {3}{4}},{\frac {1}{1}}} F 5 = 0 1 , 1 5 , 1 4 , 1 3 , 2 5 , 1 2 , 3 5 , 2 3 , 3 4 , 4 5 , 1 1 {\displaystyle {\bf {\it {F}}}_{5}={\frac {0}{1}},{\frac {1}{5}},{\frac {1}{4}},{\frac {1}{3}},{\frac {2}{5}},{\frac {1}{2}},{\frac {3}{5}},{\frac {2}{3}},{\frac {3}{4}},{\frac {4}{5}},{\frac {1}{1}}} Task   Compute and show the Farey sequence for orders   1   through   11   (inclusive).   Compute and display the   number   of fractions in the Farey sequence for order   100   through   1,000   (inclusive)   by hundreds.   Show the fractions as   n/d   (using the solidus [or slash] to separate the numerator from the denominator). The length   (the number of fractions)   of a Farey sequence asymptotically approaches: 3 × n2   ÷   π {\displaystyle \pi } 2 See also   OEIS sequence   A006842 numerators of Farey series of order 1, 2, ···   OEIS sequence   A006843 denominators of Farey series of order 1, 2, ···   OEIS sequence   A005728 number of fractions in Farey series of order n   MathWorld entry   Farey sequence   Wikipedia   entry   Farey sequence
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
farey[n_]:=StringJoin@@Riffle[ToString@Numerator[#]<>"/"<>ToString@Denominator[#]&/@FareySequence[n],", "] TableForm[farey/@Range[11]] Table[Length[FareySequence[n]], {n, 100, 1000, 100}]
http://rosettacode.org/wiki/Fairshare_between_two_and_more
Fairshare between two and more
The Thue-Morse sequence is a sequence of ones and zeros that if two people take turns in the given order, the first persons turn for every '0' in the sequence, the second for every '1'; then this is shown to give a fairer, more equitable sharing of resources. (Football penalty shoot-outs for example, might not favour the team that goes first as much if the penalty takers take turns according to the Thue-Morse sequence and took 2^n penalties) The Thue-Morse sequence of ones-and-zeroes can be generated by: "When counting in binary, the digit sum modulo 2 is the Thue-Morse sequence" Sharing fairly between two or more Use this method: When counting base b, the digit sum modulo b is the Thue-Morse sequence of fairer sharing between b people. Task Counting from zero;   using a function/method/routine to express an integer count in base b, sum the digits modulo b to produce the next member of the Thue-Morse fairshare series for b people. Show the first 25 terms of the fairshare sequence:   For two people:   For three people   For five people   For eleven people Related tasks   Non-decimal radices/Convert   Thue-Morse See also   A010060, A053838, A053840: The On-Line Encyclopedia of Integer Sequences® (OEIS®)
#XPL0
XPL0
proc Fair(Base); \Show first 25 terms of fairshare sequence int Base, Count, Sum, N, Q; [RlOut(0, float(Base)); Text(0, ": "); for Count:= 0 to 25-1 do [Sum:= 0; N:= Count; while N do [Q:= N/Base; Sum:= Sum + rem(0); N:= Q; ]; RlOut(0, float(rem(Sum/Base))); ]; CrLf(0); ];   [Format(3,0); Fair(2); Fair(3); Fair(5); Fair(11); ]
http://rosettacode.org/wiki/Fairshare_between_two_and_more
Fairshare between two and more
The Thue-Morse sequence is a sequence of ones and zeros that if two people take turns in the given order, the first persons turn for every '0' in the sequence, the second for every '1'; then this is shown to give a fairer, more equitable sharing of resources. (Football penalty shoot-outs for example, might not favour the team that goes first as much if the penalty takers take turns according to the Thue-Morse sequence and took 2^n penalties) The Thue-Morse sequence of ones-and-zeroes can be generated by: "When counting in binary, the digit sum modulo 2 is the Thue-Morse sequence" Sharing fairly between two or more Use this method: When counting base b, the digit sum modulo b is the Thue-Morse sequence of fairer sharing between b people. Task Counting from zero;   using a function/method/routine to express an integer count in base b, sum the digits modulo b to produce the next member of the Thue-Morse fairshare series for b people. Show the first 25 terms of the fairshare sequence:   For two people:   For three people   For five people   For eleven people Related tasks   Non-decimal radices/Convert   Thue-Morse See also   A010060, A053838, A053840: The On-Line Encyclopedia of Integer Sequences® (OEIS®)
#zkl
zkl
fcn fairShare(n,b){ // b<=36 n.pump(List,'wrap(n){ n.toString(b).split("").apply("toInt",b).sum(0)%b }) } foreach b in (T(2,3,5,11)){ println("%2d: %s".fmt(b,fairShare(25,b).pump(String,"%2d ".fmt))); }
http://rosettacode.org/wiki/Faulhaber%27s_triangle
Faulhaber's triangle
Named after Johann Faulhaber, the rows of Faulhaber's triangle are the coefficients of polynomials that represent sums of integer powers, which are extracted from Faulhaber's formula: ∑ k = 1 n k p = 1 p + 1 ∑ j = 0 p ( p + 1 j ) B j n p + 1 − j {\displaystyle \sum _{k=1}^{n}k^{p}={1 \over p+1}\sum _{j=0}^{p}{p+1 \choose j}B_{j}n^{p+1-j}} where B n {\displaystyle B_{n}} is the nth-Bernoulli number. The first 5 rows of Faulhaber's triangle, are: 1 1/2 1/2 1/6 1/2 1/3 0 1/4 1/2 1/4 -1/30 0 1/3 1/2 1/5 Using the third row of the triangle, we have: ∑ k = 1 n k 2 = 1 6 n + 1 2 n 2 + 1 3 n 3 {\displaystyle \sum _{k=1}^{n}k^{2}={1 \over 6}n+{1 \over 2}n^{2}+{1 \over 3}n^{3}} Task show the first 10 rows of Faulhaber's triangle. using the 18th row of Faulhaber's triangle, compute the sum: ∑ k = 1 1000 k 17 {\displaystyle \sum _{k=1}^{1000}k^{17}} (extra credit). See also Bernoulli numbers Evaluate binomial coefficients Faulhaber's formula (Wikipedia) Faulhaber's triangle (PDF)
#Prolog
Prolog
  ft_rows(Lz) :- lazy_list(ft_row, [], Lz).   ft_row([], R1, R1) :- R1 = [1]. ft_row(R0, R2, R2) :- length(R0, P), Jmax is 1 + P, numlist(2, Jmax, Qs), maplist(term(P), Qs, R0, R1), sum_list(R1, S), Bk is 1 - S, % Bk is Bernoulli number R2 = [Bk | R1].   term(P, Q, R, S) :- S is R * (P rdiv Q).   show(N) :- ft_rows(Rs), length(Rows, N), prefix(Rows, Rs), forall( member(R, Rows), (format(string(S), "~w", [R]), re_replace(" rdiv "/g, "/", S, T), re_replace(","/g, ", ", T, U), write(U), nl)).   sum(N, K, S) :- % sum I=1,N (I ** K) ft_rows(Rows), drop(K, Rows, [Coefs|_]), reverse([0|Coefs], Poly), foldl(horner(N), Poly, 0, S).   horner(N, A, S0, S1) :- S1 is N*S0 + A.   drop(N, Lz1, Lz2) :- append(Pfx, Lz2, Lz1), length(Pfx, N), !.  
http://rosettacode.org/wiki/Faulhaber%27s_formula
Faulhaber's formula
In mathematics,   Faulhaber's formula,   named after Johann Faulhaber,   expresses the sum of the p-th powers of the first n positive integers as a (p + 1)th-degree polynomial function of n,   the coefficients involving Bernoulli numbers. Task Generate the first 10 closed-form expressions, starting with p = 0. Related tasks   Bernoulli numbers.   evaluate binomial coefficients. See also   The Wikipedia entry:   Faulhaber's formula.   The Wikipedia entry:   Bernoulli numbers.   The Wikipedia entry:   binomial coefficients.
#Python
Python
from fractions import Fraction   def nextu(a): n = len(a) a.append(1) for i in range(n - 1, 0, -1): a[i] = i * a[i] + a[i - 1] return a   def nextv(a): n = len(a) - 1 b = [(1 - n) * x for x in a] b.append(1) for i in range(n): b[i + 1] += a[i] return b   def sumpol(n): u = [0, 1] v = [[1], [1, 1]] yield [Fraction(0), Fraction(1)] for i in range(1, n): v.append(nextv(v[-1])) t = [0] * (i + 2) p = 1 for j, r in enumerate(u): r = Fraction(r, j + 1) for k, s in enumerate(v[j + 1]): t[k] += r * s yield t u = nextu(u)   def polstr(a): s = "" q = False n = len(a) - 1 for i, x in enumerate(reversed(a)): i = n - i if i < 2: m = "n" if i == 1 else "" else: m = "n^%d" % i c = str(abs(x)) if i > 0: if c == "1": c = "" else: m = " " + m if x != 0: if q: t = " + " if x > 0 else " - " s += "%s%s%s" % (t, c, m) else: t = "" if x > 0 else "-" s = "%s%s%s" % (t, c, m) q = True if q: return s else: return "0"   for i, p in enumerate(sumpol(10)): print(i, ":", polstr(p))
http://rosettacode.org/wiki/Fibonacci_n-step_number_sequences
Fibonacci n-step number sequences
These number series are an expansion of the ordinary Fibonacci sequence where: For n = 2 {\displaystyle n=2} we have the Fibonacci sequence; with initial values [ 1 , 1 ] {\displaystyle [1,1]} and F k 2 = F k − 1 2 + F k − 2 2 {\displaystyle F_{k}^{2}=F_{k-1}^{2}+F_{k-2}^{2}} For n = 3 {\displaystyle n=3} we have the tribonacci sequence; with initial values [ 1 , 1 , 2 ] {\displaystyle [1,1,2]} and F k 3 = F k − 1 3 + F k − 2 3 + F k − 3 3 {\displaystyle F_{k}^{3}=F_{k-1}^{3}+F_{k-2}^{3}+F_{k-3}^{3}} For n = 4 {\displaystyle n=4} we have the tetranacci sequence; with initial values [ 1 , 1 , 2 , 4 ] {\displaystyle [1,1,2,4]} and F k 4 = F k − 1 4 + F k − 2 4 + F k − 3 4 + F k − 4 4 {\displaystyle F_{k}^{4}=F_{k-1}^{4}+F_{k-2}^{4}+F_{k-3}^{4}+F_{k-4}^{4}} ... For general n > 2 {\displaystyle n>2} we have the Fibonacci n {\displaystyle n} -step sequence - F k n {\displaystyle F_{k}^{n}} ; with initial values of the first n {\displaystyle n} values of the ( n − 1 ) {\displaystyle (n-1)} 'th Fibonacci n {\displaystyle n} -step sequence F k n − 1 {\displaystyle F_{k}^{n-1}} ; and k {\displaystyle k} 'th value of this n {\displaystyle n} 'th sequence being F k n = ∑ i = 1 ( n ) F k − i ( n ) {\displaystyle F_{k}^{n}=\sum _{i=1}^{(n)}{F_{k-i}^{(n)}}} For small values of n {\displaystyle n} , Greek numeric prefixes are sometimes used to individually name each series. Fibonacci n {\displaystyle n} -step sequences n {\displaystyle n} Series name Values 2 fibonacci 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ... 3 tribonacci 1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ... 4 tetranacci 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ... 5 pentanacci 1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ... 6 hexanacci 1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ... 7 heptanacci 1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ... 8 octonacci 1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ... 9 nonanacci 1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ... 10 decanacci 1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ... Allied sequences can be generated where the initial values are changed: The Lucas series sums the two preceding values like the fibonacci series for n = 2 {\displaystyle n=2} but uses [ 2 , 1 ] {\displaystyle [2,1]} as its initial values. Task Write a function to generate Fibonacci n {\displaystyle n} -step number sequences given its initial values and assuming the number of initial values determines how many previous values are summed to make the next number of the series. Use this to print and show here at least the first ten members of the Fibo/tribo/tetra-nacci and Lucas sequences. Related tasks   Fibonacci sequence   Wolfram Mathworld   Hofstadter Q sequence‎   Leonardo numbers Also see   Lucas Numbers - Numberphile (Video)   Tribonacci Numbers (and the Rauzy Fractal) - Numberphile (Video)   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#F.23
F#
let fibinit = Seq.append (Seq.singleton 1) (Seq.unfold (fun n -> Some(n, 2*n)) 1)   let fiblike init = Seq.append (Seq.ofList init) (Seq.unfold (function | least :: rest -> let this = least + Seq.reduce (+) rest Some(this, rest @ [this]) | _ -> None) init)   let lucas = fiblike [2; 1]   let nacci n = Seq.take n fibinit |> Seq.toList |> fiblike   [<EntryPoint>] let main argv = let start s = Seq.take 15 s |> Seq.toList let prefix = "fibo tribo tetra penta hexa hepta octo nona deca".Split() Seq.iter (fun (p, n) -> printfn "n=%2i, %5snacci -> %A" n p (start (nacci n))) (Seq.init prefix.Length (fun i -> (prefix.[i], i+2))) printfn " lucas -> %A" (start (fiblike [2; 1])) 0
http://rosettacode.org/wiki/Find_common_directory_path
Find common directory path
Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories. Test your routine using the forward slash '/' character as the directory separator and the following three strings as input paths: '/home/user1/tmp/coverage/test' '/home/user1/tmp/covert/operator' '/home/user1/tmp/coven/members' Note: The resultant path should be the valid directory '/home/user1/tmp' and not the longest common string '/home/user1/tmp/cove'. If your language has a routine that performs this function (even if it does not have a changeable separator character), then mention it as part of the task. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Standard_ML
Standard ML
fun takeWhileEq ([], _) = [] | takeWhileEq (_, []) = [] | takeWhileEq (x :: xs, y :: ys) = if x = y then x :: takeWhileEq (xs, ys) else []   fun commonPath sep = let val commonInit = fn [] => [] | x :: xs => foldl takeWhileEq x xs and split = String.fields (fn c => c = sep) and join = String.concatWith (str sep) in join o commonInit o map split end   val paths = [ "/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members" ]   val () = print (commonPath #"/" paths ^ "\n")
http://rosettacode.org/wiki/Find_common_directory_path
Find common directory path
Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories. Test your routine using the forward slash '/' character as the directory separator and the following three strings as input paths: '/home/user1/tmp/coverage/test' '/home/user1/tmp/covert/operator' '/home/user1/tmp/coven/members' Note: The resultant path should be the valid directory '/home/user1/tmp' and not the longest common string '/home/user1/tmp/cove'. If your language has a routine that performs this function (even if it does not have a changeable separator character), then mention it as part of the task. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Swift
Swift
import Foundation     func getPrefix(_ text:[String]) -> String? { var common:String = text[0] for i in text { common = i.commonPrefix(with: common) } return common }   var test = ["/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members"]   var output:String = getPrefix(test)! print(output)
http://rosettacode.org/wiki/Filter
Filter
Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
#Forth
Forth
: sel ( dest 0 test src len -- dest len ) cells over + swap do ( dest len test ) i @ over execute if i @ 2over cells + ! >r 1+ r> then cell +loop drop ;   create nums 1 , 2 , 3 , 4 , 5 , 6 , create evens 6 cells allot   : .array 0 ?do dup i cells + @ . loop drop ;   : even? ( n -- ? ) 1 and 0= ;   evens 0 ' even? nums 6 sel .array \ 2 4 6
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) The   FizzBuzz   problem was presented as the lowest level of comprehension required to illustrate adequacy. Also see   (a blog)   dont-overthink-fizzbuzz   (a blog)   fizzbuzz-the-programmers-stairway-to-heaven
#Inform_7
Inform 7
Home is a room.   When play begins: repeat with N running from 1 to 100: let printed be false; if the remainder after dividing N by 3 is 0: say "Fizz"; now printed is true; if the remainder after dividing N by 5 is 0: say "Buzz"; now printed is true; if printed is false, say N; say "."; end the story.
http://rosettacode.org/wiki/File_size
File size
Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
#TUSCRIPT
TUSCRIPT
  $$ MODE TUSCRIPT -- size of file input.txt file="input.txt" ERROR/STOP OPEN (file,READ,-std-) file_size=BYTES ("input.txt") ERROR/STOP CLOSE (file)   -- size of file x:/input.txt ERROR/STOP OPEN (file,READ,x) file_size=BYTES (file) ERROR/STOP CLOSE (file)  
http://rosettacode.org/wiki/File_size
File size
Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
#UNIX_Shell
UNIX Shell
size1=$(ls -l input.txt | tr -s ' ' | cut -d ' ' -f 5) size2=$(ls -l /input.txt | tr -s ' ' | cut -d ' ' -f 5)
http://rosettacode.org/wiki/File_size
File size
Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
#Ursa
Ursa
decl file f   f.open "input.txt" out (size f) endl console f.close   f.open "/input.txt" out (size f) endl console f.close
http://rosettacode.org/wiki/File_input/output
File input/output
File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file into a variable   how to write a variable's contents into a file Oneliners that skip the intermediate variable are of secondary interest — operating systems have copy commands for that.
#M2000_Interpreter
M2000 Interpreter
  Module FileInputOutput { Edit "Input.txt" Document Doc$ Load.Doc Doc$, "Input.txt" Report Doc$ Print "Press a key:";Key$ Save.Doc Doc$, "Output.txt" Edit "Output.txt" } FileInputOutput  
http://rosettacode.org/wiki/File_input/output
File input/output
File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file into a variable   how to write a variable's contents into a file Oneliners that skip the intermediate variable are of secondary interest — operating systems have copy commands for that.
#Maple
Maple
  inout:=proc(filename) local f; f:=FileTools[Text][ReadFile](filename); FileTools[Text][WriteFile]("output.txt",f); end proc;  
http://rosettacode.org/wiki/Fibonacci_word
Fibonacci word
The   Fibonacci Word   may be created in a manner analogous to the   Fibonacci Sequence   as described here: Define   F_Word1   as   1 Define   F_Word2   as   0 Form     F_Word3   as   F_Word2     concatenated with   F_Word1   i.e.:   01 Form     F_Wordn   as   F_Wordn-1   concatenated with   F_wordn-2 Task Perform the above steps for     n = 37. You may display the first few but not the larger values of   n. {Doing so will get the task's author into trouble with them what be (again!).} Instead, create a table for   F_Words   1   to   37   which shows:   The number of characters in the word   The word's Entropy Related tasks   Fibonacci word/fractal   Entropy   Entropy/Narcissist
#Python
Python
>>> import math >>> from collections import Counter >>> >>> def entropy(s): ... p, lns = Counter(s), float(len(s)) ... return -sum( count/lns * math.log(count/lns, 2) for count in p.values()) ... >>> >>> def fibword(nmax=37): ... fwords = ['1', '0'] ... print('%-3s %10s %-10s %s' % tuple('N Length Entropy Fibword'.split())) ... def pr(n, fwords): ... while len(fwords) < n: ... fwords += [''.join(fwords[-2:][::-1])] ... v = fwords[n-1] ... print('%3i %10i %10.7g %s' % (n, len(v), entropy(v), v if len(v) < 20 else '<too long>')) ... for n in range(1, nmax+1): pr(n, fwords) ... >>> fibword() N Length Entropy Fibword 1 1 -0 1 2 1 -0 0 3 2 1 01 4 3 0.9182958 010 5 5 0.9709506 01001 6 8 0.954434 01001010 7 13 0.9612366 0100101001001 8 21 0.9587119 <too long> 9 34 0.9596869 <too long> 10 55 0.959316 <too long> 11 89 0.9594579 <too long> 12 144 0.9594038 <too long> 13 233 0.9594244 <too long> 14 377 0.9594165 <too long> 15 610 0.9594196 <too long> 16 987 0.9594184 <too long> 17 1597 0.9594188 <too long> 18 2584 0.9594187 <too long> 19 4181 0.9594187 <too long> 20 6765 0.9594187 <too long> 21 10946 0.9594187 <too long> 22 17711 0.9594187 <too long> 23 28657 0.9594187 <too long> 24 46368 0.9594187 <too long> 25 75025 0.9594187 <too long> 26 121393 0.9594187 <too long> 27 196418 0.9594187 <too long> 28 317811 0.9594187 <too long> 29 514229 0.9594187 <too long> 30 832040 0.9594187 <too long> 31 1346269 0.9594187 <too long> 32 2178309 0.9594187 <too long> 33 3524578 0.9594187 <too long> 34 5702887 0.9594187 <too long> 35 9227465 0.9594187 <too long> 36 14930352 0.9594187 <too long> 37 24157817 0.9594187 <too long> >>>
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: Fn = Fn+2 - Fn+1, if n<0 support for negative     n     in the solution is optional. Related tasks   Fibonacci n-step number sequences‎   Leonardo numbers References   Wikipedia, Fibonacci number   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#AdvPL
AdvPL
  #include "totvs.ch" User Function fibb(a,b,n) return(if(--n>0,fibb(b,a+b,n),a))  
http://rosettacode.org/wiki/Factors_of_an_integer
Factors of an integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Compute the   factors   of a positive integer. These factors are the positive integers by which the number being factored can be divided to yield a positive integer result. (Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty;   this task does not require handling of either of these cases). Note that every prime number has two factors:   1   and itself. Related tasks   count in factors   prime decomposition   Sieve of Eratosthenes   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division   sequence: smallest number greater than previous term with exactly n divisors
#Arc
Arc
  (= divisor (fn (num) (= dlist '()) (when (is 1 num) (= dlist '(1 0))) (when (is 2 num) (= dlist '(2 1))) (unless (or (is 1 num) (is 2 num)) (up i 1 (+ 1 (/ num 2)) (if (is 0 (mod num i)) (push i dlist))) (= dlist (cons num dlist))) dlist))   (map [rev _] (map [divisor _] '(45 53 60 64)))  
http://rosettacode.org/wiki/Fast_Fourier_transform
Fast Fourier transform
Task Calculate the   FFT   (Fast Fourier Transform)   of an input sequence. The most general case allows for complex numbers at the input and results in a sequence of equal length, again of complex numbers. If you need to restrict yourself to real numbers, the output should be the magnitude   (i.e.:   sqrt(re2 + im2))   of the complex result. The classic version is the recursive Cooley–Tukey FFT. Wikipedia has pseudo-code for that. Further optimizations are possible but not required.
#GAP
GAP
# Here an implementation with no optimization (O(n^2)). # In GAP, E(n) = exp(2*i*pi/n), a primitive root of the unity.   Fourier := function(a) local n, z; n := Size(a); z := E(n); return List([0 .. n - 1], k -> Sum([0 .. n - 1], j -> a[j + 1]*z^(-k*j))); end;   InverseFourier := function(a) local n, z; n := Size(a); z := E(n); return List([0 .. n - 1], k -> Sum([0 .. n - 1], j -> a[j + 1]*z^(k*j)))/n; end;   Fourier([1, 1, 1, 1, 0, 0, 0, 0]); # [ 4, 1-E(8)-E(8)^2-E(8)^3, 0, 1-E(8)+E(8)^2-E(8)^3, # 0, 1+E(8)-E(8)^2+E(8)^3, 0, 1+E(8)+E(8)^2+E(8)^3 ]   InverseFourier(last); # [ 1, 1, 1, 1, 0, 0, 0, 0 ]
http://rosettacode.org/wiki/Factors_of_a_Mersenne_number
Factors of a Mersenne number
A Mersenne number is a number in the form of 2P-1. If P is prime, the Mersenne number may be a Mersenne prime (if P is not prime, the Mersenne number is also not prime). In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before starting a, potentially lengthy, Lucas-Lehmer test. There are very efficient algorithms for determining if a number divides 2P-1 (or equivalently, if 2P mod (the number) = 1). Some languages already have built-in implementations of this exponent-and-mod operation (called modPow or similar). The following is how to implement this modPow yourself: For example, let's compute 223 mod 47. Convert the exponent 23 to binary, you get 10111. Starting with square = 1, repeatedly square it. Remove the top bit of the exponent, and if it's 1 multiply square by the base of the exponentiation (2), then compute square modulo 47. Use the result of the modulo from the last step as the initial value of square in the next step: remove optional square top bit multiply by 2 mod 47 ──────────── ─────── ───────────── ────── 1*1 = 1 1 0111 1*2 = 2 2 2*2 = 4 0 111 no 4 4*4 = 16 1 11 16*2 = 32 32 32*32 = 1024 1 1 1024*2 = 2048 27 27*27 = 729 1 729*2 = 1458 1 Since 223 mod 47 = 1, 47 is a factor of 2P-1. (To see this, subtract 1 from both sides: 223-1 = 0 mod 47.) Since we've shown that 47 is a factor, 223-1 is not prime. Further properties of Mersenne numbers allow us to refine the process even more. Any factor q of 2P-1 must be of the form 2kP+1, k being a positive integer or zero. Furthermore, q must be 1 or 7 mod 8. Finally any potential factor q must be prime. As in other trial division algorithms, the algorithm stops when 2kP+1 > sqrt(N). These primality tests only work on Mersenne numbers where P is prime. For example, M4=15 yields no factors using these techniques, but factors into 3 and 5, neither of which fit 2kP+1. Task Using the above method find a factor of 2929-1 (aka M929) Related tasks   count in factors   prime decomposition   factors of an integer   Sieve of Eratosthenes   primality by trial division   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division See also   Computers in 1948: 2127 - 1       (Note:   This video is no longer available because the YouTube account associated with this video has been terminated.)
#Fortran
Fortran
PROGRAM EXAMPLE IMPLICIT NONE INTEGER :: exponent, factor   WRITE(*,*) "Enter exponent of Mersenne number" READ(*,*) exponent factor = Mfactor(exponent) IF (factor == 0) THEN WRITE(*,*) "No Factor found" ELSE WRITE(*,"(A,I0,A,I0)") "M", exponent, " has a factor: ", factor END IF   CONTAINS   FUNCTION isPrime(number) ! code omitted - see [[Primality by Trial Division]] END FUNCTION   FUNCTION Mfactor(p) INTEGER :: Mfactor INTEGER, INTENT(IN) :: p INTEGER :: i, k, maxk, msb, n, q   DO i = 30, 0 , -1 IF(BTEST(p, i)) THEN msb = i EXIT END IF END DO   maxk = 16384 / p ! limit for k to prevent overflow of 32 bit signed integer DO k = 1, maxk q = 2*p*k + 1 IF (.NOT. isPrime(q)) CYCLE IF (MOD(q, 8) /= 1 .AND. MOD(q, 8) /= 7) CYCLE n = 1 DO i = msb, 0, -1 IF (BTEST(p, i)) THEN n = MOD(n*n*2, q) ELSE n = MOD(n*n, q) ENDIF END DO IF (n == 1) THEN Mfactor = q RETURN END IF END DO Mfactor = 0 END FUNCTION END PROGRAM EXAMPLE
http://rosettacode.org/wiki/Farey_sequence
Farey sequence
The   Farey sequence   Fn   of order   n   is the sequence of completely reduced fractions between   0   and   1   which, when in lowest terms, have denominators less than or equal to   n,   arranged in order of increasing size. The   Farey sequence   is sometimes incorrectly called a   Farey series. Each Farey sequence:   starts with the value   0   (zero),   denoted by the fraction     0 1 {\displaystyle {\frac {0}{1}}}   ends with the value   1   (unity),   denoted by the fraction   1 1 {\displaystyle {\frac {1}{1}}} . The Farey sequences of orders   1   to   5   are: F 1 = 0 1 , 1 1 {\displaystyle {\bf {\it {F}}}_{1}={\frac {0}{1}},{\frac {1}{1}}} F 2 = 0 1 , 1 2 , 1 1 {\displaystyle {\bf {\it {F}}}_{2}={\frac {0}{1}},{\frac {1}{2}},{\frac {1}{1}}} F 3 = 0 1 , 1 3 , 1 2 , 2 3 , 1 1 {\displaystyle {\bf {\it {F}}}_{3}={\frac {0}{1}},{\frac {1}{3}},{\frac {1}{2}},{\frac {2}{3}},{\frac {1}{1}}} F 4 = 0 1 , 1 4 , 1 3 , 1 2 , 2 3 , 3 4 , 1 1 {\displaystyle {\bf {\it {F}}}_{4}={\frac {0}{1}},{\frac {1}{4}},{\frac {1}{3}},{\frac {1}{2}},{\frac {2}{3}},{\frac {3}{4}},{\frac {1}{1}}} F 5 = 0 1 , 1 5 , 1 4 , 1 3 , 2 5 , 1 2 , 3 5 , 2 3 , 3 4 , 4 5 , 1 1 {\displaystyle {\bf {\it {F}}}_{5}={\frac {0}{1}},{\frac {1}{5}},{\frac {1}{4}},{\frac {1}{3}},{\frac {2}{5}},{\frac {1}{2}},{\frac {3}{5}},{\frac {2}{3}},{\frac {3}{4}},{\frac {4}{5}},{\frac {1}{1}}} Task   Compute and show the Farey sequence for orders   1   through   11   (inclusive).   Compute and display the   number   of fractions in the Farey sequence for order   100   through   1,000   (inclusive)   by hundreds.   Show the fractions as   n/d   (using the solidus [or slash] to separate the numerator from the denominator). The length   (the number of fractions)   of a Farey sequence asymptotically approaches: 3 × n2   ÷   π {\displaystyle \pi } 2 See also   OEIS sequence   A006842 numerators of Farey series of order 1, 2, ···   OEIS sequence   A006843 denominators of Farey series of order 1, 2, ···   OEIS sequence   A005728 number of fractions in Farey series of order n   MathWorld entry   Farey sequence   Wikipedia   entry   Farey sequence
#Nim
Nim
import strformat   proc farey(n: int) = var f1 = (d: 0, n: 1) var f2 = (d: 1, n: n) write(stdout, fmt"0/1 1/{n}") while f2.n > 1: let k = (n + f1.n) div f2.n let aux = f1 f1 = f2 f2 = (f2.d * k - aux.d, f2.n * k - aux.n) write(stdout, fmt" {f2.d}/{f2.n}") write(stdout, "\n")   proc fareyLength(n: int, cache: var seq[int]): int = if n >= cache.len: var newLen = cache.len if newLen == 0: newLen = 16 while newLen <= n: newLen *= 2 cache.setLen(newLen) elif cache[n] != 0: return cache[n]   var length = n * (n + 3) div 2 var p = 2 var q = 0 while p <= n: q = n div (n div p) + 1 dec length, fareyLength(n div p, cache) * (q - p) p = q cache[n] = length return length   for n in 1..11: write(stdout, fmt"{n:>8}: ") farey(n)   var cache: seq[int] = @[] for n in countup(100, 1000, step=100): echo fmt"{n:>8}: {fareyLength(n, cache):14} items"   let n = 10_000_000 echo fmt"{n}: {fareyLength(n, cache):14} items"
http://rosettacode.org/wiki/Farey_sequence
Farey sequence
The   Farey sequence   Fn   of order   n   is the sequence of completely reduced fractions between   0   and   1   which, when in lowest terms, have denominators less than or equal to   n,   arranged in order of increasing size. The   Farey sequence   is sometimes incorrectly called a   Farey series. Each Farey sequence:   starts with the value   0   (zero),   denoted by the fraction     0 1 {\displaystyle {\frac {0}{1}}}   ends with the value   1   (unity),   denoted by the fraction   1 1 {\displaystyle {\frac {1}{1}}} . The Farey sequences of orders   1   to   5   are: F 1 = 0 1 , 1 1 {\displaystyle {\bf {\it {F}}}_{1}={\frac {0}{1}},{\frac {1}{1}}} F 2 = 0 1 , 1 2 , 1 1 {\displaystyle {\bf {\it {F}}}_{2}={\frac {0}{1}},{\frac {1}{2}},{\frac {1}{1}}} F 3 = 0 1 , 1 3 , 1 2 , 2 3 , 1 1 {\displaystyle {\bf {\it {F}}}_{3}={\frac {0}{1}},{\frac {1}{3}},{\frac {1}{2}},{\frac {2}{3}},{\frac {1}{1}}} F 4 = 0 1 , 1 4 , 1 3 , 1 2 , 2 3 , 3 4 , 1 1 {\displaystyle {\bf {\it {F}}}_{4}={\frac {0}{1}},{\frac {1}{4}},{\frac {1}{3}},{\frac {1}{2}},{\frac {2}{3}},{\frac {3}{4}},{\frac {1}{1}}} F 5 = 0 1 , 1 5 , 1 4 , 1 3 , 2 5 , 1 2 , 3 5 , 2 3 , 3 4 , 4 5 , 1 1 {\displaystyle {\bf {\it {F}}}_{5}={\frac {0}{1}},{\frac {1}{5}},{\frac {1}{4}},{\frac {1}{3}},{\frac {2}{5}},{\frac {1}{2}},{\frac {3}{5}},{\frac {2}{3}},{\frac {3}{4}},{\frac {4}{5}},{\frac {1}{1}}} Task   Compute and show the Farey sequence for orders   1   through   11   (inclusive).   Compute and display the   number   of fractions in the Farey sequence for order   100   through   1,000   (inclusive)   by hundreds.   Show the fractions as   n/d   (using the solidus [or slash] to separate the numerator from the denominator). The length   (the number of fractions)   of a Farey sequence asymptotically approaches: 3 × n2   ÷   π {\displaystyle \pi } 2 See also   OEIS sequence   A006842 numerators of Farey series of order 1, 2, ···   OEIS sequence   A006843 denominators of Farey series of order 1, 2, ···   OEIS sequence   A005728 number of fractions in Farey series of order n   MathWorld entry   Farey sequence   Wikipedia   entry   Farey sequence
#PARI.2FGP
PARI/GP
Farey(n)=my(v=List()); for(k=1,n,for(i=0,k,listput(v,i/k))); vecsort(Set(v)); countFarey(n)=1+sum(k=1, n, eulerphi(k)); fmt(n)=if(denominator(n)>1,n,Str(n,"/1")); for(n=1,11,print(apply(fmt, Farey(n)))) apply(countFarey, 100*[1..10])
http://rosettacode.org/wiki/Faulhaber%27s_triangle
Faulhaber's triangle
Named after Johann Faulhaber, the rows of Faulhaber's triangle are the coefficients of polynomials that represent sums of integer powers, which are extracted from Faulhaber's formula: ∑ k = 1 n k p = 1 p + 1 ∑ j = 0 p ( p + 1 j ) B j n p + 1 − j {\displaystyle \sum _{k=1}^{n}k^{p}={1 \over p+1}\sum _{j=0}^{p}{p+1 \choose j}B_{j}n^{p+1-j}} where B n {\displaystyle B_{n}} is the nth-Bernoulli number. The first 5 rows of Faulhaber's triangle, are: 1 1/2 1/2 1/6 1/2 1/3 0 1/4 1/2 1/4 -1/30 0 1/3 1/2 1/5 Using the third row of the triangle, we have: ∑ k = 1 n k 2 = 1 6 n + 1 2 n 2 + 1 3 n 3 {\displaystyle \sum _{k=1}^{n}k^{2}={1 \over 6}n+{1 \over 2}n^{2}+{1 \over 3}n^{3}} Task show the first 10 rows of Faulhaber's triangle. using the 18th row of Faulhaber's triangle, compute the sum: ∑ k = 1 1000 k 17 {\displaystyle \sum _{k=1}^{1000}k^{17}} (extra credit). See also Bernoulli numbers Evaluate binomial coefficients Faulhaber's formula (Wikipedia) Faulhaber's triangle (PDF)
#Python
Python
'''Faulhaber's triangle'''   from itertools import accumulate, chain, count, islice from fractions import Fraction     # faulhaberTriangle :: Int -> [[Fraction]] def faulhaberTriangle(m): '''List of rows of Faulhaber fractions.''' def go(rs, n): def f(x, y): return Fraction(n, x) * y xs = list(map(f, islice(count(2), m), rs)) return [Fraction(1 - sum(xs), 1)] + xs   return list(accumulate( [[]] + list(islice(count(0), 1 + m)), go ))[1:]     # faulhaberSum :: Integer -> Integer -> Integer def faulhaberSum(p, n): '''Sum of the p-th powers of the first n positive integers. ''' def go(x, y): return y * (n ** x)   return sum( map(go, count(1), faulhaberTriangle(p)[-1]) )     # ------------------------- TEST ------------------------- def main(): '''Tests'''   fs = faulhaberTriangle(9) print( fTable(__doc__ + ':\n')(str)( compose(concat)( fmap(showRatio(3)(3)) ) )( index(fs) )(range(0, len(fs))) ) print('') print( faulhaberSum(17, 1000) )     # ----------------------- DISPLAY ------------------------   # fTable :: String -> (a -> String) -> # (b -> String) -> (a -> b) -> [a] -> String def fTable(s): '''Heading -> x display function -> fx display function -> f -> xs -> tabular string. ''' def gox(xShow): def gofx(fxShow): def gof(f): def goxs(xs): ys = [xShow(x) for x in xs] w = max(map(len, ys))   def arrowed(x, y): return y.rjust(w, ' ') + ' -> ' + ( fxShow(f(x)) ) return s + '\n' + '\n'.join( map(arrowed, xs, ys) ) return goxs return gof return gofx return gox     # ----------------------- GENERIC ------------------------   # compose (<<<) :: (b -> c) -> (a -> b) -> a -> c def compose(g): '''Right to left function composition.''' return lambda f: lambda x: g(f(x))     # concat :: [[a]] -> [a] # concat :: [String] -> String def concat(xs): '''The concatenation of all the elements in a list or iterable. ''' def f(ys): zs = list(chain(*ys)) return ''.join(zs) if isinstance(ys[0], str) else zs   return ( f(xs) if isinstance(xs, list) else ( chain.from_iterable(xs) ) ) if xs else []     # fmap :: (a -> b) -> [a] -> [b] def fmap(f): '''fmap over a list. f lifted to a function over a list. ''' def go(xs): return list(map(f, xs))   return go     # index (!!) :: [a] -> Int -> a def index(xs): '''Item at given (zero-based) index.''' return lambda n: None if 0 > n else ( xs[n] if ( hasattr(xs, "__getitem__") ) else next(islice(xs, n, None)) )     # showRatio :: Int -> Int -> Ratio -> String def showRatio(m): '''Left and right aligned string representation of the ratio r. ''' def go(n): def f(r): d = r.denominator return str(r.numerator).rjust(m, ' ') + ( ('/' + str(d).ljust(n, ' ')) if 1 != d else ( ' ' * (1 + n) ) ) return f return go     # MAIN --- if __name__ == '__main__': main()
http://rosettacode.org/wiki/Faulhaber%27s_formula
Faulhaber's formula
In mathematics,   Faulhaber's formula,   named after Johann Faulhaber,   expresses the sum of the p-th powers of the first n positive integers as a (p + 1)th-degree polynomial function of n,   the coefficients involving Bernoulli numbers. Task Generate the first 10 closed-form expressions, starting with p = 0. Related tasks   Bernoulli numbers.   evaluate binomial coefficients. See also   The Wikipedia entry:   Faulhaber's formula.   The Wikipedia entry:   Bernoulli numbers.   The Wikipedia entry:   binomial coefficients.
#Racket
Racket
#lang racket/base   (require racket/match racket/string math/number-theory)   (define simplify-arithmetic-expression (letrec ((s-a-e (match-lambda [(list (and op '+) l ... (list '+ m ...) r ...) (s-a-e `(,op ,@l ,@m ,@r))] [(list (and op '+) l ... (? number? n1) m ... (? number? n2) r ...) (s-a-e `(,op ,@l ,(+ n1 n2) ,@m ,@r))] [(list (and op '+) (app s-a-e l _) ... 0 (app s-a-e r _) ...) (s-a-e `(,op ,@l ,@r))] [(list (and op '+) (app s-a-e x _)) (values x #t)] [(list (and op '*) l ... (list '* m ...) r ...) (s-a-e `(,op ,@l ,@m ,@r))] [(list (and op '*) l ... (? number? n1) m ... (? number? n2) r ...) (s-a-e `(,op ,@l ,(* n1 n2) ,@m ,@r))] [(list (and op '*) (app s-a-e l _) ... 1 (app s-a-e r _) ...) (s-a-e `(,op ,@l ,@r))] [(list (and op '*) (app s-a-e l _) ... 0 (app s-a-e r _) ...) (values 0 #t)] [(list (and op '*) (app s-a-e x _)) (values x #t)] [(list 'expt (app s-a-e x x-simplified?) 1) (values x x-simplified?)] [(list op (app s-a-e a #f) ...) (values `(,op ,@a) #f)] [(list op (app s-a-e a _) ...) (s-a-e `(,op ,@a))] [e (values e #f)]))) s-a-e))   (define (expression->infix-string e) (define (parenthesise-maybe s p?) (if p? (string-append "(" s ")") s))   (letrec ((e->is (lambda (paren?) (match-lambda [(list (and op (or '+ '- '* '*)) (app (e->is #t) a p?) ...) (define bits (map parenthesise-maybe a p?)) (define compound (string-join bits (format " ~a " op))) (values (if paren? (string-append "(" compound ")") compound) #f)] [(list 'expt (app (e->is #t) x xp?) (app (e->is #t) n np?)) (values (format "~a^~a" (parenthesise-maybe x xp?) (parenthesise-maybe n np?)) #f)] [(? number? (app number->string s)) (values s #f)] [(? symbol? (app symbol->string s)) (values s #f)])))) (define-values (str needs-parens?) ((e->is #f) e)) str))   (define (faulhaber p) (define p+1 (add1 p)) (define-values (simpler simplified?) (simplify-arithmetic-expression `(* ,(/ 1 p+1) (+ ,@(for/list ((j (in-range p+1))) `(* ,(* (expt -1 j) (binomial p+1 j)) (* ,(bernoulli-number j) (expt n ,(- p+1 j))))))))) simpler)   (for ((p (in-range 0 (add1 9)))) (printf "f(~a) = ~a~%" p (expression->infix-string (faulhaber p))))  
http://rosettacode.org/wiki/Fibonacci_n-step_number_sequences
Fibonacci n-step number sequences
These number series are an expansion of the ordinary Fibonacci sequence where: For n = 2 {\displaystyle n=2} we have the Fibonacci sequence; with initial values [ 1 , 1 ] {\displaystyle [1,1]} and F k 2 = F k − 1 2 + F k − 2 2 {\displaystyle F_{k}^{2}=F_{k-1}^{2}+F_{k-2}^{2}} For n = 3 {\displaystyle n=3} we have the tribonacci sequence; with initial values [ 1 , 1 , 2 ] {\displaystyle [1,1,2]} and F k 3 = F k − 1 3 + F k − 2 3 + F k − 3 3 {\displaystyle F_{k}^{3}=F_{k-1}^{3}+F_{k-2}^{3}+F_{k-3}^{3}} For n = 4 {\displaystyle n=4} we have the tetranacci sequence; with initial values [ 1 , 1 , 2 , 4 ] {\displaystyle [1,1,2,4]} and F k 4 = F k − 1 4 + F k − 2 4 + F k − 3 4 + F k − 4 4 {\displaystyle F_{k}^{4}=F_{k-1}^{4}+F_{k-2}^{4}+F_{k-3}^{4}+F_{k-4}^{4}} ... For general n > 2 {\displaystyle n>2} we have the Fibonacci n {\displaystyle n} -step sequence - F k n {\displaystyle F_{k}^{n}} ; with initial values of the first n {\displaystyle n} values of the ( n − 1 ) {\displaystyle (n-1)} 'th Fibonacci n {\displaystyle n} -step sequence F k n − 1 {\displaystyle F_{k}^{n-1}} ; and k {\displaystyle k} 'th value of this n {\displaystyle n} 'th sequence being F k n = ∑ i = 1 ( n ) F k − i ( n ) {\displaystyle F_{k}^{n}=\sum _{i=1}^{(n)}{F_{k-i}^{(n)}}} For small values of n {\displaystyle n} , Greek numeric prefixes are sometimes used to individually name each series. Fibonacci n {\displaystyle n} -step sequences n {\displaystyle n} Series name Values 2 fibonacci 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ... 3 tribonacci 1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ... 4 tetranacci 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ... 5 pentanacci 1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ... 6 hexanacci 1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ... 7 heptanacci 1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ... 8 octonacci 1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ... 9 nonanacci 1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ... 10 decanacci 1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ... Allied sequences can be generated where the initial values are changed: The Lucas series sums the two preceding values like the fibonacci series for n = 2 {\displaystyle n=2} but uses [ 2 , 1 ] {\displaystyle [2,1]} as its initial values. Task Write a function to generate Fibonacci n {\displaystyle n} -step number sequences given its initial values and assuming the number of initial values determines how many previous values are summed to make the next number of the series. Use this to print and show here at least the first ten members of the Fibo/tribo/tetra-nacci and Lucas sequences. Related tasks   Fibonacci sequence   Wolfram Mathworld   Hofstadter Q sequence‎   Leonardo numbers Also see   Lucas Numbers - Numberphile (Video)   Tribonacci Numbers (and the Rauzy Fractal) - Numberphile (Video)   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#Factor
Factor
USING: formatting fry kernel make math namespaces qw sequences ;   : n-bonacci ( n initial -- seq ) [ [ [ , ] each ] [ length - ] [ length ] tri '[ building get _ tail* sum , ] times ] { } make ;   qw{ fibonacci tribonacci tetranacci lucas } { { 1 1 } { 1 1 2 } { 1 1 2 4 } { 2 1 } } [ 10 swap n-bonacci "%-10s %[%3d, %]\n" printf ] 2each
http://rosettacode.org/wiki/Find_common_directory_path
Find common directory path
Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories. Test your routine using the forward slash '/' character as the directory separator and the following three strings as input paths: '/home/user1/tmp/coverage/test' '/home/user1/tmp/covert/operator' '/home/user1/tmp/coven/members' Note: The resultant path should be the valid directory '/home/user1/tmp' and not the longest common string '/home/user1/tmp/cove'. If your language has a routine that performs this function (even if it does not have a changeable separator character), then mention it as part of the task. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Tcl
Tcl
package require Tcl 8.5 proc pop {varname} { upvar 1 $varname var set var [lassign $var head] return $head }   proc common_prefix {dirs {separator "/"}} { set parts [split [pop dirs] $separator] while {[llength $dirs]} { set r {} foreach cmp $parts elt [split [pop dirs] $separator] { if {$cmp ne $elt} break lappend r $cmp } set parts $r } return [join $parts $separator] }
http://rosettacode.org/wiki/Filter
Filter
Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
#Fortran
Fortran
module funcs implicit none contains pure function iseven(x) logical :: iseven integer, intent(in) :: x iseven = mod(x, 2) == 0 end function iseven end module funcs
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) The   FizzBuzz   problem was presented as the lowest level of comprehension required to illustrate adequacy. Also see   (a blog)   dont-overthink-fizzbuzz   (a blog)   fizzbuzz-the-programmers-stairway-to-heaven
#Io
Io
for(a,1,100, if(a % 15 == 0) then( "FizzBuzz" println ) elseif(a % 3 == 0) then( "Fizz" println ) elseif(a % 5 == 0) then( "Buzz" println ) else ( a println ) )
http://rosettacode.org/wiki/File_size
File size
Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
#VBScript
VBScript
  With CreateObject("Scripting.FileSystemObject") WScript.Echo .GetFile("input.txt").Size WScript.Echo .GetFile("\input.txt").Size End With  
http://rosettacode.org/wiki/File_size
File size
Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
#Vedit_macro_language
Vedit macro language
Num_Type(File_Size("input.txt")) Num_Type(File_Size("/input.txt"))
http://rosettacode.org/wiki/File_size
File size
Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
#Visual_Basic
Visual Basic
Option Explicit   ----   Sub DisplayFileSize(ByVal Path As String, ByVal Filename As String) Dim i As Long If InStr(Len(Path), Path, "\") = 0 Then Path = Path & "\" End If On Error Resume Next 'otherwise runtime error if file does not exist i = FileLen(Path & Filename) If Err.Number = 0 Then Debug.Print "file size: " & CStr(i) & " Bytes" Else Debug.Print "error: " & Err.Description End If End Sub   ----   Sub Main() DisplayFileSize CurDir(), "input.txt" DisplayFileSize CurDir(), "innputt.txt" DisplayFileSize Environ$("SystemRoot"), "input.txt" End Sub  
http://rosettacode.org/wiki/File_input/output
File input/output
File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file into a variable   how to write a variable's contents into a file Oneliners that skip the intermediate variable are of secondary interest — operating systems have copy commands for that.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
SetDirectory@NotebookDirectory[]; If[FileExistsQ["output.txt"], DeleteFile["output.txt"], Print["No output yet"] ]; CopyFile["input.txt", "output.txt"]
http://rosettacode.org/wiki/File_input/output
File input/output
File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file into a variable   how to write a variable's contents into a file Oneliners that skip the intermediate variable are of secondary interest — operating systems have copy commands for that.
#MAXScript
MAXScript
inFile = openFile "input.txt" outFile = createFile "output.txt" while not EOF inFile do ( format "%" (readLine inFile) to:outFile ) close inFile close outFile
http://rosettacode.org/wiki/Fibonacci_word
Fibonacci word
The   Fibonacci Word   may be created in a manner analogous to the   Fibonacci Sequence   as described here: Define   F_Word1   as   1 Define   F_Word2   as   0 Form     F_Word3   as   F_Word2     concatenated with   F_Word1   i.e.:   01 Form     F_Wordn   as   F_Wordn-1   concatenated with   F_wordn-2 Task Perform the above steps for     n = 37. You may display the first few but not the larger values of   n. {Doing so will get the task's author into trouble with them what be (again!).} Instead, create a table for   F_Words   1   to   37   which shows:   The number of characters in the word   The word's Entropy Related tasks   Fibonacci word/fractal   Entropy   Entropy/Narcissist
#R
R
entropy <- function(s) { if (length(s) > 1) return(sapply(s, entropy))   freq <- prop.table(table(strsplit(s, '')[1])) ret <- -sum(freq * log(freq, base=2))   return(ret) }   fibwords <- function(n) { if (n == 1) fibwords <- "1" else fibwords <- c("1", "0")   if (n > 2) { for (i in 3:n) fibwords <- c(fibwords, paste(fibwords[i-1L], fibwords[i-2L], sep="")) }   str <- if (n > 7) replicate(n-7, "too long") else NULL fibwords.print <- c(fibwords[1:min(n, 7)], str)   ret <- data.frame(Length=nchar(fibwords), Entropy=entropy(fibwords), Fibwords=fibwords.print) rownames(ret) <- NULL return(ret) }
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: Fn = Fn+2 - Fn+1, if n<0 support for negative     n     in the solution is optional. Related tasks   Fibonacci n-step number sequences‎   Leonardo numbers References   Wikipedia, Fibonacci number   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#Aime
Aime
integer fibs(integer n) { integer w;   if (n == 0) { w = 0; } elif (n == 1) { w = 1; } else { integer a, b, i;   i = 1; a = 0; b = 1; while (i < n) { w = a + b; a = b; b = w; i += 1; } }   return w; }  
http://rosettacode.org/wiki/Factors_of_an_integer
Factors of an integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Compute the   factors   of a positive integer. These factors are the positive integers by which the number being factored can be divided to yield a positive integer result. (Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty;   this task does not require handling of either of these cases). Note that every prime number has two factors:   1   and itself. Related tasks   count in factors   prime decomposition   Sieve of Eratosthenes   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division   sequence: smallest number greater than previous term with exactly n divisors
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program factorst.s */   /* Constantes */ .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ WRITE, 4 @ Linux syscall /* Initialized data */ .data szMessDeb: .ascii "Factors of :" sMessValeur: .fill 12, 1, ' ' .asciz "are : \n" sMessFactor: .fill 12, 1, ' ' .asciz "\n" szCarriageReturn: .asciz "\n"   /* UnInitialized data */ .bss   /* code section */ .text .global main main: /* entry of program */ push {fp,lr} /* saves 2 registers */   mov r0,#100 bl factors mov r0,#97 bl factors ldr r0,iNumber bl factors     100: /* standard end of the program */ mov r0, #0 @ return code pop {fp,lr} @restaur 2 registers mov r7, #EXIT @ request to exit program swi 0 @ perform the system call   iNumber: .int 32767 iAdrszCarriageReturn: .int szCarriageReturn /******************************************************************/ /* calcul factors of number */ /******************************************************************/ /* r0 contains the number */ factors: push {fp,lr} /* save registres */ push {r1-r6} /* save others registers */ mov r5,r0 @ limit calcul ldr r1,iAdrsMessValeur @ conversion register in decimal string bl conversion10S ldr r0,iAdrszMessDeb @ display message bl affichageMess mov r6,#1 @ counter loop 1: @ loop mov r0,r5 @ dividende mov r1,r6 @ divisor bl division cmp r3,#0 @ remainder = zero ? bne 2f @ display result if yes mov r0,r6 ldr r1,iAdrsMessFactor bl conversion10S ldr r0,iAdrsMessFactor bl affichageMess 2: add r6,#1 @ add 1 to loop counter cmp r6,r5 @ <= number ? ble 1b @ yes loop 100: pop {r1-r6} /* restaur others registers */ pop {fp,lr} /* restaur des 2 registres */ bx lr /* return */ iAdrsMessValeur: .int sMessValeur iAdrszMessDeb: .int szMessDeb iAdrsMessFactor: .int sMessFactor /******************************************************************/ /* display text with size calculation */ /******************************************************************/ /* r0 contains the address of the message */ affichageMess: push {fp,lr} /* save registres */ push {r0,r1,r2,r7} /* save others registers */ mov r2,#0 /* counter length */ 1: /* loop length calculation */ ldrb r1,[r0,r2] /* read octet start position + index */ cmp r1,#0 /* if 0 its over */ addne r2,r2,#1 /* else add 1 in the length */ bne 1b /* and loop */ /* so here r2 contains the length of the message */ mov r1,r0 /* address message in r1 */ mov r0,#STDOUT /* code to write to the standard output Linux */ mov r7, #WRITE /* code call system "write" */ swi #0 /* call systeme */ pop {r0,r1,r2,r7} /* restaur others registers */ pop {fp,lr} /* restaur des 2 registres */ bx lr /* return */ /*=============================================*/ /* division integer unsigned */ /*============================================*/ division: /* r0 contains N */ /* r1 contains D */ /* r2 contains Q */ /* r3 contains R */ push {r4, lr} mov r2, #0 /* r2 ? 0 */ mov r3, #0 /* r3 ? 0 */ mov r4, #32 /* r4 ? 32 */ b 2f 1: movs r0, r0, LSL #1 /* r0 ? r0 << 1 updating cpsr (sets C if 31st bit of r0 was 1) */ adc r3, r3, r3 /* r3 ? r3 + r3 + C. This is equivalent to r3 ? (r3 << 1) + C */   cmp r3, r1 /* compute r3 - r1 and update cpsr */ subhs r3, r3, r1 /* if r3 >= r1 (C=1) then r3 ? r3 - r1 */ adc r2, r2, r2 /* r2 ? r2 + r2 + C. This is equivalent to r2 ? (r2 << 1) + C */ 2: subs r4, r4, #1 /* r4 ? r4 - 1 */ bpl 1b /* if r4 >= 0 (N=0) then branch to .Lloop1 */   pop {r4, lr} bx lr   /***************************************************/ /* conversion register in string décimal signed */ /***************************************************/ /* r0 contains the register */ /* r1 contains address of conversion area */ conversion10S: push {fp,lr} /* save registers frame and return */ push {r0-r5} /* save other registers */ mov r2,r1 /* early storage area */ mov r5,#'+' /* default sign is + */ cmp r0,#0 /* négatif number ? */ movlt r5,#'-' /* yes sign is - */ mvnlt r0,r0 /* and inverse in positive value */ addlt r0,#1 mov r4,#10 /* area length */ 1: /* conversion loop */ bl divisionpar10 /* division */ add r1,#48 /* add 48 at remainder for conversion ascii */ strb r1,[r2,r4] /* store byte area r5 + position r4 */ sub r4,r4,#1 /* previous position */ cmp r0,#0 bne 1b /* loop if quotient not equal zéro */ strb r5,[r2,r4] /* store sign at current position */ subs r4,r4,#1 /* previous position */ blt 100f /* if r4 < 0 end */ /* else complete area with space */ mov r3,#' ' /* character space */ 2: strb r3,[r2,r4] /* store byte */ subs r4,r4,#1 /* previous position */ bge 2b /* loop if r4 greather or equal zero */ 100: /* standard end of function */ pop {r0-r5} /*restaur others registers */ pop {fp,lr} /* restaur des 2 registers frame et return */ bx lr   /***************************************************/ /* division par 10 signé */ /* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/* /* and http://www.hackersdelight.org/ */ /***************************************************/ /* r0 contient le dividende */ /* r0 retourne le quotient */ /* r1 retourne le reste */ divisionpar10: /* r0 contains the argument to be divided by 10 */ push {r2-r4} /* save autres registres */ mov r4,r0 ldr r3, .Ls_magic_number_10 /* r1 <- magic_number */ smull r1, r2, r3, r0 /* r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0) */ mov r2, r2, ASR #2 /* r2 <- r2 >> 2 */ mov r1, r0, LSR #31 /* r1 <- r0 >> 31 */ add r0, r2, r1 /* r0 <- r2 + r1 */ add r2,r0,r0, lsl #2 /* r2 <- r0 * 5 */ sub r1,r4,r2, lsl #1 /* r1 <- r4 - (r2 * 2) = r4 - (r0 * 10) */ pop {r2-r4} bx lr /* leave function */ .align 4 .Ls_magic_number_10: .word 0x66666667      
http://rosettacode.org/wiki/Fast_Fourier_transform
Fast Fourier transform
Task Calculate the   FFT   (Fast Fourier Transform)   of an input sequence. The most general case allows for complex numbers at the input and results in a sequence of equal length, again of complex numbers. If you need to restrict yourself to real numbers, the output should be the magnitude   (i.e.:   sqrt(re2 + im2))   of the complex result. The classic version is the recursive Cooley–Tukey FFT. Wikipedia has pseudo-code for that. Further optimizations are possible but not required.
#Go
Go
package main   import ( "fmt" "math" "math/cmplx" )   func ditfft2(x []float64, y []complex128, n, s int) { if n == 1 { y[0] = complex(x[0], 0) return } ditfft2(x, y, n/2, 2*s) ditfft2(x[s:], y[n/2:], n/2, 2*s) for k := 0; k < n/2; k++ { tf := cmplx.Rect(1, -2*math.Pi*float64(k)/float64(n)) * y[k+n/2] y[k], y[k+n/2] = y[k]+tf, y[k]-tf } }   func main() { x := []float64{1, 1, 1, 1, 0, 0, 0, 0} y := make([]complex128, len(x)) ditfft2(x, y, len(x), 1) for _, c := range y { fmt.Printf("%8.4f\n", c) } }
http://rosettacode.org/wiki/Factors_of_a_Mersenne_number
Factors of a Mersenne number
A Mersenne number is a number in the form of 2P-1. If P is prime, the Mersenne number may be a Mersenne prime (if P is not prime, the Mersenne number is also not prime). In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before starting a, potentially lengthy, Lucas-Lehmer test. There are very efficient algorithms for determining if a number divides 2P-1 (or equivalently, if 2P mod (the number) = 1). Some languages already have built-in implementations of this exponent-and-mod operation (called modPow or similar). The following is how to implement this modPow yourself: For example, let's compute 223 mod 47. Convert the exponent 23 to binary, you get 10111. Starting with square = 1, repeatedly square it. Remove the top bit of the exponent, and if it's 1 multiply square by the base of the exponentiation (2), then compute square modulo 47. Use the result of the modulo from the last step as the initial value of square in the next step: remove optional square top bit multiply by 2 mod 47 ──────────── ─────── ───────────── ────── 1*1 = 1 1 0111 1*2 = 2 2 2*2 = 4 0 111 no 4 4*4 = 16 1 11 16*2 = 32 32 32*32 = 1024 1 1 1024*2 = 2048 27 27*27 = 729 1 729*2 = 1458 1 Since 223 mod 47 = 1, 47 is a factor of 2P-1. (To see this, subtract 1 from both sides: 223-1 = 0 mod 47.) Since we've shown that 47 is a factor, 223-1 is not prime. Further properties of Mersenne numbers allow us to refine the process even more. Any factor q of 2P-1 must be of the form 2kP+1, k being a positive integer or zero. Furthermore, q must be 1 or 7 mod 8. Finally any potential factor q must be prime. As in other trial division algorithms, the algorithm stops when 2kP+1 > sqrt(N). These primality tests only work on Mersenne numbers where P is prime. For example, M4=15 yields no factors using these techniques, but factors into 3 and 5, neither of which fit 2kP+1. Task Using the above method find a factor of 2929-1 (aka M929) Related tasks   count in factors   prime decomposition   factors of an integer   Sieve of Eratosthenes   primality by trial division   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division See also   Computers in 1948: 2127 - 1       (Note:   This video is no longer available because the YouTube account associated with this video has been terminated.)
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Function isPrime(n As Integer) As Boolean If n Mod 2 = 0 Then Return n = 2 If n Mod 3 = 0 Then Return n = 3 Dim d As Integer = 5 While d * d <= n If n Mod d = 0 Then Return False d += 2 If n Mod d = 0 Then Return False d += 4 Wend Return True End Function   ' test 929 plus all prime numbers below 100 which are known not to be Mersenne primes Dim q(1 To 16) As Integer = {11, 23, 29, 37, 41, 43, 47, 53, 59, 67, 71, 73, 79, 83, 97, 929} For k As Integer = 1 To 16 If isPrime(q(k)) Then Dim As Integer d, i, p, r = q(k) While r > 0 : r Shl= 1 : Wend d = 2 * q(k) + 1 Do i = 1 p = r While p <> 0 i = (i * i) Mod d If p < 0 Then i *= 2 If i > d Then i -= d p Shl= 1 Wend If i <> 1 Then d += 2 * q(k) Else Exit Do End If Loop Print "2^"; Str(q(k)); Tab(6); " - 1 = 0 (mod"; d; ")" Else Print Str(q(k)); " is not prime" End If Next Print Print "Press any key to quit" Sleep
http://rosettacode.org/wiki/Farey_sequence
Farey sequence
The   Farey sequence   Fn   of order   n   is the sequence of completely reduced fractions between   0   and   1   which, when in lowest terms, have denominators less than or equal to   n,   arranged in order of increasing size. The   Farey sequence   is sometimes incorrectly called a   Farey series. Each Farey sequence:   starts with the value   0   (zero),   denoted by the fraction     0 1 {\displaystyle {\frac {0}{1}}}   ends with the value   1   (unity),   denoted by the fraction   1 1 {\displaystyle {\frac {1}{1}}} . The Farey sequences of orders   1   to   5   are: F 1 = 0 1 , 1 1 {\displaystyle {\bf {\it {F}}}_{1}={\frac {0}{1}},{\frac {1}{1}}} F 2 = 0 1 , 1 2 , 1 1 {\displaystyle {\bf {\it {F}}}_{2}={\frac {0}{1}},{\frac {1}{2}},{\frac {1}{1}}} F 3 = 0 1 , 1 3 , 1 2 , 2 3 , 1 1 {\displaystyle {\bf {\it {F}}}_{3}={\frac {0}{1}},{\frac {1}{3}},{\frac {1}{2}},{\frac {2}{3}},{\frac {1}{1}}} F 4 = 0 1 , 1 4 , 1 3 , 1 2 , 2 3 , 3 4 , 1 1 {\displaystyle {\bf {\it {F}}}_{4}={\frac {0}{1}},{\frac {1}{4}},{\frac {1}{3}},{\frac {1}{2}},{\frac {2}{3}},{\frac {3}{4}},{\frac {1}{1}}} F 5 = 0 1 , 1 5 , 1 4 , 1 3 , 2 5 , 1 2 , 3 5 , 2 3 , 3 4 , 4 5 , 1 1 {\displaystyle {\bf {\it {F}}}_{5}={\frac {0}{1}},{\frac {1}{5}},{\frac {1}{4}},{\frac {1}{3}},{\frac {2}{5}},{\frac {1}{2}},{\frac {3}{5}},{\frac {2}{3}},{\frac {3}{4}},{\frac {4}{5}},{\frac {1}{1}}} Task   Compute and show the Farey sequence for orders   1   through   11   (inclusive).   Compute and display the   number   of fractions in the Farey sequence for order   100   through   1,000   (inclusive)   by hundreds.   Show the fractions as   n/d   (using the solidus [or slash] to separate the numerator from the denominator). The length   (the number of fractions)   of a Farey sequence asymptotically approaches: 3 × n2   ÷   π {\displaystyle \pi } 2 See also   OEIS sequence   A006842 numerators of Farey series of order 1, 2, ···   OEIS sequence   A006843 denominators of Farey series of order 1, 2, ···   OEIS sequence   A005728 number of fractions in Farey series of order n   MathWorld entry   Farey sequence   Wikipedia   entry   Farey sequence
#Pascal
Pascal
program Farey; {$IFDEF FPC }{$MODE DELPHI}{$ELSE}{$APPTYPE CONSOLE}{$ENDIF} uses sysutils; type tNextFarey= record nom,dom,n,c,d: longInt; end;   function InitFarey(maxdom:longINt):tNextFarey; Begin with result do Begin nom := 0; dom := 1; n := maxdom; c := 1; d := maxdom; end; end;   function NextFarey(var fn:tNextFarey):boolean; var k,tmp: longInt; Begin with fn do Begin k := trunc((n + dom)/d); tmp := c;c:= k*c-nom;nom:= tmp; tmp := d;d:= k*d-dom;dom:= tmp; result := nom <> dom; end; end;   procedure CheckFareyCount( num: NativeUint); var TestF : tNextFarey; cnt : NativeUint; Begin TestF:= InitFarey(num); cnt := 1; repeat inc(cnt); until NOT(NextFarey(TestF));   writeln('F(',TestF.n:4,') = ',cnt:7); end;   var TestF : tNextFarey; cnt: NativeInt; Begin   Writeln('Farey sequence for order 1 through 11 (inclusive): ');   For cnt := 1 to 11 do Begin TestF:= InitFarey(cnt); write('F(',cnt:2,') = '); repeat write(TestF.nom,'/',TestF.dom,','); until NOT(NextFarey(TestF)); writeln(TestF.nom,'/',TestF.dom); end; writeln; writeln('Number of fractions in the Farey sequence:'); cnt := 100; repeat CheckFareyCount(cnt); inc(cnt,100); until cnt > 1000; end.
http://rosettacode.org/wiki/Faulhaber%27s_triangle
Faulhaber's triangle
Named after Johann Faulhaber, the rows of Faulhaber's triangle are the coefficients of polynomials that represent sums of integer powers, which are extracted from Faulhaber's formula: ∑ k = 1 n k p = 1 p + 1 ∑ j = 0 p ( p + 1 j ) B j n p + 1 − j {\displaystyle \sum _{k=1}^{n}k^{p}={1 \over p+1}\sum _{j=0}^{p}{p+1 \choose j}B_{j}n^{p+1-j}} where B n {\displaystyle B_{n}} is the nth-Bernoulli number. The first 5 rows of Faulhaber's triangle, are: 1 1/2 1/2 1/6 1/2 1/3 0 1/4 1/2 1/4 -1/30 0 1/3 1/2 1/5 Using the third row of the triangle, we have: ∑ k = 1 n k 2 = 1 6 n + 1 2 n 2 + 1 3 n 3 {\displaystyle \sum _{k=1}^{n}k^{2}={1 \over 6}n+{1 \over 2}n^{2}+{1 \over 3}n^{3}} Task show the first 10 rows of Faulhaber's triangle. using the 18th row of Faulhaber's triangle, compute the sum: ∑ k = 1 1000 k 17 {\displaystyle \sum _{k=1}^{1000}k^{17}} (extra credit). See also Bernoulli numbers Evaluate binomial coefficients Faulhaber's formula (Wikipedia) Faulhaber's triangle (PDF)
#Racket
Racket
#lang racket (require math/number-theory)   (define (second-bernoulli-number n) (if (= n 1) 1/2 (bernoulli-number n)))   (define (faulhaber-row:formulaic p) (let ((p+1 (+ p 1))) (reverse (for/list ((j (in-range p+1))) (* (/ p+1) (second-bernoulli-number j) (binomial p+1 j))))))   (define (sum-k^p:formulaic p n) (for/sum ((f (faulhaber-row:formulaic p)) (i (in-naturals 1))) (* f (expt n i))))   (module+ main (map faulhaber-row:formulaic (range 10)) (sum-k^p:formulaic 17 1000))   (module+ test (require rackunit) (check-equal? (sum-k^p:formulaic 17 1000) (for/sum ((k (in-range 1 (add1 1000)))) (expt k 17))))
http://rosettacode.org/wiki/Faulhaber%27s_triangle
Faulhaber's triangle
Named after Johann Faulhaber, the rows of Faulhaber's triangle are the coefficients of polynomials that represent sums of integer powers, which are extracted from Faulhaber's formula: ∑ k = 1 n k p = 1 p + 1 ∑ j = 0 p ( p + 1 j ) B j n p + 1 − j {\displaystyle \sum _{k=1}^{n}k^{p}={1 \over p+1}\sum _{j=0}^{p}{p+1 \choose j}B_{j}n^{p+1-j}} where B n {\displaystyle B_{n}} is the nth-Bernoulli number. The first 5 rows of Faulhaber's triangle, are: 1 1/2 1/2 1/6 1/2 1/3 0 1/4 1/2 1/4 -1/30 0 1/3 1/2 1/5 Using the third row of the triangle, we have: ∑ k = 1 n k 2 = 1 6 n + 1 2 n 2 + 1 3 n 3 {\displaystyle \sum _{k=1}^{n}k^{2}={1 \over 6}n+{1 \over 2}n^{2}+{1 \over 3}n^{3}} Task show the first 10 rows of Faulhaber's triangle. using the 18th row of Faulhaber's triangle, compute the sum: ∑ k = 1 1000 k 17 {\displaystyle \sum _{k=1}^{1000}k^{17}} (extra credit). See also Bernoulli numbers Evaluate binomial coefficients Faulhaber's formula (Wikipedia) Faulhaber's triangle (PDF)
#Raku
Raku
# Helper subs   sub infix:<reduce> (\prev, \this) { this.key => this.key * (this.value - prev.value) }   sub next-bernoulli ( (:key($pm), :value(@pa)) ) { $pm + 1 => [ map *.value, [\reduce] ($pm + 2 ... 1) Z=> 1 / ($pm + 2), |@pa ] }   constant bernoulli = (0 => [1.FatRat], &next-bernoulli ... *).map: { .value[*-1] };   sub binomial (Int $n, Int $p) { combinations($n, $p).elems }   sub asRat (FatRat $r) { $r ?? $r.denominator == 1 ?? $r.numerator !! $r.nude.join('/') !! 0 }     # The task sub faulhaber_triangle ($p) { map { binomial($p + 1, $_) * bernoulli[$_] / ($p + 1) }, ($p ... 0) }   # First 10 rows of Faulhaber's triangle: say faulhaber_triangle($_)».&asRat.fmt('%5s') for ^10; say '';   # Extra credit: my $p = 17; my $n = 1000; say sum faulhaber_triangle($p).kv.map: { $^value * $n**($^key + 1) }
http://rosettacode.org/wiki/Faulhaber%27s_formula
Faulhaber's formula
In mathematics,   Faulhaber's formula,   named after Johann Faulhaber,   expresses the sum of the p-th powers of the first n positive integers as a (p + 1)th-degree polynomial function of n,   the coefficients involving Bernoulli numbers. Task Generate the first 10 closed-form expressions, starting with p = 0. Related tasks   Bernoulli numbers.   evaluate binomial coefficients. See also   The Wikipedia entry:   Faulhaber's formula.   The Wikipedia entry:   Bernoulli numbers.   The Wikipedia entry:   binomial coefficients.
#Raku
Raku
sub bernoulli_number($n) {   return 1/2 if $n == 1; return 0/1 if $n % 2;   my @A; for 0..$n -> $m { @A[$m] = 1 / ($m + 1); for $m, $m-1 ... 1 -> $j { @A[$j - 1] = $j * (@A[$j - 1] - @A[$j]); } }   return @A[0]; }   sub binomial($n, $k) { $k == 0 || $n == $k ?? 1 !! binomial($n-1, $k-1) + binomial($n-1, $k); }   sub faulhaber_s_formula($p) {   my @formula = gather for 0..$p -> $j { take '(' ~ join('/', (binomial($p+1, $j) * bernoulli_number($j)).Rat.nude) ~ ")*n^{$p+1 - $j}"; }   my $formula = join(' + ', @formula.grep({!m{'(0/1)*'}}));   $formula .= subst(rx{ '(1/1)*' }, '', :g); $formula .= subst(rx{ '^1'» }, '', :g);   "1/{$p+1} * ($formula)"; }   for 0..9 -> $p { say "f($p) = ", faulhaber_s_formula($p); }
http://rosettacode.org/wiki/Fibonacci_n-step_number_sequences
Fibonacci n-step number sequences
These number series are an expansion of the ordinary Fibonacci sequence where: For n = 2 {\displaystyle n=2} we have the Fibonacci sequence; with initial values [ 1 , 1 ] {\displaystyle [1,1]} and F k 2 = F k − 1 2 + F k − 2 2 {\displaystyle F_{k}^{2}=F_{k-1}^{2}+F_{k-2}^{2}} For n = 3 {\displaystyle n=3} we have the tribonacci sequence; with initial values [ 1 , 1 , 2 ] {\displaystyle [1,1,2]} and F k 3 = F k − 1 3 + F k − 2 3 + F k − 3 3 {\displaystyle F_{k}^{3}=F_{k-1}^{3}+F_{k-2}^{3}+F_{k-3}^{3}} For n = 4 {\displaystyle n=4} we have the tetranacci sequence; with initial values [ 1 , 1 , 2 , 4 ] {\displaystyle [1,1,2,4]} and F k 4 = F k − 1 4 + F k − 2 4 + F k − 3 4 + F k − 4 4 {\displaystyle F_{k}^{4}=F_{k-1}^{4}+F_{k-2}^{4}+F_{k-3}^{4}+F_{k-4}^{4}} ... For general n > 2 {\displaystyle n>2} we have the Fibonacci n {\displaystyle n} -step sequence - F k n {\displaystyle F_{k}^{n}} ; with initial values of the first n {\displaystyle n} values of the ( n − 1 ) {\displaystyle (n-1)} 'th Fibonacci n {\displaystyle n} -step sequence F k n − 1 {\displaystyle F_{k}^{n-1}} ; and k {\displaystyle k} 'th value of this n {\displaystyle n} 'th sequence being F k n = ∑ i = 1 ( n ) F k − i ( n ) {\displaystyle F_{k}^{n}=\sum _{i=1}^{(n)}{F_{k-i}^{(n)}}} For small values of n {\displaystyle n} , Greek numeric prefixes are sometimes used to individually name each series. Fibonacci n {\displaystyle n} -step sequences n {\displaystyle n} Series name Values 2 fibonacci 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ... 3 tribonacci 1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ... 4 tetranacci 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ... 5 pentanacci 1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ... 6 hexanacci 1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ... 7 heptanacci 1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ... 8 octonacci 1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ... 9 nonanacci 1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ... 10 decanacci 1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ... Allied sequences can be generated where the initial values are changed: The Lucas series sums the two preceding values like the fibonacci series for n = 2 {\displaystyle n=2} but uses [ 2 , 1 ] {\displaystyle [2,1]} as its initial values. Task Write a function to generate Fibonacci n {\displaystyle n} -step number sequences given its initial values and assuming the number of initial values determines how many previous values are summed to make the next number of the series. Use this to print and show here at least the first ten members of the Fibo/tribo/tetra-nacci and Lucas sequences. Related tasks   Fibonacci sequence   Wolfram Mathworld   Hofstadter Q sequence‎   Leonardo numbers Also see   Lucas Numbers - Numberphile (Video)   Tribonacci Numbers (and the Rauzy Fractal) - Numberphile (Video)   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#Forth
Forth
: length @ ; \ length of an array is stored at its address : a{ here cell allot ; : } , here over - cell / over ! ;   defer nacci   : step ( a- i n -- a- i m ) >r 1- 2dup nacci r> + ;   : steps ( a- i n -- m ) 0 tuck do step loop nip nip ;   :noname ( a- i -- n ) over length over > \ if i is within the array if cells + @ \ fetch i...if not, else over length 1- steps \ get length of array for calling step and recurse then ; is nacci   : show-nacci 11 1 do dup i nacci . loop cr drop ;   ." fibonacci: " a{ 1 , 1 } show-nacci ." tribonacci: " a{ 1 , 1 , 2 } show-nacci ." tetranacci: " a{ 1 , 1 , 2 , 4 } show-nacci ." lucas: " a{ 2 , 1 } show-nacci  
http://rosettacode.org/wiki/Find_common_directory_path
Find common directory path
Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories. Test your routine using the forward slash '/' character as the directory separator and the following three strings as input paths: '/home/user1/tmp/coverage/test' '/home/user1/tmp/covert/operator' '/home/user1/tmp/coven/members' Note: The resultant path should be the valid directory '/home/user1/tmp' and not the longest common string '/home/user1/tmp/cove'. If your language has a routine that performs this function (even if it does not have a changeable separator character), then mention it as part of the task. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#TUSCRIPT
TUSCRIPT
  $$ MODE TUSCRIPT common="" dir1="/home/user1/tmp/coverage/test" dir2="/home/user1/tmp/covert/operator" dir3="/home/user1/tmp/coven/members" dir1=SPLIT (dir1,":/:"),dir2=SPLIT (dir2,":/:"), dir3=SPLIT (dir3,":/:") LOOP d1=dir1,d2=dir2,d3=dir3 IF (d1==d2,d3) THEN common=APPEND(common,d1,"/") ELSE PRINT common EXIT ENDIF ENDLOOP  
http://rosettacode.org/wiki/Find_common_directory_path
Find common directory path
Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories. Test your routine using the forward slash '/' character as the directory separator and the following three strings as input paths: '/home/user1/tmp/coverage/test' '/home/user1/tmp/covert/operator' '/home/user1/tmp/coven/members' Note: The resultant path should be the valid directory '/home/user1/tmp' and not the longest common string '/home/user1/tmp/cove'. If your language has a routine that performs this function (even if it does not have a changeable separator character), then mention it as part of the task. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#UNIX_Shell
UNIX Shell
  #!/bin/sh   pathlist='/home/user1/tmp/coverage/test /home/user1/tmp/covert/operator /home/user1/tmp/coven/members'   i=2   while [ $i -lt 100 ] do path=`echo "$pathlist" | cut -f1-$i -d/ | uniq -d` if [ -z "$path" ] then echo $prev_path break else prev_path=$path fi i=`expr $i + 1` done  
http://rosettacode.org/wiki/Filter
Filter
Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Type FilterType As Function(As Integer) As Boolean   Function isEven(n As Integer) As Boolean Return n Mod 2 = 0 End Function   Sub filterArray(a() As Integer, b() As Integer, filter As FilterType) If UBound(a) = -1 Then Return '' empty array Dim count As Integer = 0 Redim b(0 To UBound(a) - LBound(a)) For i As Integer = LBound(a) To UBound(a) If filter(a(i)) Then b(count) = a(i) count += 1 End If Next   If count > 0 Then Redim Preserve b(0 To count - 1) '' trim excess elements End Sub   ' Note that da() must be a dynamic array as static arrays can't be redimensioned Sub filterDestructArray(da() As Integer, filter As FilterType) If UBound(da) = -1 Then Return '' empty array Dim count As Integer = 0 For i As Integer = LBound(da) To UBound(da) If i > UBound(da) - count Then Exit For If Not filter(da(i)) Then '' remove this element by moving those still to be examined down one For j As Integer = i + 1 To UBound(da) - count da(j - 1) = da(j) Next j count += 1 i -= 1 End If Next i   If count > 0 Then Redim Preserve da(LBound(da) To UBound(da) - count) '' trim excess elements End If End Sub   Dim n As Integer = 12 Dim a(1 To n) As Integer '' creates dynamic array as upper bound is a variable For i As Integer = 1 To n : Read a(i) : Next Dim b() As Integer '' array to store results filterArray a(), b(), @isEven Print "The even numbers are (in new array)  : "; For i As Integer = LBound(b) To UBound(b) Print b(i); " "; Next Print : Print filterDestructArray a(), @isEven Print "The even numbers are (in original array) : "; For i As Integer = LBound(a) To UBound(a) Print a(i); " "; Next Print : Print Print "Press any key to quit" Sleep End   Data 1, 2, 3, 7, 8, 10, 11, 16, 19, 21, 22, 27
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) The   FizzBuzz   problem was presented as the lowest level of comprehension required to illustrate adequacy. Also see   (a blog)   dont-overthink-fizzbuzz   (a blog)   fizzbuzz-the-programmers-stairway-to-heaven
#Ioke
Ioke
(1..100) each(x, cond( (x % 15) zero?, "FizzBuzz" println, (x % 3) zero?, "Fizz" println, (x % 5) zero?, "Buzz" println ) )
http://rosettacode.org/wiki/File_size
File size
Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
#Visual_Basic_.NET
Visual Basic .NET
Dim local As New IO.FileInfo("input.txt") Console.WriteLine(local.Length)   Dim root As New IO.FileInfo("\input.txt") Console.WriteLine(root.Length)
http://rosettacode.org/wiki/File_size
File size
Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
#Wren
Wren
import "io" for File   var name = "input.txt" System.print("'%(name)' has a a size of %(File.size(name)) bytes")
http://rosettacode.org/wiki/File_size
File size
Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
#X86_Assembly
X86 Assembly
  ; x86_64 linux nasm   section .data localFileName: db "input.txt", 0 rootFileName: db "/initrd.img", 0   section .text   global _start   _start:    ; open file in current dir mov rax, 2 mov rdi, localFileName xor rsi, rsi mov rdx, 0 syscall push rax   mov rdi, rax ; file descriptior mov rsi, 0 ; offset mov rdx, 2 ; whence mov rax, 8 ; sys_lseek syscall    ; compare result to actual size cmp rax, 11 jne fail    ; close the file pop rdi mov rax, 3 syscall    ; open file in root dir mov rax, 2 mov rdi, rootFileName xor rsi, rsi mov rdx, 0 syscall push rax   mov rdi, rax ; file descriptior mov rsi, 0 ; offset mov rdx, 2 ; whence mov rax, 8 ; sys_lseek syscall    ; compare result to actual size cmp rax, 37722243 jne fail    ; close the file pop rdi mov rax, 3 syscall    ; test successful mov rax, 60 mov rdi, 0 syscall    ; test failed fail: mov rax, 60 mov rdi, 1 syscall  
http://rosettacode.org/wiki/File_input/output
File input/output
File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file into a variable   how to write a variable's contents into a file Oneliners that skip the intermediate variable are of secondary interest — operating systems have copy commands for that.
#Mercury
Mercury
:- module file_io. :- interface.   :- import_module io. :- pred main(io::di, io::uo) is det.   :- implementation.   main(!IO) :- io.open_input("input.txt", InputRes, !IO), ( InputRes = ok(Input), io.read_file_as_string(Input, ReadRes, !IO), ( ReadRes = ok(Contents), io.close_input(Input, !IO), io.open_output("output.txt", OutputRes, !IO), ( OutputRes = ok(Output), io.write_string(Output, Contents, !IO), io.close_output(Output, !IO)  ; OutputRes = error(OutputError), print_io_error(OutputError, !IO) )  ; ReadRes = error(_, ReadError), print_io_error(ReadError, !IO) )  ; InputRes = error(InputError), print_io_error(InputError, !IO) ).   :- pred print_io_error(io.error::in, io::di, io::uo) is det.   print_io_error(Error, !IO) :- io.stderr_stream(Stderr, !IO), io.write_string(Stderr, io.error_message(Error), !IO), io.set_exit_status(1, !IO).
http://rosettacode.org/wiki/File_input/output
File input/output
File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file into a variable   how to write a variable's contents into a file Oneliners that skip the intermediate variable are of secondary interest — operating systems have copy commands for that.
#mIRC_Scripting_Language
mIRC Scripting Language
alias Write2FileAndReadIt { .write myfilename.txt Goodbye Mike! .echo -a Myfilename.txt contains: $read(myfilename.txt,1) }
http://rosettacode.org/wiki/Fibonacci_word
Fibonacci word
The   Fibonacci Word   may be created in a manner analogous to the   Fibonacci Sequence   as described here: Define   F_Word1   as   1 Define   F_Word2   as   0 Form     F_Word3   as   F_Word2     concatenated with   F_Word1   i.e.:   01 Form     F_Wordn   as   F_Wordn-1   concatenated with   F_wordn-2 Task Perform the above steps for     n = 37. You may display the first few but not the larger values of   n. {Doing so will get the task's author into trouble with them what be (again!).} Instead, create a table for   F_Words   1   to   37   which shows:   The number of characters in the word   The word's Entropy Related tasks   Fibonacci word/fractal   Entropy   Entropy/Narcissist
#Racket
Racket
#lang racket (provide F-Word gen-F-Word (struct-out f-word) f-word-max-length) (require "entropy.rkt") ; save Entropy task implementation as "entropy.rkt"   (define f-word-max-length (make-parameter 80)) (define-struct f-word (str length count-0 count-1)) (define (string->f-word str) (apply f-word str (call-with-values (λ () (for/fold ((l 0) (zeros 0) (ones 0)) ((c str)) (match c (#\0 (values (add1 l) (add1 zeros) ones)) (#\1 (values (add1 l) zeros (add1 ones)))))) list))) (define F-Word# (make-hash))   (define (gen-F-Word n #:key-id key-id #:word-1 word-1 #:word-2 word-2 #:merge-fn merge-fn) (define sub-F-Word (match-lambda (1 word-1) (2 word-2) ((? number? n) (merge-fn n)))) (hash-ref! F-Word# (list key-id (f-word-max-length) n) (λ () (sub-F-Word n))))   (define (F-Word n) (define f-word-1 (string->f-word "1")) (define f-word-2 (string->f-word "0")) (define (f-word-merge>2 n) (define f-1 (F-Word (- n 1))) (define f-2 (F-Word (- n 2))) (define length+ (+ (f-word-length f-1) (f-word-length f-2))) (define count-0+ (+ (f-word-count-0 f-1) (f-word-count-0 f-2))) (define count-1+ (+ (f-word-count-1 f-1) (f-word-count-1 f-2))) (define str+ (if (and (f-word-max-length) (> length+ (f-word-max-length))) (format "<string too long (~a)>" length+) (string-append (f-word-str f-1) (f-word-str f-2)))) (f-word str+ length+ count-0+ count-1+))   (gen-F-Word n #:key-id 'words #:word-1 f-word-1 #:word-2 f-word-2 #:merge-fn f-word-merge>2))   (module+ main (parameterize ((f-word-max-length 80)) (for ((n (sequence-map add1 (in-range 37)))) (define W (F-Word n)) (define e (hash-entropy (hash 0 (f-word-count-0 W) 1 (f-word-count-1 W)))) (printf "~a ~a ~a ~a~%" (~a n #:width 3 #:align 'right) (~a (f-word-length W) #:width 9 #:align 'right) (real->decimal-string e 12) (~a (f-word-str W))))))   (module+ test (require rackunit) (check-match (F-Word 4) (f-word "010" _ _ _)) (check-match (F-Word 5) (f-word "01001" _ _ _)) (check-match (F-Word 8) (f-word "010010100100101001010" _ _ _)))
http://rosettacode.org/wiki/Fibonacci_word
Fibonacci word
The   Fibonacci Word   may be created in a manner analogous to the   Fibonacci Sequence   as described here: Define   F_Word1   as   1 Define   F_Word2   as   0 Form     F_Word3   as   F_Word2     concatenated with   F_Word1   i.e.:   01 Form     F_Wordn   as   F_Wordn-1   concatenated with   F_wordn-2 Task Perform the above steps for     n = 37. You may display the first few but not the larger values of   n. {Doing so will get the task's author into trouble with them what be (again!).} Instead, create a table for   F_Words   1   to   37   which shows:   The number of characters in the word   The word's Entropy Related tasks   Fibonacci word/fractal   Entropy   Entropy/Narcissist
#Raku
Raku
constant @fib-word = 1, 0, { $^b ~ $^a } ... *;   sub entropy { -log(2) R/ [+] map -> \p { p * log p }, $^string.comb.Bag.values »/» $string.chars } for @fib-word[^37] { printf "%5d\t%10d\t%.8e\t%s\n", (state $n)++, .chars, .&entropy, $n > 10 ?? '' !! $_; }
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: Fn = Fn+2 - Fn+1, if n<0 support for negative     n     in the solution is optional. Related tasks   Fibonacci n-step number sequences‎   Leonardo numbers References   Wikipedia, Fibonacci number   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#ALGOL_60
ALGOL 60
begin comment Fibonacci sequence; integer procedure fibonacci(n); value n; integer n; begin integer i, fn, fn1, fn2; fn2 := 1; fn1 := 0; fn  := 0; for i := 1 step 1 until n do begin fn  := fn1 + fn2; fn2 := fn1; fn1 := fn end; fibonacci := fn end fibonacci;   integer i; for i := 0 step 1 until 20 do outinteger(1,fibonacci(i)) end
http://rosettacode.org/wiki/Factors_of_an_integer
Factors of an integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Compute the   factors   of a positive integer. These factors are the positive integers by which the number being factored can be divided to yield a positive integer result. (Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty;   this task does not require handling of either of these cases). Note that every prime number has two factors:   1   and itself. Related tasks   count in factors   prime decomposition   Sieve of Eratosthenes   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division   sequence: smallest number greater than previous term with exactly n divisors
#Arturo
Arturo
factors: $[num][ select 1..num [x][ (num%x)=0 ] ]   print factors 36
http://rosettacode.org/wiki/Fast_Fourier_transform
Fast Fourier transform
Task Calculate the   FFT   (Fast Fourier Transform)   of an input sequence. The most general case allows for complex numbers at the input and results in a sequence of equal length, again of complex numbers. If you need to restrict yourself to real numbers, the output should be the magnitude   (i.e.:   sqrt(re2 + im2))   of the complex result. The classic version is the recursive Cooley–Tukey FFT. Wikipedia has pseudo-code for that. Further optimizations are possible but not required.
#Golfscript
Golfscript
#Cooley-Tukey   {.,.({[\.2%fft\(;2%fft@-1?-1\?-2?:w;.,,{w\?}%[\]zip{{*}*}%]zip.{{+}*}%\{{-}*}%+}{;}if}:fft;   [1 1 1 1 0 0 0 0]fft n*  
http://rosettacode.org/wiki/Factors_of_a_Mersenne_number
Factors of a Mersenne number
A Mersenne number is a number in the form of 2P-1. If P is prime, the Mersenne number may be a Mersenne prime (if P is not prime, the Mersenne number is also not prime). In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before starting a, potentially lengthy, Lucas-Lehmer test. There are very efficient algorithms for determining if a number divides 2P-1 (or equivalently, if 2P mod (the number) = 1). Some languages already have built-in implementations of this exponent-and-mod operation (called modPow or similar). The following is how to implement this modPow yourself: For example, let's compute 223 mod 47. Convert the exponent 23 to binary, you get 10111. Starting with square = 1, repeatedly square it. Remove the top bit of the exponent, and if it's 1 multiply square by the base of the exponentiation (2), then compute square modulo 47. Use the result of the modulo from the last step as the initial value of square in the next step: remove optional square top bit multiply by 2 mod 47 ──────────── ─────── ───────────── ────── 1*1 = 1 1 0111 1*2 = 2 2 2*2 = 4 0 111 no 4 4*4 = 16 1 11 16*2 = 32 32 32*32 = 1024 1 1 1024*2 = 2048 27 27*27 = 729 1 729*2 = 1458 1 Since 223 mod 47 = 1, 47 is a factor of 2P-1. (To see this, subtract 1 from both sides: 223-1 = 0 mod 47.) Since we've shown that 47 is a factor, 223-1 is not prime. Further properties of Mersenne numbers allow us to refine the process even more. Any factor q of 2P-1 must be of the form 2kP+1, k being a positive integer or zero. Furthermore, q must be 1 or 7 mod 8. Finally any potential factor q must be prime. As in other trial division algorithms, the algorithm stops when 2kP+1 > sqrt(N). These primality tests only work on Mersenne numbers where P is prime. For example, M4=15 yields no factors using these techniques, but factors into 3 and 5, neither of which fit 2kP+1. Task Using the above method find a factor of 2929-1 (aka M929) Related tasks   count in factors   prime decomposition   factors of an integer   Sieve of Eratosthenes   primality by trial division   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division See also   Computers in 1948: 2127 - 1       (Note:   This video is no longer available because the YouTube account associated with this video has been terminated.)
#Frink
Frink
for p = primes[] if modPow[2, 929, p] - 1 == 0 println[p]
http://rosettacode.org/wiki/Factors_of_a_Mersenne_number
Factors of a Mersenne number
A Mersenne number is a number in the form of 2P-1. If P is prime, the Mersenne number may be a Mersenne prime (if P is not prime, the Mersenne number is also not prime). In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before starting a, potentially lengthy, Lucas-Lehmer test. There are very efficient algorithms for determining if a number divides 2P-1 (or equivalently, if 2P mod (the number) = 1). Some languages already have built-in implementations of this exponent-and-mod operation (called modPow or similar). The following is how to implement this modPow yourself: For example, let's compute 223 mod 47. Convert the exponent 23 to binary, you get 10111. Starting with square = 1, repeatedly square it. Remove the top bit of the exponent, and if it's 1 multiply square by the base of the exponentiation (2), then compute square modulo 47. Use the result of the modulo from the last step as the initial value of square in the next step: remove optional square top bit multiply by 2 mod 47 ──────────── ─────── ───────────── ────── 1*1 = 1 1 0111 1*2 = 2 2 2*2 = 4 0 111 no 4 4*4 = 16 1 11 16*2 = 32 32 32*32 = 1024 1 1 1024*2 = 2048 27 27*27 = 729 1 729*2 = 1458 1 Since 223 mod 47 = 1, 47 is a factor of 2P-1. (To see this, subtract 1 from both sides: 223-1 = 0 mod 47.) Since we've shown that 47 is a factor, 223-1 is not prime. Further properties of Mersenne numbers allow us to refine the process even more. Any factor q of 2P-1 must be of the form 2kP+1, k being a positive integer or zero. Furthermore, q must be 1 or 7 mod 8. Finally any potential factor q must be prime. As in other trial division algorithms, the algorithm stops when 2kP+1 > sqrt(N). These primality tests only work on Mersenne numbers where P is prime. For example, M4=15 yields no factors using these techniques, but factors into 3 and 5, neither of which fit 2kP+1. Task Using the above method find a factor of 2929-1 (aka M929) Related tasks   count in factors   prime decomposition   factors of an integer   Sieve of Eratosthenes   primality by trial division   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division See also   Computers in 1948: 2127 - 1       (Note:   This video is no longer available because the YouTube account associated with this video has been terminated.)
#GAP
GAP
MersenneSmallFactor := function(n) local k, m, d; if IsPrime(n) then d := 2*n; m := 1; for k in [1 .. 1000000] do m := m + d; if PowerModInt(2, n, m) = 1 then return m; fi; od; fi; return fail; end;     # If n is not prime, fail immediately MersenneSmallFactor(15); # fail   MersenneSmallFactor(929); # 13007   MersenneSmallFactor(1009); # 3454817   # We stop at k = 1000000 in 2*k*n + 1, so it may fail if 2^n - 1 has only larger factors MersenneSmallFactor(101); # fail   FactorsInt(2^101-1); # [ 7432339208719, 341117531003194129 ]
http://rosettacode.org/wiki/Farey_sequence
Farey sequence
The   Farey sequence   Fn   of order   n   is the sequence of completely reduced fractions between   0   and   1   which, when in lowest terms, have denominators less than or equal to   n,   arranged in order of increasing size. The   Farey sequence   is sometimes incorrectly called a   Farey series. Each Farey sequence:   starts with the value   0   (zero),   denoted by the fraction     0 1 {\displaystyle {\frac {0}{1}}}   ends with the value   1   (unity),   denoted by the fraction   1 1 {\displaystyle {\frac {1}{1}}} . The Farey sequences of orders   1   to   5   are: F 1 = 0 1 , 1 1 {\displaystyle {\bf {\it {F}}}_{1}={\frac {0}{1}},{\frac {1}{1}}} F 2 = 0 1 , 1 2 , 1 1 {\displaystyle {\bf {\it {F}}}_{2}={\frac {0}{1}},{\frac {1}{2}},{\frac {1}{1}}} F 3 = 0 1 , 1 3 , 1 2 , 2 3 , 1 1 {\displaystyle {\bf {\it {F}}}_{3}={\frac {0}{1}},{\frac {1}{3}},{\frac {1}{2}},{\frac {2}{3}},{\frac {1}{1}}} F 4 = 0 1 , 1 4 , 1 3 , 1 2 , 2 3 , 3 4 , 1 1 {\displaystyle {\bf {\it {F}}}_{4}={\frac {0}{1}},{\frac {1}{4}},{\frac {1}{3}},{\frac {1}{2}},{\frac {2}{3}},{\frac {3}{4}},{\frac {1}{1}}} F 5 = 0 1 , 1 5 , 1 4 , 1 3 , 2 5 , 1 2 , 3 5 , 2 3 , 3 4 , 4 5 , 1 1 {\displaystyle {\bf {\it {F}}}_{5}={\frac {0}{1}},{\frac {1}{5}},{\frac {1}{4}},{\frac {1}{3}},{\frac {2}{5}},{\frac {1}{2}},{\frac {3}{5}},{\frac {2}{3}},{\frac {3}{4}},{\frac {4}{5}},{\frac {1}{1}}} Task   Compute and show the Farey sequence for orders   1   through   11   (inclusive).   Compute and display the   number   of fractions in the Farey sequence for order   100   through   1,000   (inclusive)   by hundreds.   Show the fractions as   n/d   (using the solidus [or slash] to separate the numerator from the denominator). The length   (the number of fractions)   of a Farey sequence asymptotically approaches: 3 × n2   ÷   π {\displaystyle \pi } 2 See also   OEIS sequence   A006842 numerators of Farey series of order 1, 2, ···   OEIS sequence   A006843 denominators of Farey series of order 1, 2, ···   OEIS sequence   A005728 number of fractions in Farey series of order n   MathWorld entry   Farey sequence   Wikipedia   entry   Farey sequence
#Perl
Perl
use warnings; use strict; use Math::BigRat; use ntheory qw/euler_phi vecsum/;   sub farey { my $N = shift; my @f; my($m0,$n0, $m1,$n1) = (0, 1, 1, $N); push @f, Math::BigRat->new("$m0/$n0"); push @f, Math::BigRat->new("$m1/$n1"); while ($f[-1] < 1) { my $m = int( ($n0 + $N) / $n1) * $m1 - $m0; my $n = int( ($n0 + $N) / $n1) * $n1 - $n0; ($m0,$n0, $m1,$n1) = ($m1,$n1, $m,$n); push @f, Math::BigRat->new("$m/$n"); } @f; } sub farey_count { 1 + vecsum(euler_phi(1, shift)); }   for (1 .. 11) { my @f = map { join "/", $_->parts } # Force 0/1 and 1/1 farey($_); print "F$_: [@f]\n"; } for (1 .. 10, 100000) { print "F${_}00: ", farey_count(100*$_), " members\n"; }
http://rosettacode.org/wiki/Faulhaber%27s_triangle
Faulhaber's triangle
Named after Johann Faulhaber, the rows of Faulhaber's triangle are the coefficients of polynomials that represent sums of integer powers, which are extracted from Faulhaber's formula: ∑ k = 1 n k p = 1 p + 1 ∑ j = 0 p ( p + 1 j ) B j n p + 1 − j {\displaystyle \sum _{k=1}^{n}k^{p}={1 \over p+1}\sum _{j=0}^{p}{p+1 \choose j}B_{j}n^{p+1-j}} where B n {\displaystyle B_{n}} is the nth-Bernoulli number. The first 5 rows of Faulhaber's triangle, are: 1 1/2 1/2 1/6 1/2 1/3 0 1/4 1/2 1/4 -1/30 0 1/3 1/2 1/5 Using the third row of the triangle, we have: ∑ k = 1 n k 2 = 1 6 n + 1 2 n 2 + 1 3 n 3 {\displaystyle \sum _{k=1}^{n}k^{2}={1 \over 6}n+{1 \over 2}n^{2}+{1 \over 3}n^{3}} Task show the first 10 rows of Faulhaber's triangle. using the 18th row of Faulhaber's triangle, compute the sum: ∑ k = 1 1000 k 17 {\displaystyle \sum _{k=1}^{1000}k^{17}} (extra credit). See also Bernoulli numbers Evaluate binomial coefficients Faulhaber's formula (Wikipedia) Faulhaber's triangle (PDF)
#REXX
REXX
Numeric Digits 100 Do r=0 To 20 ra=r-1 If r=0 Then f.r.1=1 Else Do rsum=0 Do c=2 To r+1 ca=c-1 f.r.c=fdivide(fmultiply(f.ra.ca,r),c) rsum=fsum(rsum,f.r.c) End f.r.1=fsubtract(1,rsum) End End Do r=0 To 9 ol='' Do c=1 To r+1 ol=ol right(f.r.c,5) End Say ol End Say '' x=0 Do c=1 To 18 x=fsum(x,fmultiply(f.17.c,(1000**c))) End Say k(x) s=0 Do k=1 To 1000 s=s+k**17 End Say s Exit   fmultiply: Procedure Parse Arg a,b Parse Var a ad '/' an Parse Var b bd '/' bn If an='' Then an=1 If bn='' Then bn=1 res=(abs(ad)*abs(bd))'/'||(an*bn) Return s(ad,bd)k(res)   fdivide: Procedure Parse Arg a,b Parse Var a ad '/' an Parse Var b bd '/' bn If an='' Then an=1 If bn='' Then bn=1 res=s(ad,bd)(abs(ad)*bn)'/'||(an*abs(bd)) Return k(res)   fsum: Procedure Parse Arg a,b Parse Var a ad '/' an Parse Var b bd '/' bn If an='' Then an=1 If bn='' Then bn=1 n=an*bn d=ad*bn+bd*an res=d'/'n Return k(res)   fsubtract: Procedure Parse Arg a,b Parse Var a ad '/' an Parse Var b bd '/' bn If an='' Then an=1 If bn='' Then bn=1 n=an*bn d=ad*bn-bd*an res=d'/'n Return k(res)   s: Procedure Parse Arg ad,bd s=sign(ad)*sign(bd) If s<0 Then Return '-' Else Return ''   k: Procedure Parse Arg a Parse Var a ad '/' an Select When ad=0 Then Return 0 When an=1 Then Return ad Otherwise Do g=gcd(ad,an) ad=ad/g an=an/g Return ad'/'an End End   gcd: procedure Parse Arg a,b if b = 0 then return abs(a) return gcd(b,a//b)
http://rosettacode.org/wiki/Faulhaber%27s_formula
Faulhaber's formula
In mathematics,   Faulhaber's formula,   named after Johann Faulhaber,   expresses the sum of the p-th powers of the first n positive integers as a (p + 1)th-degree polynomial function of n,   the coefficients involving Bernoulli numbers. Task Generate the first 10 closed-form expressions, starting with p = 0. Related tasks   Bernoulli numbers.   evaluate binomial coefficients. See also   The Wikipedia entry:   Faulhaber's formula.   The Wikipedia entry:   Bernoulli numbers.   The Wikipedia entry:   binomial coefficients.
#Ruby
Ruby
def binomial(n,k) if n < 0 or k < 0 or n < k then return -1 end if n == 0 or k == 0 then return 1 end   num = 1 for i in k+1 .. n do num = num * i end   denom = 1 for i in 2 .. n-k do denom = denom * i end   return num / denom end   def bernoulli(n) if n < 0 then raise "n cannot be less than zero" end   a = Array.new(16) for m in 0 .. n do a[m] = Rational(1, m + 1) for j in m.downto(1) do a[j-1] = (a[j-1] - a[j]) * Rational(j) end end   if n != 1 then return a[0] end return -a[0] end   def faulhaber(p) print("%d : " % [p]) q = Rational(1, p + 1) sign = -1 for j in 0 .. p do sign = -1 * sign coeff = q * Rational(sign) * Rational(binomial(p+1, j)) * bernoulli(j) if coeff == 0 then next end if j == 0 then if coeff != 1 then if coeff == -1 then print "-" else print coeff end end else if coeff == 1 then print " + " elsif coeff == -1 then print " - " elsif 0 < coeff then print " + " print coeff else print " - " print -coeff end end pwr = p + 1 - j if pwr > 1 then print "n^%d" % [pwr] else print "n" end end print "\n" end   def main for i in 0 .. 9 do faulhaber(i) end end   main()
http://rosettacode.org/wiki/Fibonacci_n-step_number_sequences
Fibonacci n-step number sequences
These number series are an expansion of the ordinary Fibonacci sequence where: For n = 2 {\displaystyle n=2} we have the Fibonacci sequence; with initial values [ 1 , 1 ] {\displaystyle [1,1]} and F k 2 = F k − 1 2 + F k − 2 2 {\displaystyle F_{k}^{2}=F_{k-1}^{2}+F_{k-2}^{2}} For n = 3 {\displaystyle n=3} we have the tribonacci sequence; with initial values [ 1 , 1 , 2 ] {\displaystyle [1,1,2]} and F k 3 = F k − 1 3 + F k − 2 3 + F k − 3 3 {\displaystyle F_{k}^{3}=F_{k-1}^{3}+F_{k-2}^{3}+F_{k-3}^{3}} For n = 4 {\displaystyle n=4} we have the tetranacci sequence; with initial values [ 1 , 1 , 2 , 4 ] {\displaystyle [1,1,2,4]} and F k 4 = F k − 1 4 + F k − 2 4 + F k − 3 4 + F k − 4 4 {\displaystyle F_{k}^{4}=F_{k-1}^{4}+F_{k-2}^{4}+F_{k-3}^{4}+F_{k-4}^{4}} ... For general n > 2 {\displaystyle n>2} we have the Fibonacci n {\displaystyle n} -step sequence - F k n {\displaystyle F_{k}^{n}} ; with initial values of the first n {\displaystyle n} values of the ( n − 1 ) {\displaystyle (n-1)} 'th Fibonacci n {\displaystyle n} -step sequence F k n − 1 {\displaystyle F_{k}^{n-1}} ; and k {\displaystyle k} 'th value of this n {\displaystyle n} 'th sequence being F k n = ∑ i = 1 ( n ) F k − i ( n ) {\displaystyle F_{k}^{n}=\sum _{i=1}^{(n)}{F_{k-i}^{(n)}}} For small values of n {\displaystyle n} , Greek numeric prefixes are sometimes used to individually name each series. Fibonacci n {\displaystyle n} -step sequences n {\displaystyle n} Series name Values 2 fibonacci 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ... 3 tribonacci 1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ... 4 tetranacci 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ... 5 pentanacci 1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ... 6 hexanacci 1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ... 7 heptanacci 1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ... 8 octonacci 1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ... 9 nonanacci 1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ... 10 decanacci 1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ... Allied sequences can be generated where the initial values are changed: The Lucas series sums the two preceding values like the fibonacci series for n = 2 {\displaystyle n=2} but uses [ 2 , 1 ] {\displaystyle [2,1]} as its initial values. Task Write a function to generate Fibonacci n {\displaystyle n} -step number sequences given its initial values and assuming the number of initial values determines how many previous values are summed to make the next number of the series. Use this to print and show here at least the first ten members of the Fibo/tribo/tetra-nacci and Lucas sequences. Related tasks   Fibonacci sequence   Wolfram Mathworld   Hofstadter Q sequence‎   Leonardo numbers Also see   Lucas Numbers - Numberphile (Video)   Tribonacci Numbers (and the Rauzy Fractal) - Numberphile (Video)   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#Fortran
Fortran
  ! save this program as file f.f08 ! gnu-linux command to build and test ! $ a=./f && gfortran -Wall -std=f2008 $a.f08 -o $a && echo -e 2\\n5\\n\\n | $a   ! -*- mode: compilation; default-directory: "/tmp/" -*- ! Compilation started at Fri Apr 4 23:20:27 ! ! a=./f && gfortran -Wall -std=f2008 $a.f08 -o $a && echo -e 2\\n8\\ny\\n | $a ! Enter the number of terms to sum: Show the the first how many terms of the sequence? Accept this initial sequence (y/n)? ! 1 1 ! 1 1 2 3 5 8 13 21 ! ! Compilation finished at Fri Apr 4 23:20:27   program f implicit none integer :: n, terms integer, allocatable, dimension(:) :: sequence integer :: i character :: answer write(6,'(a)',advance='no')'Enter the number of terms to sum: ' read(5,*) n if ((n < 2) .or. (29 < n)) stop'Unreasonable! Exit.' write(6,'(a)',advance='no')'Show the the first how many terms of the sequence? ' read(5,*) terms if (terms < 1) stop'Lazy programmer has not implemented backward sequences.' n = min(n, terms) allocate(sequence(1:terms)) sequence(1) = 1 do i = 0, n - 2 sequence(i+2) = 2**i end do write(6,*)'Accept this initial sequence (y/n)?' write(6,*) sequence(:n) read(5,*) answer if (answer .eq. 'n') then write(6,*) 'Fine. Enter the initial terms.' do i=1, n write(6, '(i2,a2)', advance = 'no') i, ': ' read(5, *) sequence(i) end do end if call nacci(n, sequence) write(6,*) sequence(:terms) deallocate(sequence)   contains   subroutine nacci(n, s) ! nacci =: (] , +/@{.)^:(-@#@]`(-#)`]) integer, intent(in) :: n integer, intent(inout), dimension(:) :: s integer :: i, terms terms = size(s) ! do i = n+1, terms ! s(i) = sum(s(i-n:i-1)) ! end do i = n+1 if (n+1 .le. terms) s(i) = sum(s(i-n:i-1)) do i = n + 2, terms s(i) = 2*s(i-1) - s(i-(n+1)) end do end subroutine nacci end program f  
http://rosettacode.org/wiki/Find_common_directory_path
Find common directory path
Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories. Test your routine using the forward slash '/' character as the directory separator and the following three strings as input paths: '/home/user1/tmp/coverage/test' '/home/user1/tmp/covert/operator' '/home/user1/tmp/coven/members' Note: The resultant path should be the valid directory '/home/user1/tmp' and not the longest common string '/home/user1/tmp/cove'. If your language has a routine that performs this function (even if it does not have a changeable separator character), then mention it as part of the task. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Ursala
Ursala
#import std   comdir"s" "p" = mat"s" reduce(gcp,0) (map sep "s") "p"
http://rosettacode.org/wiki/Find_common_directory_path
Find common directory path
Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories. Test your routine using the forward slash '/' character as the directory separator and the following three strings as input paths: '/home/user1/tmp/coverage/test' '/home/user1/tmp/covert/operator' '/home/user1/tmp/coven/members' Note: The resultant path should be the valid directory '/home/user1/tmp' and not the longest common string '/home/user1/tmp/cove'. If your language has a routine that performs this function (even if it does not have a changeable separator character), then mention it as part of the task. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#VBScript
VBScript
  ' Read the list of paths (newline-separated) into an array... strPaths = Split(WScript.StdIn.ReadAll, vbCrLf)   ' Split each path by the delimiter (/)... For i = 0 To UBound(strPaths) strPaths(i) = Split(strPaths(i), "/") Next   With CreateObject("Scripting.FileSystemObject")   ' Test each path segment... For j = 0 To UBound(strPaths(0))   ' Test each successive path against the first... For i = 1 To UBound(strPaths) If strPaths(0)(j) <> strPaths(i)(j) Then Exit For Next   ' If we didn't make it all the way through, exit the block... If i <= UBound(strPaths) Then Exit For   ' Make sure this path exists... If Not .FolderExists(strPath & strPaths(0)(j) & "/") Then Exit For strPath = strPath & strPaths(0)(j) & "/"   Next   End With   ' Remove the final "/"... WScript.Echo Left(strPath, Len(strPath) - 1)  
http://rosettacode.org/wiki/Filter
Filter
Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
#Frink
Frink
  b = array[1 to 100] c = select[b, {|x| x mod 2 == 0}]  
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) The   FizzBuzz   problem was presented as the lowest level of comprehension required to illustrate adequacy. Also see   (a blog)   dont-overthink-fizzbuzz   (a blog)   fizzbuzz-the-programmers-stairway-to-heaven
#Iptscrae
Iptscrae
; FizzBuzz in Iptscrae 1 a = { "" b = { "fizz" b &= } a 3 % 0 == IF { "buzz" b &= } a 5 % 0 == IF { a ITOA LOGMSG } { b LOGMSG } b STRLEN 0 == IFELSE a ++ } { a 100 <= } WHILE
http://rosettacode.org/wiki/File_size
File size
Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
#XPL0
XPL0
proc ShowSize(FileName); char FileName; int Size, C; [Trap(false); \disable abort on error FSet(FOpen(FileName, 0), ^i); Size:= 0; repeat C:= ChIn(3); \reads 2 EOFs before Size:= Size+1; \ read beyond end-of-file until GetErr; \ is detected IntOut(0, Size-2); CrLf(0); ];   [ShowSize("input.txt"); ShowSize("/input.txt"); \root under Linux ]
http://rosettacode.org/wiki/File_size
File size
Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
#zkl
zkl
File.info("input.txt").println(); File.info("/input.txt").println();
http://rosettacode.org/wiki/File_input/output
File input/output
File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file into a variable   how to write a variable's contents into a file Oneliners that skip the intermediate variable are of secondary interest — operating systems have copy commands for that.
#Modula-3
Modula-3
MODULE FileIO EXPORTS Main;   IMPORT IO, Rd, Wr;   <*FATAL ANY*>   VAR infile: Rd.T; outfile: Wr.T; txt: TEXT;   BEGIN infile := IO.OpenRead("input.txt"); outfile := IO.OpenWrite("output.txt"); txt := Rd.GetText(infile, LAST(CARDINAL)); Wr.PutText(outfile, txt); Rd.Close(infile); Wr.Close(outfile); END FileIO.
http://rosettacode.org/wiki/File_input/output
File input/output
File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file into a variable   how to write a variable's contents into a file Oneliners that skip the intermediate variable are of secondary interest — operating systems have copy commands for that.
#Nanoquery
Nanoquery
import Nanoquery.IO   input = new(File, "input.txt") output = new(File)   output.create("output.txt") output.open("output.txt")   contents = input.readAll() output.write(contents)
http://rosettacode.org/wiki/Fibonacci_word
Fibonacci word
The   Fibonacci Word   may be created in a manner analogous to the   Fibonacci Sequence   as described here: Define   F_Word1   as   1 Define   F_Word2   as   0 Form     F_Word3   as   F_Word2     concatenated with   F_Word1   i.e.:   01 Form     F_Wordn   as   F_Wordn-1   concatenated with   F_wordn-2 Task Perform the above steps for     n = 37. You may display the first few but not the larger values of   n. {Doing so will get the task's author into trouble with them what be (again!).} Instead, create a table for   F_Words   1   to   37   which shows:   The number of characters in the word   The word's Entropy Related tasks   Fibonacci word/fractal   Entropy   Entropy/Narcissist
#REXX
REXX
/*REXX program displays the number of chars in a fibonacci word, and the word's entropy.*/ d= 21; de= d + 6; numeric digits de /*use more precision (the default is 9)*/ parse arg N . /*get optional argument from the C.L. */ if N=='' | N=="," then N= 42 /*Not specified? Then use the default.*/ say center('N', 3) center("length", de) center('entropy', de) center("Fib word", 56) say copies('─', 3) copies("─" , de) copies('─' , de) copies("─" , 56) c= 1 /*initialize the 1st value for entropy.*/ do j=1 for N /* [↓] display N fibonacci words. */ if j==2 then c= 0 /*test for the case of J equals 2. */ if j==3 then parse value 1 0 with a b /* " " " " " " " 3. */ if j>2 then c= b || a /*calculate the FIBword if we need to.*/ L= length(c) /*find the length of the fib─word C. */ if L<56 then Fw= c else Fw= '{the word is too wide to display}' say right(j, 2) right( commas(L), de) ' ' entropy() " " Fw a= b; b= c /*define the new values for A and B.*/ end /*j*/ /*display text msg; */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ commas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ? /*──────────────────────────────────────────────────────────────────────────────────────*/ entropy: if L==1 then return left(0, d + 2) /*handle special case of one character.*/  !.0= length(space(translate(c,, 1), 0)) /*efficient way to count the "zeroes".*/  !.1= L - !.0; $= 0 /*define 1st fib─word; initial entropy.*/ do i=1 for 2; _= i - 1 /*construct character from the ether. */ $= $ - !._ / L * log2(!._ / L) /*add (negatively) the entropies. */ end /*i*/ if $=1 then return left(1, d+2) /*return a left─justified "1" (one). */ return format($, , d) /*normalize the sum (S) number. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ log2: procedure; parse arg x 1 xx; ig=x>1.5; is=1-2*(ig\==1); numeric digits 5+digits() e=2.71828182845904523536028747135266249775724709369995957496696762772407663035354759 m=0; do while ig & xx>1.5 | \ig&xx<.5; _=e; do j=-1; iz=xx* _ ** - is if j>=0 then if ig & iz<1 | \ig&iz>.5 then leave; _=_*_; izz=iz; end /*j*/ xx=izz; m=m+is*2**j; end /*while*/; x=x* e** -m -1; z=0; _=-1; p=z do k=1; _=-_*x; z=z+_/k; if z=p then leave; p=z; end /*k*/ r=z+m; if arg()==2 then return r; return r / log2(2,.)