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.
#EchoLisp
EchoLisp
  (define -∏*2 (complex 0 (* -2 PI)))   (define (fft xs N) (if (<= N 1) xs (let* [ (N/2 (/ N 2)) (even (fft (for/vector ([i (in-range 0 N 2)]) [xs i]) N/2)) (odd (fft (for/vector ([i (in-range 1 N 2)]) [xs i]) N/2)) ] (for ((k N/2)) (vector*= odd k (exp (/ (* -∏*2 k) N )))) (vector-append (vector-map + even odd) (vector-map - even odd)))))   (define data #( 1 1 1 1 0 0 0 0 ))   (fft data 8) → #( 4+0i 1-2.414213562373095i 0+0i 1-0.4142135623730949i 0+0i 1+0.4142135623730949i 0+0i 1+2.414213562373095i)  
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.)
#Common_Lisp
Common Lisp
(defun mersenne-fac (p &aux (m (1- (expt 2 p)))) (loop for k from 1 for n = (1+ (* 2 k p)) until (zerop (mod m n)) finally (return n)))   (print (mersenne-fac 929))
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.)
#Crystal
Crystal
require "big"   def prime?(n) # P3 Prime Generator primality test return n | 1 == 3 if n < 5 # n: 0,1,4|false, 2,3|true return false if n.gcd(6) != 1 # for n a P3 prime candidate (pc) pc1, pc2 = -1, 1 # use P3's prime candidates sequence until (pc1 += 6) > Math.sqrt(n).to_i # pcs are only 1/3 of all integers return false if n % pc1 == 0 || n % (pc2 += 6) == 0 # if n is composite end true end   # Compute b**e mod m def powmod(b, e, m) r, b = 1.to_big_i, b.to_big_i while e > 0 r = (r * b) % m if e.odd? b = (b * b) % m e >>= 1 end r end   def mersenne_factor(p) mers_num = 2.to_big_i ** p - 1 kp2 = p2 = 2.to_big_i * p while (kp2 - 1) ** 2 < mers_num q = kp2 + 1 # return q if it's a factor return q if [1, 7].includes?(q % 8) && prime?(q) && (powmod(2, p, q) == 1) kp2 += p2 end true # could also set to `0` value to check for end   def check_mersenne(p) print "M#{p} = 2**#{p}-1 is " f = mersenne_factor(p) (puts "prime"; return) if f.is_a?(Bool) # or f == 0 puts "composite with factor #{f}" end   (2..53).each { |p| check_mersenne(p) if prime?(p) } check_mersenne 929
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
#Go
Go
package main   import "fmt"   type frac struct{ num, den int }   func (f frac) String() string { return fmt.Sprintf("%d/%d", f.num, f.den) }   func f(l, r frac, n int) { m := frac{l.num + r.num, l.den + r.den} if m.den <= n { f(l, m, n) fmt.Print(m, " ") f(m, r, n) } }   func main() { // task 1. solution by recursive generation of mediants for n := 1; n <= 11; n++ { l := frac{0, 1} r := frac{1, 1} fmt.Printf("F(%d): %s ", n, l) f(l, r, n) fmt.Println(r) } // task 2. direct solution by summing totient function // 2.1 generate primes to 1000 var composite [1001]bool for _, p := range []int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31} { for n := p * 2; n <= 1000; n += p { composite[n] = true } } // 2.2 generate totients to 1000 var tot [1001]int for i := range tot { tot[i] = 1 } for n := 2; n <= 1000; n++ { if !composite[n] { tot[n] = n - 1 for a := n * 2; a <= 1000; a += n { f := n - 1 for r := a / n; r%n == 0; r /= n { f *= n } tot[a] *= f } } } // 2.3 sum totients for n, sum := 1, 1; n <= 1000; n++ { sum += tot[n] if n%100 == 0 { fmt.Printf("|F(%d)|: %d\n", n, sum) } } }
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®)
#Quackery
Quackery
[ dup dip digitsum mod ] is fairshare ( n n --> n )   ' [ 2 3 5 11 ] witheach [ dup echo say ": " 25 times [ i^ over fairshare echo sp ] drop cr ]
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®)
#Racket
Racket
#lang racket   (define (Thue-Morse base) (letrec ((q/r (curryr quotient/remainder base)) (inner (λ (n (s 0)) (match n [0 (modulo s base)] [(app q/r q r) (inner q (+ s r))])))) inner))   (define (report-turns B n) (printf "Base:\t~a\t~a~%" B (map (Thue-Morse B) (range n))))   (define (report-stats B n) (define TM (Thue-Morse B)) (define h0 (for/hash ((b B)) (values b 0))) (define d (for/fold ((h h0)) ((i n)) (hash-update h (TM i) add1 0))) (define d′ (for/fold ((h (hash))) (([k v] (in-hash d))) (hash-update h v add1 0))) (define d′′ (hash-map d′ (λ (k v) (format "~a people have ~a turn(s)" v k)))) (printf "Over ~a turns for ~a people:~a~%" n B (string-join d′′ ", ")))   (define (Fairshare-between-two-and-more) (report-turns 2 25) (report-turns 3 25) (report-turns 5 25) (report-turns 11 25) (newline) (report-stats 191 50000) (report-stats 1377 50000) (report-stats 49999 50000) (report-stats 50000 50000) (report-stats 50001 50000))   (module+ main (Fairshare-between-two-and-more))
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®)
#Raku
Raku
sub fairshare (\b) { ^∞ .hyper.map: { .polymod( b xx * ).sum % b } }   .say for <2 3 5 11>.map: { .fmt('%2d:') ~ .&fairshare[^25]».fmt('%2d').join: ', ' }   say "\nRelative fairness of this method. Scaled fairness correlation. The closer to 1.0 each person is, the more fair the selection algorithm is. Gets better with more iterations.";   for <2 3 5 11 39> -> $people { print "\n$people people: \n"; for $people * 1, $people * 10, $people * 1000 -> $iterations { my @fairness; fairshare($people)[^$iterations].kv.map: { @fairness[$^v % $people] += $^k } my $scale = @fairness.sum / @fairness; my @range = @fairness.map( { $_ / $scale } ); printf "After round %4d: Best advantage: %-10.8g - Worst disadvantage: %-10.8g - Spread between best and worst: %-10.8g\n", $iterations/$people, @range.min, @range.max, @range.max - @range.min; } }
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)
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ClearAll[Faulhaber] bernoulliB[1] := 1/2 bernoulliB[n_] := BernoulliB[n] Faulhaber[n_, p_] := 1/(p + 1) Sum[Binomial[p + 1, j] bernoulliB[j] n^(p + 1 - j), {j, 0, p}] Table[Rest@CoefficientList[Faulhaber[n, t], n], {t, 0, 9}] // Grid Faulhaber[1000, 17]
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.
#Modula-2
Modula-2
MODULE Faulhaber; FROM EXCEPTIONS IMPORT AllocateSource,ExceptionSource,GetMessage,RAISE; FROM FormatString IMPORT FormatString; FROM Terminal IMPORT WriteString,WriteLn,ReadChar;   VAR TextWinExSrc : ExceptionSource;   (* Helper Functions *) PROCEDURE Abs(n : INTEGER) : INTEGER; BEGIN IF n < 0 THEN RETURN -n END; RETURN n END Abs;   PROCEDURE Binomial(n,k : INTEGER) : INTEGER; VAR i,num,denom : INTEGER; BEGIN IF (n < 0) OR (k < 0) OR (n < k) THEN RAISE(TextWinExSrc, 0, "Argument Exception.") END; IF (n = 0) OR (k = 0) THEN RETURN 1 END; num := 1; FOR i:=k+1 TO n DO num := num * i END; denom := 1; FOR i:=2 TO n - k DO denom := denom * i END; RETURN num / denom END Binomial;   PROCEDURE GCD(a,b : INTEGER) : INTEGER; BEGIN IF b = 0 THEN RETURN a END; RETURN GCD(b, a MOD b) END GCD;   PROCEDURE WriteInteger(n : INTEGER); VAR buf : ARRAY[0..15] OF CHAR; BEGIN FormatString("%i", buf, n); WriteString(buf) END WriteInteger;   (* Fraction Handling *) TYPE Frac = RECORD num,denom : INTEGER; END;   PROCEDURE InitFrac(n,d : INTEGER) : Frac; VAR nn,dd,g : INTEGER; BEGIN IF d = 0 THEN RAISE(TextWinExSrc, 0, "The denominator must not be zero.") END; IF n = 0 THEN d := 1 ELSIF d < 0 THEN n := -n; d := -d END; g := Abs(GCD(n, d)); IF g > 1 THEN n := n / g; d := d / g END; RETURN Frac{n, d} END InitFrac;   PROCEDURE EqualFrac(a,b : Frac) : BOOLEAN; BEGIN RETURN (a.num = b.num) AND (a.denom = b.denom) END EqualFrac;   PROCEDURE LessFrac(a,b : Frac) : BOOLEAN; BEGIN RETURN a.num * b.denom < b.num * a.denom END LessFrac;   PROCEDURE NegateFrac(f : Frac) : Frac; BEGIN RETURN Frac{-f.num, f.denom} END NegateFrac;   PROCEDURE SubFrac(lhs,rhs : Frac) : Frac; BEGIN RETURN InitFrac(lhs.num * rhs.denom - lhs.denom * rhs.num, rhs.denom * lhs.denom) END SubFrac;   PROCEDURE MultFrac(lhs,rhs : Frac) : Frac; BEGIN RETURN InitFrac(lhs.num * rhs.num, lhs.denom * rhs.denom) END MultFrac;   PROCEDURE Bernoulli(n : INTEGER) : Frac; VAR a : ARRAY[0..15] OF Frac; i,j,m : INTEGER; BEGIN IF n < 0 THEN RAISE(TextWinExSrc, 0, "n may not be negative or zero.") END; FOR m:=0 TO n DO a[m] := Frac{1, m + 1}; FOR j:=m TO 1 BY -1 DO a[j-1] := MultFrac(SubFrac(a[j-1], a[j]), Frac{j, 1}) END END; IF n # 1 THEN RETURN a[0] END; RETURN NegateFrac(a[0]) END Bernoulli;   PROCEDURE WriteFrac(f : Frac); BEGIN WriteInteger(f.num); IF f.denom # 1 THEN WriteString("/"); WriteInteger(f.denom) END END WriteFrac;   (* Target *) PROCEDURE Faulhaber(p : INTEGER); VAR j,pwr,sign : INTEGER; q,coeff : Frac; BEGIN WriteInteger(p); WriteString(" : "); q := InitFrac(1, p + 1); sign := -1; FOR j:=0 TO p DO sign := -1 * sign; coeff := MultFrac(MultFrac(MultFrac(q, Frac{sign, 1}), Frac{Binomial(p + 1, j), 1}), Bernoulli(j)); IF EqualFrac(coeff, Frac{0, 1}) THEN CONTINUE END; IF j = 0 THEN IF NOT EqualFrac(coeff, Frac{1, 1}) THEN IF EqualFrac(coeff, Frac{-1, 1}) THEN WriteString("-") ELSE WriteFrac(coeff) END END ELSE IF EqualFrac(coeff, Frac{1, 1}) THEN WriteString(" + ") ELSIF EqualFrac(coeff, Frac{-1, 1}) THEN WriteString(" - ") ELSIF LessFrac(Frac{0, 1}, coeff) THEN WriteString(" + "); WriteFrac(coeff) ELSE WriteString(" - "); WriteFrac(NegateFrac(coeff)) END END; pwr := p + 1 - j; IF pwr > 1 THEN WriteString("n^"); WriteInteger(pwr) ELSE WriteString("n") END END; WriteLn END Faulhaber;   (* Main *) VAR i : INTEGER; BEGIN FOR i:=0 TO 9 DO Faulhaber(i) END; ReadChar END Faulhaber.
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
#Delphi
Delphi
  ;; generate a recursive lambda() for a x-nacci ;; equip it with memoïzation ;; bind it to its name (define (make-nacci name seed) (define len (1+ (vector-length seed))) (define-global name `(lambda(n) (for/sum ((i (in-range (1- n) (- n ,len) -1))) (,name i)))) (remember name seed) name)   (define nacci-family `( (Fibonacci #(1 1)) (Tribonacci #(1 1 2)) (Tetranacci #(1 1 2 4)) (Decanacci #(1 1 2 4 8 16 32 64 128 256)) (Random-😜-nacci ,(list->vector (take 6 (shuffle (iota 100))))) (Lucas #(2 1))))   (define (task naccis) (for ((nacci naccis)) (define-values (name seed) nacci) (make-nacci name seed) (printf "%s[%d] → %d" name (vector-length seed) (take name 16))))  
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
#REXX
REXX
/*REXX program finds the common directory path for a list of files. */ @. = /*the default for all file lists (null)*/ @.1 = '/home/user1/tmp/coverage/test' @.2 = '/home/user1/tmp/covert/operator' @.3 = '/home/user1/tmp/coven/members' L= length(@.1) /*use the length of the first string. */ do j=2 while @.j\=='' /*start search with the second string. */ _= compare(@.j, @.1) /*use REXX compare BIF for comparison*/ if _==0 then iterate /*Strings are equal? Then con't use min*/ L= min(L, _) /*get the minimum length equal strings.*/ if right(@.j, 1)=='/' then iterate /*if a directory, then it's OK. */ L= lastpos('/', left(@.j, L) ) /*obtain directory name up to here*/ end /*j*/   common= left( @.1, lastpos('/', @.1, L) ) /*determine the shortest DIR string. */ if right(common, 1)=='/' then common= left(common, max(0, length(common) - 1) ) if common=='' then common= "/" /*if no common directory, assume home. */ say 'common directory path: ' common /* [↑] handle trailing / delimiter*/ /*stick a fork in it, we're all 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.
#Erlang
Erlang
Numbers = lists:seq(1, 5). EvenNumbers = lists:filter(fun (X) -> X rem 2 == 0 end, Numbers).
http://rosettacode.org/wiki/Find_limit_of_recursion
Find limit of recursion
Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
#VBScript
VBScript
'mung.vbs option explicit   dim c if wscript.arguments.count = 1 then c = wscript.arguments(0) c = c + 1 else c = 0 end if wscript.echo "[Depth",c & "] Mung until no good." CreateObject("WScript.Shell").Run "cscript Mung.vbs " & c, 1, true wscript.echo "[Depth",c & "] no good."
http://rosettacode.org/wiki/Find_limit_of_recursion
Find limit of recursion
Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
#Vlang
Vlang
// Find limit of recursion, in V module main   // starts here, then call down until stacks become faulty pub fn main() { recurse(0) }   fn recurse(n int) { println(n) recurse(n+1) }
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
#Hy
Hy
(for [i (range 1 101)] (print (cond [(not (% i 15)) "FizzBuzz"] [(not (% i 5)) "Buzz"] [(not (% i 3)) "Fizz"] [True i])))
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.
#Ring
Ring
See len(read('input.txt')) + nl see len(read('/input.txt')) + nl
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.
#Ruby
Ruby
size = File.size('input.txt') size = 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.
#Run_BASIC
Run BASIC
print fileSize(DefaultDir$,"input.txt") ' current default directory print fileSize("","input.txt") ' root directory   function fileSize(dir$,file$) open dir$;"\";file$ FOR input as #f fileSize = lof(#f) ' Length Of File close #f end function
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.
#Julia
Julia
mystring = read("file1", String) open(io->write(io, mystring), "file2", "w")
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.
#K
K
`output.txt 0:0:`input.txt
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
#Pascal
Pascal
program FibWord; {$IFDEF DELPHI} {$APPTYPE CONSOLE} {$ENDIF} const FibSMaxLen = 35; type tFibString = string[2*FibSMaxLen];//Ansistring; tFibCnt = longWord; tFib = record ZeroCnt, OneCnt : tFibCnt; // fibS  : tFibString;//didn't work :-( end; var FibSCheck : boolean; Fib0,Fib1 : tFib; FibS0,FibS1: tFibString;   procedure FibInit; Begin with Fib0 do begin ZeroCnt := 1; OneCnt := 0; end;   with Fib1 do begin ZeroCnt := 0; OneCnt := 1; end; FibS0 := '1'; FibS1 := '0'; FibSCheck := true; end;   Function FibLength(const F:Tfib):tFibCnt; begin FibLength := F.ZeroCnt+F.OneCnt; end;   function FibEntropy(const F:Tfib):extended; const rcpLn2 = 1.0/ln(2); var entrp, ratio: extended; begin entrp := 0.0; ratio := F.ZeroCnt/FibLength(F); if Ratio <> 0.0 then entrp := -ratio*ln(ratio)*rcpLn2; ratio := F.OneCnt/FibLength(F); if Ratio <> 0.0 then entrp := entrp-ratio*ln(ratio)*rcpLn2; FibEntropy:=entrp end;   procedure FibSExtend; var tmpS : tFibString; begin IF FibSCheck then begin tmpS := FibS0+FibS1; FibS0 := FibS1; FibS1 := tmpS; FibSCheck := (length(FibS1) < FibSMaxLen); end; end;   procedure FibNext; var tmpFib : tFib; Begin tmpFib.ZeroCnt := Fib0.ZeroCnt+Fib1.ZeroCnt; tmpFib.OneCnt := Fib0.OneCnt +Fib1.OneCnt; Fib0 := Fib1; Fib1 := tmpFib; IF FibSCheck then FibSExtend; end;   procedure FibWrite(const F:Tfib); begin // With F do // write(ZeroCnt:10,OneCnt:10,FibLength(F):10,FibEntropy(f):17:14); write(FibLength(F):10,FibEntropy(F):17:14); IF FibSCheck then writeln(' ',FibS1) else writeln(' ....'); end;   var i : integer; BEGIN FibInit; writeln('No. Length Entropy Word'); write(1:4);FibWrite(Fib0); write(2:4);FibWrite(Fib1); For i := 3 to 37 do begin FibNext; write(i:4); FibWrite(Fib1); end; END.  
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.
#Ruby
Ruby
def fasta_format(strings) out, text = [], "" strings.split("\n").each do |line| if line[0] == '>' out << text unless text.empty? text = line[1..-1] + ": " else text << line end end out << text unless text.empty? end   data = <<'EOS' >Rosetta_Example_1 THERECANBENOSPACE >Rosetta_Example_2 THERECANBESEVERAL LINESBUTTHEYALLMUST BECONCATENATED EOS   puts fasta_format(data)
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.
#Run_BASIC
Run BASIC
a$ = ">Rosetta_Example_1 THERECANBENOSPACE >Rosetta_Example_2 THERECANBESEVERAL LINESBUTTHEYALLMUST BECONCATENATED"   i = 1 while i <= len(a$) if mid$(a$,i,17) = ">Rosetta_Example_" then print print mid$(a$,i,18);": "; i = i + 17 else if asc(mid$(a$,i,1)) > 20 then print mid$(a$,i,1); end if i = i + 1 wend
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.
#Rust
Rust
  use std::env; use std::io::{BufReader, Lines}; use std::io::prelude::*; use std::fs::File;   fn main() { let args: Vec<String> = env::args().collect(); let f = File::open(&args[1]).unwrap(); for line in FastaIter::new(f) { println!("{}", line); } }   struct FastaIter<T> { buffer_lines: Lines<BufReader<T>>, current_name: Option<String>, current_sequence: String }   impl<T: Read> FastaIter<T> { fn new(file: T) -> FastaIter<T> { FastaIter { buffer_lines: BufReader::new(file).lines(), current_name: None, current_sequence: String::new() } } }   impl<T: Read> Iterator for FastaIter<T> { type Item = String;   fn next(&mut self) -> Option<String> { while let Some(l) = self.buffer_lines.next() { let line = l.unwrap(); if line.starts_with(">") { if self.current_name.is_some() { let mut res = String::new(); res.push_str(self.current_name.as_ref().unwrap()); res.push_str(": "); res.push_str(&self.current_sequence); self.current_name = Some(String::from(&line[1..])); self.current_sequence.clear(); return Some(res); } else { self.current_name = Some(String::from(&line[1..])); self.current_sequence.clear(); } continue; } self.current_sequence.push_str(line.trim()); } if self.current_name.is_some() { let mut res = String::new(); res.push_str(self.current_name.as_ref().unwrap()); res.push_str(": "); res.push_str(&self.current_sequence); self.current_name = None; self.current_sequence.clear(); self.current_sequence.shrink_to_fit(); return Some(res); } None } }  
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
#ABAP
ABAP
FORM fibonacci_iter USING index TYPE i CHANGING number_fib TYPE i. DATA: lv_old type i, lv_cur type i. Do index times. If sy-index = 1 or sy-index = 2. lv_cur = 1. lv_old = 0. endif. number_fib = lv_cur + lv_old. lv_old = lv_cur. lv_cur = number_fib. enddo. ENDFORM.
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
#ALGOL_68
ALGOL 68
MODE YIELDINT = PROC(INT)VOID;   PROC gen factors = (INT n, YIELDINT yield)VOID: ( FOR i FROM 1 TO ENTIER sqrt(n) DO IF n MOD i = 0 THEN yield(i); INT other = n OVER i; IF i NE other THEN yield(n OVER i) FI FI OD );   []INT nums2factor = (45, 53, 64);   FOR i TO UPB nums2factor DO INT num = nums2factor[i]; STRING sep := ": "; print(num); # FOR INT j IN # gen factors(num, # ) DO ( # ## (INT j)VOID:( print((sep,whole(j,0))); sep:=", " # OD # )); print(new line) OD
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.
#ERRE
ERRE
  PROGRAM FFT   CONST CNT=8   !$DYNAMIC DIM REL[0],IMG[0],CMP[0],V[0]   BEGIN SIG=INT(LOG(CNT)/LOG(2)+0.9999) REAL1=2^SIG   REAL=REAL1-1 REAL2=INT(REAL1/2) REAL4=INT(REAL1/4) REAL3=REAL4+REAL2   !$DIM REL[REAL1],IMG[REAL1],CMP[REAL3]   FOR I=0 TO CNT-1 DO READ(REL[I],IMG[I]) END FOR   DATA(1,0,1,0,1,0,1,0,0,0,0,0,0,0,0,0)   SIG2=INT(SIG/2) SIG1=SIG-SIG2 CNT1=2^SIG1 CNT2=2^SIG2   !$DIM V[CNT1-1] V[0]=0 DV=1 PTR=CNT1   FOR J=1 TO SIG1 DO HLFPTR=INT(PTR/2) PT=CNT1-HLFPTR FOR I=HLFPTR TO PT STEP PTR DO V[I]=V[I-HLFPTR]+DV END FOR DV=2*DV PTR=HLFPTR END FOR   K=2*π/REAL1   FOR X=0 TO REAL4 DO CMP[X]=COS(K*X) CMP[REAL2-X]=-CMP[X] CMP[REAL2+X]=-CMP[X] END FOR   PRINT("FFT: BIT REVERSAL")   FOR I=0 TO CNT1-1 DO IP=I*CNT2 FOR J=0 TO CNT2-1 DO H=IP+J G=V[J]*CNT2+V[I] IF G>H THEN SWAP(REL[G],REL[H]) SWAP(IMG[G],IMG[H]) END IF END FOR END FOR   T=1 FOR STAGE=1 TO SIG DO PRINT("STAGE:";STAGE) D=INT(REAL2/T) FOR II=0 TO T-1 DO L=D*II LS=L+REAL4 FOR I=0 TO D-1 DO A=2*I*T+II B=A+T F1=REL[A] F2=IMG[A] CNT1=CMP[L]*REL[B] CNT2=CMP[LS]*IMG[B] CNT3=CMP[LS]*REL[B] CNT4=CMP[L]*IMG[B] REL[A]=F1+CNT1-CNT2 IMG[A]=F2+CNT3+CNT4 REL[B]=F1-CNT1+CNT2 IMG[B]=F2-CNT3-CNT4 END FOR END FOR T=2*T END FOR   PRINT("NUM REAL IMAG") FOR I=0 TO REAL DO IF ABS(REL[I])<1E-5 THEN REL[I]=0 END IF IF ABS(IMG[I])<1E-5 THEN IMG[I]=0 END IF PRINT(I;"";) WRITE("##.###### ##.######";REL[I];IMG[I]) END FOR END PROGRAM  
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.)
#D
D
import std.stdio, std.math, std.traits;   ulong mersenneFactor(in ulong p) pure nothrow @nogc { static bool isPrime(T)(in T n) pure nothrow @nogc { if (n < 2 || n % 2 == 0) return n == 2; for (Unqual!T i = 3; i ^^ 2 <= n; i += 2) if (n % i == 0) return false; return true; }   static ulong modPow(in ulong cb, in ulong ce,in ulong m) pure nothrow @nogc { ulong b = cb; ulong result = 1; for (ulong e = ce; e > 0; e >>= 1) { if ((e & 1) == 1) result = (result * b) % m; b = (b ^^ 2) % m; } return result; }   immutable ulong limit = p <= 64 ? cast(ulong)(real(2.0) ^^ p - 1).sqrt : uint.max; // prevents silent overflows for (ulong k = 1; (2 * p * k + 1) < limit; k++) { immutable ulong q = 2 * p * k + 1; if ((q % 8 == 1 || q % 8 == 7) && isPrime(q) && modPow(2, p, q) == 1) return q; } return 1; // returns a sensible smallest factor }   void main() { writefln("Factor of M929: %d", 929.mersenneFactor); }
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
#Haskell
Haskell
import Data.List (unfoldr, mapAccumR) import Data.Ratio ((%), denominator, numerator) import Text.Printf (PrintfArg, printf)   -- The n'th order Farey sequence. farey :: Integer -> [Rational] farey n = 0 : unfoldr step (0, 1, 1, n) where step (a, b, c, d) | c > n = Nothing | otherwise = let k = (n + b) `quot` d in Just (c %d, (c, d, k * c - a, k * d - b))   -- A list of pairs, (n, fn n), where fn is a function applied to the n'th order -- Farey sequence. We assume the list of orders is increasing. Only the -- highest order Farey sequence is evaluated; the remainder are generated by -- successively pruning this sequence. fareys :: ([Rational] -> a) -> [Integer] -> [(Integer, a)] fareys fn ns = snd $ mapAccumR prune (farey $ last ns) ns where prune rs n = let rs'' = filter ((<= n) . denominator) rs in (rs'', (n, fn rs''))   fprint :: (PrintfArg b) => String -> [(Integer, b)] -> IO () fprint fmt = mapM_ (uncurry $ printf fmt)   showFracs :: [Rational] -> String showFracs = unwords . map (concat . (<*>) [show . numerator, const "/", show . denominator] . pure)   main :: IO () main = do putStrLn "Farey Sequences\n" fprint "%2d %s\n" $ fareys showFracs [1 .. 11] putStrLn "\nSequence Lengths\n" fprint "%4d %d\n" $ fareys length [100,200 .. 1000]
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®)
#REXX
REXX
/*REXX program calculates N terms of the fairshare sequence for some group of peoples.*/ parse arg n g /*obtain optional arguments from the CL*/ if n=='' | n=="," then n= 25 /*Not specified? Then use the default.*/ if g='' | g="," then g= 2 3 5 11 /* " " " " " " */ /* [↑] a list of a number of peoples. */ do p=1 for words(g); r= word(g, p) /*traipse through the bases specfiied. */ $= 'base' right(r, 2)': ' /*construct start of the 1─line output.*/ do j=0 for n; $= $ right( sumDigs( base(j, r)) // r, 2)',' end /*j*/ /* [↑] append # (base R) mod R──►$ list*/ say strip($, , ",") /*elide trailing comma from the $ list.*/ end /*p*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ base: parse arg #,b,,y; @= 0123456789abcdefghijklmnopqrstuvwxyz; @@= substr(@,2) do while #>=b; y= substr(@, #//b + 1, 1)y; #= #%b; end; return substr(@, #+1, 1)y /*──────────────────────────────────────────────────────────────────────────────────────*/ sumDigs: parse arg x; !=0; do i=1 for length(x); != !+pos(substr(x,i,1),@@); end; return !
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®)
#Ring
Ring
  str = [] people = [2,3,5,11]   result = people for i in people str = [] see "" + i + ": " fair(25, i) for n in result add(str,n) next showarray(str) next   func fair n,base   result = list(n) for i=1 to n j = i-1 t = 0 while j>0 t = t + j % base j = floor(j/base) end result[i] = t % base next   func showarray vect svect = "" for n in vect svect += " " + n + "," next svect = left(svect, len(svect) - 1)  ? "[" + svect + "]"  
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)
#Nim
Nim
import algorithm, math, strutils import bignum   type FaulhaberSequence = seq[Rat]   #---------------------------------------------------------------------------------------------------   func bernoulli(n: Natural): Rat = ## Return nth Bernoulli coefficient.   var a = newSeq[Rat](n + 1) for m in 0..n: a[m] = newRat(1, m + 1) for k in countdown(m, 1): a[k - 1] = (a[k - 1] - a[k]) * k result = if n != 1: a[0] else: -a[0]   #---------------------------------------------------------------------------------------------------   func faulhaber(n: Natural): FaulhaberSequence = ## Return nth Faulhaber sequence (high degree first).   var a = newRat(1, n + 1) var sign = -1 for k in 0..n: sign = -sign result.add(a * sign * binom(n + 1, k) * bernoulli(k))   #---------------------------------------------------------------------------------------------------   proc display(fs: FaulhaberSequence) = ## Return the string representing a Faulhaber sequence.   var str = "" for i, coeff in reversed(fs): str.addSep(" ", 0) str.add(($coeff).align(6)) echo str   #---------------------------------------------------------------------------------------------------   func evaluate(fs: FaulhaberSequence; n: int): Rat = ## Evaluate the polynomial associated to a sequence for value "n".   result = newRat(0) for coeff in fs: result = result * n + coeff result *= n   #———————————————————————————————————————————————————————————————————————————————————————————————————   for n in 0..9: display(faulhaber(n))   echo "" let fs18 = faulhaber(17) # 18th row. echo fs18.evaluate(1000)
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.
#Nim
Nim
import math, rationals   type Fraction = Rational[int] FaulhaberSequence = seq[Fraction]   const Zero = 0 // 1 One = 1 // 1 MinusOne = -1 // 1 Powers = ["⁰", "¹", "²", "³", "⁴", "⁵", "⁶", "⁷", "⁸", "⁹"]   #---------------------------------------------------------------------------------------------------   func bernoulli(n: Natural): Fraction = ## Return nth Bernoulli coefficient.   var a = newSeq[Fraction](n + 1) for m in 0..n: a[m] = 1 // (m + 1) for k in countdown(m, 1): a[k - 1] = (a[k - 1] - a[k]) * k result = if n != 1: a[0] else: -a[0]   #---------------------------------------------------------------------------------------------------   func faulhaber(n: Natural): FaulhaberSequence = ## Return nth Faulhaber sequence.   var a = 1 // (n + 1) var sign = -1 for k in 0..n: sign = -sign result.add(a * sign * binom(n + 1, k) * bernoulli(k))   #---------------------------------------------------------------------------------------------------   func npower(k: Natural): string = ## Return the string representing "n" at power "k".   if k == 0: return "" if k == 1: return "n" var k = k result = "n" while k != 0: result.insert(Powers[k mod 10], 1) k = k div 10   #---------------------------------------------------------------------------------------------------   func `$`(fs: FaulhaberSequence): string = ## Return the string representing a Faulhaber sequence.   for i, coeff in fs:   # Process coefficient. if coeff.num == 0: continue if i == 0: if coeff == MinusOne: result.add(" - ") elif coeff != One: result.add($coeff) else: if coeff == One: result.add(" + ") elif coeff == MinusOne: result.add(" - ") elif coeff > Zero: result.add(" + " & $coeff) else: result.add(" - " & $(-coeff))   # Process power of "n". let pwr = fs.len - i result.add(npower(pwr))   #———————————————————————————————————————————————————————————————————————————————————————————————————   for n in 0..9: echo n, ": ", faulhaber(n)
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
#EchoLisp
EchoLisp
  ;; generate a recursive lambda() for a x-nacci ;; equip it with memoïzation ;; bind it to its name (define (make-nacci name seed) (define len (1+ (vector-length seed))) (define-global name `(lambda(n) (for/sum ((i (in-range (1- n) (- n ,len) -1))) (,name i)))) (remember name seed) name)   (define nacci-family `( (Fibonacci #(1 1)) (Tribonacci #(1 1 2)) (Tetranacci #(1 1 2 4)) (Decanacci #(1 1 2 4 8 16 32 64 128 256)) (Random-😜-nacci ,(list->vector (take 6 (shuffle (iota 100))))) (Lucas #(2 1))))   (define (task naccis) (for ((nacci naccis)) (define-values (name seed) nacci) (make-nacci name seed) (printf "%s[%d] → %d" name (vector-length seed) (take name 16))))  
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
#Ring
Ring
  # Project : Find common directory path   load "stdlib.ring" i = null o = null path = list(3)   path[1] = "/home/user1/tmp/coverage/test" path[2] = "/home/user1/tmp/covert/operator" path[3] = "/home/user1/tmp/coven/members"   see commonpath(path, "/")   func commonpath(p, s) while i != 0 o = i i = substring(p[1], s, i+1) for j = 2 to len(p) if left(p[1], i) != left(p[j], i) exit 2 ok next end return left(p[1], o-1)  
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
#Ruby
Ruby
require 'abbrev'   dirs = %w( /home/user1/tmp/coverage/test /home/user1/tmp/covert/operator /home/user1/tmp/coven/members )   common_prefix = dirs.abbrev.keys.min_by {|key| key.length}.chop # => "/home/user1/tmp/cove" common_directory = common_prefix.sub(%r{/[^/]*$}, '') # => "/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.
#Euphoria
Euphoria
sequence s, evens s = {1, 2, 3, 4, 5, 6} evens = {} for i = 1 to length(s) do if remainder(s[i], 2) = 0 then evens = append(evens, s[i]) end if end for ? evens
http://rosettacode.org/wiki/Find_limit_of_recursion
Find limit of recursion
Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
#x86_Assembly
x86 Assembly
global main   section .text   main xor eax, eax call recurse ret   recurse add eax, 1 call recurse ret
http://rosettacode.org/wiki/Find_limit_of_recursion
Find limit of recursion
Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
#Wren
Wren
var f f = Fn.new { |n| if (n%500 == 0) System.print(n) // print progress after every 500 calls System.write("") // required to fix a VM recursion bug f.call(n + 1) } f.call(1)
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
#i
i
software { for each 1 to 100 if i % 15 = 0 print("FizzBuzz") else if i % 3 = 0 print("Fizz") else if i % 5 = 0 print("Buzz") else print(i) end end }
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.
#Rust
Rust
use std::{env, fs, process}; use std::io::{self, Write}; use std::fmt::Display;   fn main() { let file_name = env::args().nth(1).unwrap_or_else(|| exit_err("No file name supplied", 1)); let metadata = fs::metadata(file_name).unwrap_or_else(|e| exit_err(e, 2));   println!("Size of file.txt is {} bytes", metadata.len()); }   #[inline] fn exit_err<T: Display>(msg: T, code: i32) -> ! { writeln!(&mut io::stderr(), "Error: {}", msg).expect("Could not write to stdout"); process::exit(code) }   }
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.
#Scala
Scala
import java.io.File   object FileSize extends App { val name = "pg1661.txt"   println(s"$name  : ${new File(name).length()} bytes") println(s"/$name : ${new File(s"${File.separator}$name").length()} 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.
#Scheme
Scheme
  (define (file-size filename) (call-with-input-file filename (lambda (port) (let loop ((c (read-char port)) (count 0)) (if (eof-object? c) count (loop (read-char port) (+ 1 count)))))))   (file-size "input.txt") (file-size "/input.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.
#Kotlin
Kotlin
// version 1.1.2   import java.io.File   fun main(args: Array<String>) { val text = File("input.txt").readText() File("output.txt").writeText(text) }
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.
#LabVIEW
LabVIEW
: puts(*) . "\n" . ; : set-file '> swap open ; : >>contents slurp puts ; : copy-file swap set-file 'fdst set fdst fout >>contents fdst close ;   'output.txt 'input.txt copy-file
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
#Perl
Perl
sub fiboword; { my ($a, $b, $count) = (1, 0, 0); sub fiboword { $count++; return $a if $count == 1; return $b if $count == 2; ($a, $b) = ($b, "$b$a"); return $b; } } sub entropy { my %c; $c{$_}++ for split //, my $str = shift; my $e = 0; for (values %c) { my $p = $_ / length $str; $e -= $p * log $p; } return $e / log 2; }   my $count; while ($count++ < 37) { my $word = fiboword; printf "%5d\t%10d\t%.8e\t%s\n", $count, length($word), entropy($word), $count > 9 ? '' : $word }
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.
#Scala
Scala
import java.io.File import java.util.Scanner   object ReadFastaFile extends App { val sc = new Scanner(new File("test.fasta")) var first = true   while (sc.hasNextLine) { val line = sc.nextLine.trim if (line.charAt(0) == '>') { if (first) first = false else println() printf("%s: ", line.substring(1)) } else print(line) }   println("~~~+~~~") }
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.
#Scheme
Scheme
(import (scheme base) (scheme file) (scheme write))   (with-input-from-file ; reads text from named file, one line at a time "fasta.txt" (lambda () (do ((first-line? #t #f) (line (read-line) (read-line))) ((eof-object? line) (newline)) (cond ((char=? #\> (string-ref line 0)) ; found a name (unless first-line? ; no newline on first name (newline)) (display (string-copy line 1)) (display ": ")) (else ; display the string directly (display line))))))
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
#ACL2
ACL2
(defun fast-fib-r (n a b) (if (or (zp n) (zp (1- n))) b (fast-fib-r (1- n) b (+ a b))))   (defun fast-fib (n) (fast-fib-r n 1 1))   (defun first-fibs-r (n i) (declare (xargs :measure (nfix (- n i)))) (if (zp (- n i)) nil (cons (fast-fib i) (first-fibs-r n (1+ i)))))   (defun first-fibs (n) (first-fibs-r n 0))
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
#ALGOL_W
ALGOL W
begin  % return the factors of n ( n should be >= 1 ) in the array factor  %  % the bounds of factor should be 0 :: len (len must be at least 1)  %  % the number of factors will be returned in factor( 0 )  % procedure getFactorsOf ( integer value n  ; integer array factor( * )  ; integer value len ) ; begin for i := 0 until len do factor( i ) := 0; if n >= 1 and len >= 1 then begin integer pos, lastFactor; factor( 0 ) := factor( 1 ) := pos := 1;  % find the factors up to sqrt( n )  % for f := 2 until truncate( sqrt( n ) ) + 1 do begin if ( n rem f ) = 0 and pos <= len then begin  % found another factor and there's room to store it  % pos  := pos + 1; factor( 0 ) := pos; factor( pos ) := f end if_found_factor end for_f;  % find the factors above sqrt( n )  % lastFactor := factor( factor( 0 ) ); for f := factor( 0 ) step -1 until 1 do begin integer newFactor; newFactor := n div factor( f ); if newFactor > lastFactor and pos <= len then begin  % found another factor and there's room to store it  % pos  := pos + 1; factor( 0 ) := pos; factor( pos ) := newFactor end if_found_factor end for_f; end if_params_ok end getFactorsOf ;      % prpocedure to test getFactorsOf  % procedure testFactorsOf( integer value n ) ; begin integer array factor( 0 :: 100 ); getFactorsOf( n, factor, 100 ); i_w := 1; s_w := 0; % set output format  % write( n, " has ", factor( 0 ), " factors:" ); for f := 1 until factor( 0 ) do writeon( " ", factor( f ) ) end testFactorsOf ;    % test the factorising  % for i := 1 until 100 do testFactorsOf( i )   end.
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.
#Factor
Factor
  IN: USE math.transforms.fft IN: { 1 1 1 1 0 0 0 0 } fft . { C{ 4.0 0.0 } C{ 1.0 -2.414213562373095 } C{ 0.0 0.0 } C{ 1.0 -0.4142135623730949 } C{ 0.0 0.0 } C{ 0.9999999999999999 0.4142135623730949 } C{ 0.0 0.0 } C{ 0.9999999999999997 2.414213562373095 } }  
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.)
#Delphi
Delphi
  ;; M = 2^P - 1 , P prime ;; look for a prime divisor q such as : q < √ M, q = 1 or 7 modulo 8, q = 1 + 2kP ;; q is divisor if (powmod 2 P q) = 1 ;; m-divisor returns q or #f   (define ( m-divisor P ) ;; must limit the search as √ M may be HUGE (define maxprime (min 1_000_000_000 (sqrt (expt 2 P)))) (for ((q (in-range 1 maxprime (* 2 P)))) #:when (member (modulo q 8) '(1 7)) #:when (prime? q) #:break (= 1 (powmod 2 P q)) => q #f ))   (m-divisor 929) → 13007 (m-divisor 4423) → #f   (lib 'bigint) (prime? (1- (expt 2 4423))) ;; 2^4423 -1 is a Mersenne prime → #t    
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
#J
J
Farey=: x:@/:~@(0 , ~.)@(#~ <:&1)@:,@(%/~@(1 + i.)) NB. calculates Farey sequence displayFarey=: ('r/' charsub '0r' , ,&'r1')@": NB. format character representation of Farey sequence according to task requirements order=: ': ' ,~ ": NB. decorate order of Farey sequence
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
#Java
Java
import java.util.TreeSet;   public class Farey{ private static class Frac implements Comparable<Frac>{ int num; int den;   public Frac(int num, int den){ this.num = num; this.den = den; }   @Override public String toString(){ return num + "/" + den; }   @Override public int compareTo(Frac o){ return Double.compare((double)num / den, (double)o.num / o.den); } }   public static TreeSet<Frac> genFarey(int i){ TreeSet<Frac> farey = new TreeSet<Frac>(); for(int den = 1; den <= i; den++){ for(int num = 0; num <= den; num++){ farey.add(new Frac(num, den)); } } return farey; }   public static void main(String[] args){ for(int i = 1; i <= 11; i++){ System.out.println("F" + i + ": " + genFarey(i)); }   for(int i = 100; i <= 1000; i += 100){ System.out.println("F" + i + ": " + genFarey(i).size() + " members"); } } }
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®)
#Ruby
Ruby
def turn(base, n) sum = 0 while n != 0 do rem = n % base n = n / base sum = sum + rem end return sum % base end   def fairshare(base, count) print "Base %2d: " % [base] for i in 0 .. count - 1 do t = turn(base, i) print " %2d" % [t] end print "\n" end   def turnCount(base, count) cnt = Array.new(base, 0)   for i in 0 .. count - 1 do t = turn(base, i) cnt[t] = cnt[t] + 1 end   minTurn = base * count maxTurn = -1 portion = 0 for i in 0 .. base - 1 do if cnt[i] > 0 then portion = portion + 1 end if cnt[i] < minTurn then minTurn = cnt[i] end if cnt[i] > maxTurn then maxTurn = cnt[i] end end   print " With %d people: " % [base] if 0 == minTurn then print "Only %d have a turn\n" % portion elsif minTurn == maxTurn then print "%d\n" % [minTurn] else print "%d or %d\n" % [minTurn, maxTurn] end end   def main fairshare(2, 25) fairshare(3, 25) fairshare(5, 25) fairshare(11, 25)   puts "How many times does each get a turn in 50000 iterations?" turnCount(191, 50000) turnCount(1377, 50000) turnCount(49999, 50000) turnCount(50000, 50000) turnCount(50001, 50000) end   main()
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)
#Pascal
Pascal
  program FaulhaberTriangle; uses uIntX, uEnums, // units in the library IntXLib4Pascal SysUtils;   // Convert a rational num/den to a string, right-justified in the given width. // Before converting, remove any common factor of num and den. // For this application we can assume den > 0. function RationalToString( num, den : TIntX; minWidth : integer) : string; var num1, den1, divisor : TIntX; w : integer; begin divisor := TIntX.GCD( num, den); // TIntx.Divide requires the caller to specifiy the division mode num1 := TIntx.Divide( num, divisor, uEnums.dmClassic); den1 := TIntx.Divide( den, divisor, uEnums.dmClassic); result := num1.ToString; if not den1.IsOne then result := result + '/' + den1.ToString; w := minWidth - Length( result); if (w > 0) then result := StringOfChar(' ', w) + result; end;   // Main routine const r_MAX = 17; var g : array [1..r_MAX + 1] of TIntX; r, s, k : integer; r_1_fac, sum, k_intx : TIntX; begin // Calculate rows 0..17 of Faulhaner's triangle, and show rows 0..9. // For a given r, the subarray g[1..(r+1)] contains (r + 1)! times row r. r_1_fac := 1; // (r + 1)! g[1] := 1; for r := 0 to r_MAX do begin r_1_fac := r_1_fac * (r+1); sum := 0; for s := r downto 1 do begin g[s + 1] := r*(r+1)*g[s] div (s+1); sum := sum + g[s + 1]; end; g[1] := r_1_fac - sum; // the scaled row must sum to (r + 1)! if (r <= 9) then begin for s := 1 to r + 1 do Write( RationalToString( g[s], r_1_fac, 7)); WriteLn; end; end;   // Use row 17 to sum 17th powers from 1 to 1000 sum := 0; for s := r_MAX + 1 downto 1 do sum := (sum + g[s]) * 1000; sum := TIntx.Divide( sum, r_1_fac, uEnums.dmClassic); WriteLn; WriteLn( 'Sum by Faulhaber = ' + sum.ToString);   // Check by direct calculation sum := 0; for k := 1 to 1000 do begin k_intx := k; sum := sum + TIntX.Pow( k_intx, r_MAX); end; WriteLn( 'by direct calc. = ' + sum.ToString); end.  
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.
#PARI.2FGP
PARI/GP
  \\ Using "Faulhaber's" formula based on Bernoulli numbers. aev 2/7/17 \\ In str string replace all occurrences of the search string ssrch with the replacement string srepl. aev 3/8/16 sreplace(str,ssrch,srepl)={ my(sn=#str,ssn=#ssrch,srn=#srepl,sres="",Vi,Vs,Vz,vin,vin1,vi,L=List(),tok,zi,js=1); if(sn==0,return("")); if(ssn==0||ssn>sn,return(str)); \\ Vi - found ssrch indexes Vi=sfindalls(str,ssrch); vin=#Vi; if(vin==0,return(str)); vin1=vin+1; Vi=Vec(Vi,vin1); Vi[vin1]=sn+1; for(i=1,vin1, vi=Vi[i]; for(j=js,sn, \\print("ij:",i,"/",j,": ",sres); if(j!=vi, sres=concat(sres,ssubstr(str,j,1)), sres=concat(sres,srepl); js=j+ssn; break) ); \\fend j ); \\fend i return(sres); } B(n)=(bernfrac(n)); Comb(n,k)={my(r=0); if(k<=n, r=n!/(n-k)!/k!); return(r)}; Faulhaber2(p)={ my(s="",s1="",s2="",c1=0,c2=0); for(j=0,p, c1=(-1)^j*Comb(p+1,j)*B(j); c2=(p+1-j); s2="*n"; if(c1==0, next); if(c2==1, s1="", s1=Str("^",c2)); s=Str(s,c1,s2,s1,"+") ); s=ssubstr(s,1,#s-1); s=sreplace(s,"1*n","n"); s=sreplace(s,"+-","-"); if(p==0, s="n", s=Str("(",s,")/",p+1)); print(p,": ",s); } {\\ Testing: for(i=0,9, Faulhaber2(i))}  
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
#Elixir
Elixir
defmodule RC do def anynacci(start_sequence, count) do n = length(start_sequence) anynacci(Enum.reverse(start_sequence), count-n, n) end   def anynacci(seq, 0, _), do: Enum.reverse(seq) def anynacci(seq, count, n) do next = Enum.sum(Enum.take(seq, n)) anynacci([next|seq], count-1, n) end end   IO.inspect RC.anynacci([1,1], 15)   naccis = [ lucus: [2,1], fibonacci: [1,1], tribonacci: [1,1,2], tetranacci: [1,1,2,4], pentanacci: [1,1,2,4,8], hexanacci: [1,1,2,4,8,16], heptanacci: [1,1,2,4,8,16,32], octonacci: [1,1,2,4,8,16,32,64], nonanacci: [1,1,2,4,8,16,32,64,128], decanacci: [1,1,2,4,8,16,32,64,128,256] ] Enum.each(naccis, fn {name, list} ->  :io.format("~11s: ", [name]) IO.inspect RC.anynacci(list, 15) end)
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
#Run_BASIC
Run BASIC
' ------------------------------------------ ' Find common directory to all directories ' and directories common with other Paths ' ------------------------------------------ print word$(word$(httpget$("http://tycho.usno.navy.mil/cgi-bin/timer.pl"),1,"UTC"),2,"<BR>") ' Universal time   dim path$(20) path$(1) = "/home/user1/tmp/coverage/test" path$(2) = "/home/user1/tmp/covert/operator" path$(3) = "/home/user1/tmp/coven/members"   path$(4) = "/home/user1/tmp1/coverage/test" path$(5) = "/home/user1/tmp1/covert/operator" path$(6) = "/home/user1/tmp1/coven/members"   path$(7) = "/home/user1/tmp2/coverage/test" path$(8) = "/home/user1/tmp2/covert/operator" path$(9) = "/home/user1/tmp2/coven/members"   path$(10) = "/home/user1/tmp3/coverage/test" path$(11) = "/home/user1/tmp3/covert/operator" path$(12) = "/home/user1/tmp3/coven/members"   sqliteconnect #mem, ":memory:" #mem execute("CREATE TABLE dirTree (seq,pos,dir)")   for i = 1 to 12 j = 1 [loop] j = instr(path$(i),"/",j + 1) if j > 0 then dir$ = mid$(path$(i),1,j) mem$ = "INSERT INTO dirTree VALUES (";i;",";j;",'";dir$;"')" #mem execute(mem$) goto [loop] end if next i   mem$ = "SELECT dir FROM dirTree GROUP BY dir HAVING count(*) = pos ORDER BY pos desc LIMIT 1" #mem execute(mem$) rows = #mem ROWCOUNT() 'Get the number of rows if rows > 0 then #row = #mem #nextrow() print "====== Largest Directory Common to all Paths =========" print #row dir$() else print "No common Directory" end if   html "<HR>"   print "========= Common paths ================"   mem$ = "SELECT t.seq as seq,t.pos as pos,t.dir as dir,t1.seq as t1Seq ,t1.dir as t1Dir FROM dirTree as t JOIN dirTree as t1 ON t1.dir = t.dir AND t1.seq > t.seq GROUP BY t.dir,t1.seq"   html "<table border=1><TR align=center> <TD>Seq</TD> <TD>Path</TD> <TD>Common Dir</TD> <TD>Seq</TD> <TD>With Path</TD></TR>"   #mem execute(mem$) WHILE #mem hasanswer() #row = #mem #nextrow() seq = #row seq() t1Seq = #row t1Seq() pos = #row pos() dir$ = #row dir$() t1Dir$ = #row t1Dir$() html "<TR>" html "<TD>";seq;"</TD>" html "<TD>";path$(seq);"</TD>" html "<TD>";dir$;"</TD>" html "<TD>";t1Seq;"</TD>" html "<TD>";path$(t1Seq);"</TD>" html "</TR>" WEND html "</TABLE>" wait end
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
#Rust
Rust
  use std::path::{Path, PathBuf};   fn main() { let paths = [ Path::new("/home/user1/tmp/coverage/test"), Path::new("/home/user1/tmp/covert/operator"), Path::new("/home/user1/tmp/coven/members"), ]; match common_path(&paths) { Some(p) => println!("The common path is: {:#?}", p), None => println!("No common paths found"), } }   fn common_path<I, P>(paths: I) -> Option<PathBuf> where I: IntoIterator<Item = P>, P: AsRef<Path>, { let mut iter = paths.into_iter(); let mut ret = iter.next()?.as_ref().to_path_buf(); for path in iter { if let Some(r) = common(ret, path.as_ref()) { ret = r; } else { return None; } } Some(ret) }   fn common<A: AsRef<Path>, B: AsRef<Path>>(a: A, b: B) -> Option<PathBuf> { let a = a.as_ref().components(); let b = b.as_ref().components(); let mut ret = PathBuf::new(); let mut found = false; for (one, two) in a.zip(b) { if one == two { ret.push(one); found = true; } else { break; } } if found { Some(ret) } else { None } }  
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.
#F.23
F#
let lst = [1;2;3;4;5;6] List.filter (fun x -> x % 2 = 0) lst;;   val it : int list = [2; 4; 6]
http://rosettacode.org/wiki/Find_limit_of_recursion
Find limit of recursion
Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
#Z80_Assembly
Z80 Assembly
org &0000 LD SP,&FFFF ;3 bytes loop: or a ;1 byte, clears the carry flag ld (&0024),sp ;4 bytes ld hl,(&0024) ;3 bytes push af ;1 byte ld bc,(&0024) ;4 bytes sbc hl,bc ;4 bytes jr z,loop ;2 bytes jr * ;2 bytes ;address &0024 begins here word 0 ;placeholder for stack pointer
http://rosettacode.org/wiki/Find_limit_of_recursion
Find limit of recursion
Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
#zkl
zkl
fcn{self.fcn()}()
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
#Icon_and_Unicon
Icon and Unicon
# straight-forward modulo tester procedure main() every i := 1 to 100 do if i % 15 = 0 then write("FizzBuzz") else if i % 5 = 0 then write("Buzz") else if i % 3 = 0 then write("Fizz") else write(i) end
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.
#Seed7
Seed7
$ include "seed7_05.s7i";   const proc: main is func begin writeln(fileSize("input.txt")); writeln(fileSize("/input.txt")); end func;
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.
#Sidef
Sidef
say (Dir.cwd + %f'input.txt' -> size); say (Dir.root + %f'input.txt' -> size);
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.
#Slate
Slate
(File newNamed: 'input.txt') fileInfo fileSize. (File newNamed: '/input.txt') fileInfo fileSize.
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.
#Lang5
Lang5
: puts(*) . "\n" . ; : set-file '> swap open ; : >>contents slurp puts ; : copy-file swap set-file 'fdst set fdst fout >>contents fdst close ;   'output.txt 'input.txt copy-file
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.
#Liberty_BASIC
Liberty BASIC
nomainwin   open "input.txt" for input as #f1 qtyBytes = lof( #f1) source$ = input$( #f1, qtyBytes) close #f1   open "output.txt" for output as #f2 #f2 source$; close #f2   end
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
#Phix
Phix
with javascript_semantics function entropy(sequence s) sequence symbols = unique(s), counts = repeat(0,length(symbols)) for i=1 to length(s) do integer k = find(s[i],symbols) counts[k] += 1 end for atom H = 0 for i=1 to length(counts) do atom ci = counts[i]/length(s) H -= ci*log2(ci) end for return H end function sequence F_words = {"1","0"} for i=3 to 37 do F_words = append(F_words,F_words[i-1]&F_words[i-2]) end for for i=1 to length(F_words) do string fi = F_words[i] printf(1,"%2d: length %9d, entropy %f %s\n", {i,length(fi),entropy(fi),iff(i<10?fi,"...")}) end for
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.
#Seed7
Seed7
$ include "seed7_05.s7i";   const proc: main is func local var file: fastaFile is STD_NULL; var string: line is ""; var boolean: first is TRUE; begin fastaFile := open("fasta_format.in", "r"); if fastaFile <> STD_NULL then while hasNext(fastaFile) do line := getln(fastaFile); if startsWith(line, ">") then if first then first := FALSE; else writeln; end if; write(line[2 ..] <& ": "); else write(line); end if; end while; close(fastaFile); end if; writeln; end func;
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.
#Sidef
Sidef
func fasta_format(strings) { var out = [] var text = '' for line in (strings.lines) { if (line.begins_with('>')) { text.len && (out << text) text = line.substr(1)+': ' } else { text += line } } text.len && (out << text) return out }   fasta_format(DATA.slurp).each { .say }   __DATA__ >Rosetta_Example_1 THERECANBENOSPACE >Rosetta_Example_2 THERECANBESEVERAL LINESBUTTHEYALLMUST BECONCATENATED
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.
#Tcl
Tcl
proc fastaReader {filename} { set f [open $filename] set sep "" while {[gets $f line] >= 0} { if {[string match >* $line]} { puts -nonewline "$sep[string range $line 1 end]: " set sep "\n" } else { puts -nonewline $line } } puts "" close $f }   fastaReader ./rosettacode.fas
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
#Action.21
Action!
INT FUNC Fibonacci(INT n) INT curr,prev,tmp   IF n>=-1 AND n<=1 THEN RETURN (n) FI   prev=0 IF n>0 THEN curr=1 DO tmp=prev prev=curr curr==+tmp n==-1 UNTIL n=1 OD ELSE curr=-1 DO tmp=prev prev=curr curr==+tmp n==+1 UNTIL n=-1 OD FI RETURN (curr)   PROC Main() BYTE n INT f   Put(125) ;clear screen   FOR n=0 TO 22 DO f=Fibonacci(n) Position(2,n+1) PrintF("Fib(%I)=%I",n,f)   IF n>0 THEN f=Fibonacci(-n) Position(21,n+1) PrintF("Fib(%I)=%I",-n,f) FI OD RETURN
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
#ALGOL-M
ALGOL-M
  BEGIN   COMMENT RETURN P MOD Q; INTEGER FUNCTION MOD (P, Q); INTEGER P, Q; BEGIN MOD := P - Q * (P / Q); END;   INTEGER I, N, LIMIT, FOUND, START, DELTA;   WHILE 1 = 1 DO BEGIN WRITE ("NUMBER TO FACTOR (OR 0 TO QUIT):"); READ (N); IF N = 0 THEN GOTO DONE; WRITE ("THE FACTORS ARE:");   COMMENT CHECK WHETHER NUMBER IS EVEN OR ODD; IF MOD(N, 2) = 0 THEN BEGIN START := 2; DELTA := 1; END ELSE BEGIN START := 3; DELTA := 2; END;   COMMENT TEST POTENTIAL DIVISORS; FOUND := 0; I := START; LIMIT := N / I; WHILE I <= LIMIT DO BEGIN IF MOD(N, I) = 0 THEN BEGIN WRITEON (I); FOUND := FOUND + 1; END; I := I + DELTA; IF FOUND = 0 THEN LIMIT := N / I; END; IF FOUND = 0 THEN WRITEON (" NONE - THE NUMBER IS PRIME."); WRITE(""); END;   DONE: WRITE ("GOODBYE");   END
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.
#Fortran
Fortran
  module fft_mod implicit none integer, parameter :: dp=selected_real_kind(15,300) real(kind=dp), parameter :: pi=3.141592653589793238460_dp contains   ! In place Cooley-Tukey FFT recursive subroutine fft(x) complex(kind=dp), dimension(:), intent(inout) :: x complex(kind=dp) :: t integer :: N integer :: i complex(kind=dp), dimension(:), allocatable :: even, odd   N=size(x)   if(N .le. 1) return   allocate(odd((N+1)/2)) allocate(even(N/2))   ! divide odd =x(1:N:2) even=x(2:N:2)   ! conquer call fft(odd) call fft(even)   ! combine do i=1,N/2 t=exp(cmplx(0.0_dp,-2.0_dp*pi*real(i-1,dp)/real(N,dp),kind=dp))*even(i) x(i) = odd(i) + t x(i+N/2) = odd(i) - t end do   deallocate(odd) deallocate(even)   end subroutine fft   end module fft_mod   program test use fft_mod implicit none complex(kind=dp), dimension(8) :: data = (/1.0, 1.0, 1.0, 1.0, 0.0,   0.0, 0.0, 0.0/) integer :: i   call fft(data)   do i=1,8 write(*,'("(", F20.15, ",", F20.15, "i )")') data(i) end do   end program test
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.)
#EchoLisp
EchoLisp
  ;; M = 2^P - 1 , P prime ;; look for a prime divisor q such as : q < √ M, q = 1 or 7 modulo 8, q = 1 + 2kP ;; q is divisor if (powmod 2 P q) = 1 ;; m-divisor returns q or #f   (define ( m-divisor P ) ;; must limit the search as √ M may be HUGE (define maxprime (min 1_000_000_000 (sqrt (expt 2 P)))) (for ((q (in-range 1 maxprime (* 2 P)))) #:when (member (modulo q 8) '(1 7)) #:when (prime? q) #:break (= 1 (powmod 2 P q)) => q #f ))   (m-divisor 929) → 13007 (m-divisor 4423) → #f   (lib 'bigint) (prime? (1- (expt 2 4423))) ;; 2^4423 -1 is a Mersenne prime → #t    
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
#Julia
Julia
using DataStructures   function farey(n::Int) rst = SortedSet{Rational}(Rational[0, 1]) for den in 1:n, num in 1:den-1 push!(rst, Rational(num, den)) end return rst end   for n in 1:11 print("F_$n: ") for frac in farey(n) print(numerator(frac), "/", denominator(frac), " ") end println() end   for n in 100:100:1000 println("F_$n has ", length(farey(n)), " fractions") 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
#Kotlin
Kotlin
// version 1.1   fun farey(n: Int): List<String> { var a = 0 var b = 1 var c = 1 var d = n val f = mutableListOf("$a/$b") while (c <= n) { val k = (n + b) / d val aa = a val bb = b a = c b = d c = k * c - aa d = k * d - bb f.add("$a/$b") } return f.toList() }   fun main(args: Array<String>) { for (i in 1..11) println("${"%2d".format(i)}: ${farey(i).joinToString(" ")}") println() for (i in 100..1000 step 100) println("${"%4d".format(i)}: ${"%6d".format(farey(i).size)} fractions") }
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®)
#Rust
Rust
struct Digits { rest: usize, base: usize, }   impl Iterator for Digits { type Item = usize;   fn next(&mut self) -> Option<usize> { if self.rest == 0 { return None; } let (digit, rest) = (self.rest % self.base, self.rest / self.base); self.rest = rest; Some(digit) } }   fn digits(num: usize, base: usize) -> Digits { Digits { rest: num, base: base } }   struct FairSharing { participants: usize, index: usize, }   impl Iterator for FairSharing { type Item = usize; fn next(&mut self) -> Option<usize> { let digit_sum: usize = digits(self.index, self.participants).sum(); let selected = digit_sum % self.participants; self.index += 1; Some(selected) } }   fn fair_sharing(participants: usize) -> FairSharing { FairSharing { participants: participants, index: 0 } }   fn main() { for i in vec![2, 3, 5, 7] { println!("{}: {:?}", i, fair_sharing(i).take(25).collect::<Vec<usize>>()); } }
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®)
#Sidef
Sidef
for b in (2,3,5,11) { say ("#{'%2d' % b}: ", 25.of { .sumdigits(b) % b }) }
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®)
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Function Turn(base As Integer, n As Integer) As Integer Dim sum = 0 While n <> 0 Dim re = n Mod base n \= base sum += re End While Return sum Mod base End Function   Sub Fairshare(base As Integer, count As Integer) Console.Write("Base {0,2}:", base) For i = 1 To count Dim t = Turn(base, i - 1) Console.Write(" {0,2}", t) Next Console.WriteLine() End Sub   Sub TurnCount(base As Integer, count As Integer) Dim cnt(base) As Integer For i = 1 To base cnt(i - 1) = 0 Next   For i = 1 To count Dim t = Turn(base, i - 1) cnt(t) += 1 Next   Dim minTurn = Integer.MaxValue Dim maxTurn = Integer.MinValue Dim portion = 0 For i = 1 To base Dim num = cnt(i - 1) If num > 0 Then portion += 1 End If If num < minTurn Then minTurn = num End If If num > maxTurn Then maxTurn = num End If Next   Console.Write(" With {0} people: ", base) If 0 = minTurn Then Console.WriteLine("Only {0} have a turn", portion) ElseIf minTurn = maxTurn Then Console.WriteLine(minTurn) Else Console.WriteLine("{0} or {1}", minTurn, maxTurn) End If End Sub   Sub Main() Fairshare(2, 25) Fairshare(3, 25) Fairshare(5, 25) Fairshare(11, 25)   Console.WriteLine("How many times does each get a turn in 50000 iterations?") TurnCount(191, 50000) TurnCount(1377, 50000) TurnCount(49999, 50000) TurnCount(50000, 50000) TurnCount(50001, 50000) End Sub   End Module
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)
#Perl
Perl
use 5.010; use List::Util qw(sum); use Math::BigRat try => 'GMP'; use ntheory qw(binomial bernfrac);   sub faulhaber_triangle { my ($p) = @_; map { Math::BigRat->new(bernfrac($_)) * binomial($p, $_) / $p } reverse(0 .. $p-1); }   # First 10 rows of Faulhaber's triangle foreach my $p (1 .. 10) { say map { sprintf("%6s", $_) } faulhaber_triangle($p); }   # Extra credit my $p = 17; my $n = Math::BigInt->new(1000); my @r = faulhaber_triangle($p+1); say "\n", sum(map { $r[$_] * $n**($_ + 1) } 0 .. $#r);
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.
#Perl
Perl
use 5.014; use Math::Algebra::Symbols;   sub bernoulli_number { my ($n) = @_;   return 0 if $n > 1 && $n % 2;   my @A; for my $m (0 .. $n) { $A[$m] = symbols(1) / ($m + 1);   for (my $j = $m ; $j > 0 ; $j--) { $A[$j - 1] = $j * ($A[$j - 1] - $A[$j]); } }   return $A[0]; }   sub binomial { my ($n, $k) = @_; return 1 if $k == 0 || $n == $k; binomial($n - 1, $k - 1) + binomial($n - 1, $k); }   sub faulhaber_s_formula { my ($p) = @_;   my $formula = 0; for my $j (0 .. $p) { $formula += binomial($p + 1, $j) * bernoulli_number($j) * symbols('n')**($p + 1 - $j); }   (symbols(1) / ($p + 1) * $formula) =~ s/\$n/n/gr =~ s/\*\*/^/gr =~ s/\*/ /gr; }   foreach my $i (0 .. 9) { say "$i: ", faulhaber_s_formula($i); }
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
#Erlang
Erlang
  -module( fibonacci_nstep ).   -export( [nacci/2, task/0] ).   nacci( N, Ns ) when N =< erlang:length(Ns) -> {Sequence, _Not_sequence} = lists:split( N, Ns ), Sequence; nacci( N, Ns ) -> Nth = erlang:length( Ns ), {_Nth, Sequence_reversed} = lists:foldl( fun nacci_foldl/2, {Nth, lists:reverse(Ns)}, lists:seq(Nth+1, N) ), lists:reverse( Sequence_reversed ).   task() -> Names_and_funs = [{X, fun (N) -> nacci( N, Y ) end} || {X, Y} <- [{fibonacci, [1, 1]}, {tribonacci, [1, 1, 2]}, {tetranacci, [1, 1, 2, 4]}, {lukas, [2, 1]}]], [io:fwrite( "~p: ~p~n", [X, Y(10)] ) || {X, Y} <- Names_and_funs].       nacci_foldl( _N, {Nth, Ns} ) -> {Sum_ns, _Not_sum_ns} = lists:split( Nth, Ns ), {Nth, [lists:sum(Sum_ns) | Ns]}.  
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
#Scala
Scala
object FindCommonDirectoryPath extends App { def commonPath(paths: List[String]): String = { def common(a: List[String], b: List[String]): List[String] = (a, b) match { case (a :: as, b :: bs) if a equals b => a :: common(as, bs) case _ => Nil } if (paths.length < 2) paths.headOption.getOrElse("") else paths.map(_.split("/").toList).reduceLeft(common).mkString("/") }   val test = List( "/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members" ) println(commonPath(test)) }
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.
#Factor
Factor
10 <iota> >array [ even? ] filter . ! prints { 0 2 4 6 8 }
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
#Idris
Idris
partial fizzBuzz : Nat -> String fizzBuzz n = if (n `modNat` 15) == 0 then "FizzBuzz" else if (n `modNat` 3) == 0 then "Fizz" else if (n `modNat` 5) == 0 then "Buzz" else show n   main : IO () main = sequence_ $ map (putStrLn . fizzBuzz) [1..100]
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.
#Smalltalk
Smalltalk
(File name: 'input.txt') size printNl. (File name: '/input.txt') size printNl.
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.
#Standard_ML
Standard ML
val size = OS.FileSys.fileSize "input.txt" ;; val size = OS.FileSys.fileSize "/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.
#Stata
Stata
file open f using input.txt, read binary file seek f eof file seek f query display r(loc) file close f
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.
#Lingo
Lingo
---------------------------------------- -- Returns file as ByteArray -- @param {string} tFile -- @return {byteArray|false} ---------------------------------------- on getBytes (tFile) fp = xtra("fileIO").new() fp.openFile(tFile, 1) if fp.status() then return false data = fp.readByteArray(fp.getLength()) fp.closeFile() return data end   ---------------------------------------- -- Saves ByteArray to file -- @param {string} tFile -- @param {byteArray} tString -- @return {bool} success ---------------------------------------- on putBytes (tFile, tByteArray) fp = xtra("fileIO").new() fp.openFile(tFile, 2) err = fp.status() if not (err) then fp.delete() else if (err and not (err = -37)) then return false fp.createFile(tFile) if fp.status() then return false fp.openFile(tFile, 2) if fp.status() then return false fp.writeByteArray(tByteArray) fp.closeFile() return true end
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.
#Lisaac
Lisaac
Section Header   + name := FILE_IO;   Section Public   - main <- ( + e : ENTRY; + f : STD_FILE; + s : STRING;   e := FILE_SYSTEM.get "input.txt"; (e != NULL).if { f ?= e.open_read_only; (f != NULL).if { s := STRING.create(f.size); f.read s size (f.size); f.close; }; };   (s != NULL).if { e := FILE_SYSTEM.make_file "output.txt"; (e != NULL).if { f ?= e.open; (f != NULL).if { f.write s from (s.lower) size (s.count); f.close; }; }; }; );
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
#Picat
Picat
go => foreach(N in 1..37) F = fib(N), E = entropy(F), if N <= 10 then printf("%3d %10d %0.16f %w\n",N,length(F),E,F) else printf("%3d %10d %0.16f\n",N,length(F),E) end end, nl.   table fib(1) = "1". fib(2) = "0". fib(N) = fib(N-1) ++ fib(N-2).   entropy(L) = Entropy => Len = L.len, Occ = new_map(), foreach(E in L) Occ.put(E, Occ.get(E,0) + 1) end, Entropy = -sum([P2*log2(P2) : _C=P in Occ, P2 = P/Len]).
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
#PL.2FI
PL/I
fibword: procedure options (main); /* 9 October 2013 */ declare (fn, fnp1, fibword) bit (32000) varying; declare (i, ln, lnp1, lfibword) fixed binary(31);   fn = '1'b; fnp1 = '0'b; ln, lnp1 = 1; put skip edit (1, length(fn), fn) (f(2), f(10), x(1), b); put skip edit (2, length(fnp1), fnp1) (f(2), f(10), x(1), b); do i = 3 to 37; lfibword = lnp1 + ln; ln = lnp1; lnp1 = lfibword; if i <= 10 then do; fibword = fnp1 || fn; put skip edit (i, length(fibword), fibword) (f(2), f(10), x(1), b); fn = fnp1; fnp1 = fibword; end; else do; put skip edit (i, lfibword) (f(2), f(10)); end; end;   end fibword;
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.
#TMG
TMG
prog: ignore(spaces) loop: parse(line)\loop parse(( = {*} )); line: ( name | * = {} | seqns ); name: <>> ignore(none) smark string(nonl) scopy * ( [f>0?] = {} | = {*} ) [f=0] = { 1 2 <: > }; seqns: smark string(nonl) scopy * [f=0];   none: <<>>; nonl:  !<< >>; spaces: << >>;   f: 1;
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.
#uBasic.2F4tH
uBasic/4tH
If Cmd (0) < 2 Then Print "Usage: fasta <fasta file>" : End If Set(a, Open (Cmd(2), "r")) < 0 Then Print "Cannot open \q";Cmd(2);"\q" : End   Do While Read (a) ' while there are lines to process t = Tok (0) ' get a lime   If Peek(t, 0) = Ord(">") Then ' if it's a marker Print Show (Chop(t, 1)); ": "; Show (FUNC(_Payload(a))) Continue ' get the payload and print it EndIf   Print "Out of sequence" : Break ' this should never happen Loop   Close a ' close the file End ' and end the program   _Payload ' get the payload Param (1) Local (4)   b@ = Dup("") ' start with an empty string   Do c@ = Mark(a@) ' mark its position While Read (a@) ' now read a line d@ = Tok (0) ' get the line If Peek (d@, 0) = Ord(">") Then e@ = Head(a@, c@) : Break b@ = Join (b@, d@) ' marker? reset position and exit Loop ' if not add the line to current string   Return (b@) ' return the string
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.
#Wren
Wren
import "io" for File   var checkNoSpaces = Fn.new { |s| !s.contains(" ") && !s.contains("\t") }   var first = true   var process = Fn.new { |line| if (line[0] == ">") { if (!first) System.print() System.write("%(line[1..-1]): ") if (first) first = false } else if (first) { Fiber.abort("File does not begin with '>'.") } else if (checkNoSpaces.call(line)) { System.write(line) } else { Fiber.abort("Sequence contains space(s).") } }   var fileName = "input.fasta" File.open(fileName) { |file| var offset = 0 var line = "" while(true) { var b = file.readBytes(1, offset) offset = offset + 1 if (b == "\n") { process.call(line) line = "" // reset line variable } else if (b == "\r") { // Windows // wait for following "\n" } else if (b == "") { // end of stream System.print() return } else { line = line + b } } }
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
#ActionScript
ActionScript
public function fib(n:uint):uint { if (n < 2) return n;   return fib(n - 1) + fib(n - 2); }
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
#APL
APL
factors←{(0=(⍳⍵)|⍵)/⍳⍵} factors 12345 1 3 5 15 823 2469 4115 12345 factors 720 1 2 3 4 5 6 8 9 10 12 15 16 18 20 24 30 36 40 45 48 60 72 80 90 120 144 180 240 360 720