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/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.
#Python
Python
import sys print(sys.getrecursionlimit())
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
#Golfscript
Golfscript
100,{)6,{.(&},{1$1$%{;}{4*35+6875*25base{90\-}%}if}%\or}%n*
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.
#Nanoquery
Nanoquery
import Nanoquery.IO println new(File, "input.txt").length() println new(File, "/input.txt").length()
http://rosettacode.org/wiki/File_size
File size
Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java symbols binary   runSample(arg) return   -- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . method fileSize(fn) public static returns double ff = File(fn) fSize = ff.length() return fSize   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method runSample(arg) private static parse arg files if files = '' then files = 'input.txt F docs D /input.txt F /docs D' loop while files.length > 0 parse files fn ft files select case(ft.upper()) when 'F' then do ft = 'File' end when 'D' then do ft = 'Directory' end otherwise do ft = 'File' end end sz = fileSize(fn) say ft ''''fn'''' sz 'bytes.' end   return
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.
#Fortran
Fortran
program FileIO   integer, parameter :: out = 123, in = 124 integer :: err character :: c   open(out, file="output.txt", status="new", action="write", access="stream", iostat=err) if (err == 0) then open(in, file="input.txt", status="old", action="read", access="stream", iostat=err) if (err == 0) then err = 0 do while (err == 0) read(unit=in, iostat=err) c if (err == 0) write(out) c end do close(in) end if close(out) end if   end program FileIO
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
#Haskell
Haskell
module Main where   import Control.Monad import Data.List import Data.Monoid import Text.Printf   entropy :: (Ord a) => [a] -> Double entropy = sum . map (\c -> (c *) . logBase 2 $ 1.0 / c) . (\cs -> let { sc = sum cs } in map (/ sc) cs) . map (fromIntegral . length) . group . sort   fibonacci :: (Monoid m) => m -> m -> [m] fibonacci a b = unfoldr (\(a,b) -> Just (a, (b, a <> b))) (a,b)   main :: IO () main = do printf "%2s %10s %17s %s\n" "N" "length" "entropy" "word" zipWithM_ (\i v -> let { l = length v } in printf "%2d %10d %.15f %s\n" i l (entropy v) (if l > 40 then "..." else v)) [1..38::Int] (take 37 $ fibonacci "1" "0")
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.
#Haskell
Haskell
import Data.List ( groupBy )   parseFasta :: FilePath -> IO () parseFasta fileName = do file <- readFile fileName let pairedFasta = readFasta $ lines file mapM_ (\(name, code) -> putStrLn $ name ++ ": " ++ code) pairedFasta   readFasta :: [String] -> [(String, String)] readFasta = pair . map concat . groupBy (\x y -> notName x && notName y) where notName :: String -> Bool notName = (/=) '>' . head   pair :: [String] -> [(String, String)] pair [] = [] pair (x : y : xs) = (drop 1 x, y) : pair xs
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.
#J
J
require 'strings' NB. not needed for J versions greater than 6. parseFasta=: ((': ' ,~ LF&taketo) , (LF -.~ LF&takeafter));._1
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.
#ALGOL_68
ALGOL 68
PRIO DICE = 9; # ideally = 11 #   OP DICE = ([]SCALAR in, INT step)[]SCALAR: ( ### Dice the array, extract array values a "step" apart ### IF step = 1 THEN in ELSE INT upb out := 0; [(UPB in-LWB in)%step+1]SCALAR out; FOR index FROM LWB in BY step TO UPB in DO out[upb out+:=1] := in[index] OD; out[@LWB in] FI );   PROC fft = ([]SCALAR in t)[]SCALAR: ( ### The Cooley-Tukey FFT algorithm ### IF LWB in t >= UPB in t THEN in t[@0] ELSE []SCALAR t = in t[@0]; INT n = UPB t + 1, half n = n % 2; [LWB t:UPB t]SCALAR coef;   []SCALAR even = fft(t DICE 2), odd = fft(t[1:]DICE 2);   COMPL i = 0 I 1;   REAL w = 2*pi / n; FOR k FROM LWB t TO half n-1 DO COMPL cis t = scalar exp(0 I (-w * k))*odd[k]; coef[k] := even[k] + cis t; coef[k + half n] := even[k] - cis t OD; coef FI );
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.)
#8086_Assembly
8086 Assembly
P: equ 929 ; P for 2^P-1 cpu 8086 bits 16 org 100h section .text mov ax,P ; Is P prime? call prime mov dx,notprm jc msg ; If not, say so and stop. xor bp,bp ; Let BP hold k test_k: inc bp ; k += 1 mov ax,P ; Calculate 2kP + 1 mul bp ; AX = kP shl ax,1 ; AX = 2kP inc ax ; AX = 2kP + 1 mov dx,ovfl ; If AX overflows (16 bits), say so and stop jc msg mov bx,ax ; What is 2^P mod (2kP+1)? mov cx,P call modpow dec ax ; If it is 1, we're done jnz test_k ; If not, increment K and try again mov dx,factor ; If so, we found a factor call msg prbx: mov ax,10 ; The factor is still in BX xchg bx,ax ; Put factor in AX and divisor (10) in BX mov di,number ; Generate ASCII representation of number digit: xor dx,dx div bx ; Divide current number by 10, add dl,'0' ; add '0' to remainder, dec di ; move pointer back, mov [di],dl ; store digit, test ax,ax ; and if there are more digits, jnz digit ; find the next digit. mov dx,di ; Finally, print the number. jmp msg ;;; Calculate 2^CX mod BX ;;; Output: AX ;;; Destroyed: CX, DX modpow: shl cx,1 ; Shift CX left until top bit in high bit jnc modpow ; Keep shifting while carry zero rcr cx,1 ; Put the top bit back into CX mov ax,1 ; Start with square = 1 .step: mul ax ; Square (result is 32-bit, goes in DX:AX) shl cx,1 ; Grab a bit from CX jnc .nodbl ; If zero, don't multiply by two shl ax,1 ; Shift DX:AX left (mul by two) rcl dx,1 .nodbl: div bx ; Divide DX:AX by BX (putting modulus in DX) mov ax,dx ; Continue with modulus jcxz .done ; When CX reaches 0, we're done jmp .step ; Otherwise, do the next step .done: ret ;;; Is AX prime? ;;; Output: carry clear if prime, set if not prime. ;;; Destroyed: AX, BX, CX, DX, SI, DI, BP prime: mov cx,[prcnt] ; See if AX is already in the list of primes mov di,primes repne scasw ; If so, return je modpow.done ; Reuse the RET just above here (carry clear) mov bp,ax ; Move AX out of the way mov bx,[di-2] ; Start generating new primes .sieve: inc bx ; BX = last prime + 2 inc bx cmp bp,bx ; If BX higher than number to test, jb modpow.done ; stop, number is not prime. (carry set) mov cx,[prcnt] ; CX = amount of current primes mov si,primes ; SI = start of primes .try: mov ax,bx ; BX divisible by current prime? xor dx,dx div word [si] test dx,dx ; If so, BX is not prime. jz .sieve inc si inc si loop .try ; Otherwise, try next prime. mov ax,bx ; If we get here, BX _is_ prime stosw ; So add it to the list inc word [prcnt] ; We have one more prime cmp ax,bp ; Is it the prime we are looking for? jne .sieve ; If not, try next prime ret ;;; Print message in DX msg: mov ah,9 int 21h ret section .data db "*****" ; Placeholder for number number: db "$" notprm: db "P is not prime.$" ovfl: db "Range of factor exceeded (max 16 bits)." factor: db "Found factor: $" prcnt: dw 2 ; Amount of primes currently in list primes: dw 2, 3 ; List of primes to be extended
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
#C.23
C#
using System; using System.Collections.Generic; using System.Linq;   public static class FareySequence { public static void Main() { for (int i = 1; i <= 11; i++) { Console.WriteLine($"F{i}: " + string.Join(", ", Generate(i).Select(f => $"{f.num}/{f.den}"))); } for (int i = 100; i <= 1000; i+=100) { Console.WriteLine($"F{i} has {Generate(i).Count()} terms."); } }   public static IEnumerable<(int num, int den)> Generate(int i) { var comparer = Comparer<(int n, int d)>.Create((a, b) => (a.n * b.d).CompareTo(a.d * b.n)); var seq = new SortedSet<(int n, int d)>(comparer); for (int d = 1; d <= i; d++) { for (int n = 0; n <= d; n++) { seq.Add((n, d)); } } return seq; } }
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®)
#D
D
import std.array; import std.stdio;   int turn(int base, int n) { int sum = 0; while (n != 0) { int re = n % base; n /= base; sum += re; } return sum % base; }   void fairShare(int base, int count) { writef("Base %2d:", base); foreach (i; 0..count) { auto t = turn(base, i); writef(" %2d", t); } writeln; }   void turnCount(int base, int count) { auto cnt = uninitializedArray!(int[])(base); cnt[] = 0;   foreach (i; 0..count) { auto t = turn(base, i); cnt[t]++; }   auto minTurn = int.max; auto maxTurn = int.min; int portion = 0; foreach (num; cnt) { if (num > 0) { portion++; } if (num < minTurn) { minTurn = num; } if (maxTurn < num) { maxTurn = num; } }   writef(" With %d people: ", base); if (minTurn == 0) { writefln("Only %d have a turn", portion); } else if (minTurn == maxTurn) { writeln(minTurn); } else { writeln(minTurn," or ", maxTurn); } }   void main() { fairShare(2, 25); fairShare(3, 25); fairShare(5, 25); fairShare(11, 25);   writeln("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); }
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)
#F.C5.8Drmul.C3.A6
Fōrmulæ
package main   import ( "fmt" "math/big" )   func bernoulli(n uint) *big.Rat { a := make([]big.Rat, n+1) z := new(big.Rat) for m := range a { a[m].SetFrac64(1, int64(m+1)) for j := m; j >= 1; j-- { d := &a[j-1] d.Mul(z.SetInt64(int64(j)), d.Sub(d, &a[j])) } } // return the 'first' Bernoulli number if n != 1 { return &a[0] } a[0].Neg(&a[0]) return &a[0] }   func binomial(n, k int) int64 { if n <= 0 || k <= 0 || n < k { return 1 } var num, den int64 = 1, 1 for i := k + 1; i <= n; i++ { num *= int64(i) } for i := 2; i <= n-k; i++ { den *= int64(i) } return num / den }   func faulhaberTriangle(p int) []big.Rat { coeffs := make([]big.Rat, p+1) q := big.NewRat(1, int64(p)+1) t := new(big.Rat) u := new(big.Rat) sign := -1 for j := range coeffs { sign *= -1 d := &coeffs[p-j] t.SetInt64(int64(sign)) u.SetInt64(binomial(p+1, j)) d.Mul(q, t) d.Mul(d, u) d.Mul(d, bernoulli(uint(j))) } return coeffs }   func main() { for i := 0; i < 10; i++ { coeffs := faulhaberTriangle(i) for _, coeff := range coeffs { fmt.Printf("%5s ", coeff.RatString()) } fmt.Println() } fmt.Println() // get coeffs for (k + 1)th row k := 17 cc := faulhaberTriangle(k) n := int64(1000) nn := big.NewRat(n, 1) np := big.NewRat(1, 1) sum := new(big.Rat) tmp := new(big.Rat) for _, c := range cc { np.Mul(np, nn) tmp.Set(np) tmp.Mul(tmp, &c) sum.Add(sum, tmp) } fmt.Println(sum.RatString()) }
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.
#Go
Go
package main   import ( "fmt" "math/big" )   func bernoulli(z *big.Rat, n int64) *big.Rat { if z == nil { z = new(big.Rat) } a := make([]big.Rat, n+1) for m := range a { a[m].SetFrac64(1, int64(m+1)) for j := m; j >= 1; j-- { d := &a[j-1] d.Mul(z.SetInt64(int64(j)), d.Sub(d, &a[j])) } } return z.Set(&a[0]) }   func main() { // allocate needed big.Rat's once q := new(big.Rat) c := new(big.Rat) // coefficients be := new(big.Rat) // for Bernoulli numbers bi := big.NewRat(1, 1) // for binomials   for p := int64(0); p < 10; p++ { fmt.Print(p, " : ") q.SetFrac64(1, p+1) neg := true for j := int64(0); j <= p; j++ { neg = !neg if neg { c.Neg(q) } else { c.Set(q) } bi.Num().Binomial(p+1, j) bernoulli(be, j) c.Mul(c, bi) c.Mul(c, be) if c.Num().BitLen() == 0 { continue } if j == 0 { fmt.Printf(" %4s", c.RatString()) } else { fmt.Printf(" %+2d/%-2d", c.Num(), c.Denom()) } fmt.Print("×n") if exp := p + 1 - j; exp > 1 { fmt.Printf("^%-2d", exp) } } fmt.Println() } }
http://rosettacode.org/wiki/Fermat_numbers
Fermat numbers
In mathematics, a Fermat number, named after Pierre de Fermat who first studied them, is a positive integer of the form Fn = 22n + 1 where n is a non-negative integer. Despite the simplicity of generating Fermat numbers, they have some powerful mathematical properties and are extensively used in cryptography & pseudo-random number generation, and are often linked to other number theoric fields. As of this writing, (mid 2019), there are only five known prime Fermat numbers, the first five (F0 through F4). Only the first twelve Fermat numbers have been completely factored, though many have been partially factored. Task Write a routine (function, procedure, whatever) to generate Fermat numbers. Use the routine to find and display here, on this page, the first 10 Fermat numbers - F0 through F9. Find and display here, on this page, the prime factors of as many Fermat numbers as you have patience for. (Or as many as can be found in five minutes or less of processing time). Note: if you make it past F11, there may be money, and certainly will be acclaim in it for you. See also Wikipedia - Fermat numbers OEIS:A000215 - Fermat numbers OEIS:A019434 - Fermat primes
#Ring
Ring
  decimals(0) load "stdlib.ring"   see "working..." + nl see "The first 10 Fermat numbers are:" + nl   num = 0 limit = 9   for n = 0 to limit fermat = pow(2,pow(2,n)) + 1 mod = fermat%2 if n > 5 ferm = string(fermat) tmp = number(right(ferm,1))+1 fermat = left(ferm,len(ferm)-1) + string(tmp) ok see "F(" + n + ") = " + fermat + nl next   see "done..." + nl  
http://rosettacode.org/wiki/Fermat_numbers
Fermat numbers
In mathematics, a Fermat number, named after Pierre de Fermat who first studied them, is a positive integer of the form Fn = 22n + 1 where n is a non-negative integer. Despite the simplicity of generating Fermat numbers, they have some powerful mathematical properties and are extensively used in cryptography & pseudo-random number generation, and are often linked to other number theoric fields. As of this writing, (mid 2019), there are only five known prime Fermat numbers, the first five (F0 through F4). Only the first twelve Fermat numbers have been completely factored, though many have been partially factored. Task Write a routine (function, procedure, whatever) to generate Fermat numbers. Use the routine to find and display here, on this page, the first 10 Fermat numbers - F0 through F9. Find and display here, on this page, the prime factors of as many Fermat numbers as you have patience for. (Or as many as can be found in five minutes or less of processing time). Note: if you make it past F11, there may be money, and certainly will be acclaim in it for you. See also Wikipedia - Fermat numbers OEIS:A000215 - Fermat numbers OEIS:A019434 - Fermat primes
#Ruby
Ruby
This uses the `factor` function from the `coreutils` library that comes standard with most GNU/Linux, BSD, and Unix systems. https://www.gnu.org/software/coreutils/ https://en.wikipedia.org/wiki/GNU_Core_Utilities
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
#Befunge
Befunge
110p>>55+109"iccanaceD"22099v v9013"Tetranacci"9014"Lucas"< >"iccanobirT"2109"iccanobiF"v >>:#,_0p20p0>:01-\2>#v0>#g<>> ^_@#:,+55$_^ JH v`1:v#\p03< _$.1+:77+`^vg03:_0g+>\:1+#^ 50p-\30v v\<>\30g1-\^$$_:1- 05g04\g< >`#^_:40p30g0>^!:g
http://rosettacode.org/wiki/Feigenbaum_constant_calculation
Feigenbaum constant calculation
Task Calculate the Feigenbaum constant. See   Details in the Wikipedia article:   Feigenbaum constant.
#Ruby
Ruby
def main maxIt = 13 maxItJ = 10 a1 = 1.0 a2 = 0.0 d1 = 3.2 puts " i d" for i in 2 .. maxIt a = a1 + (a1 - a2) / d1 for j in 1 .. maxItJ x = 0.0 y = 0.0 for k in 1 .. 1 << i y = 1.0 - 2.0 * y * x x = a - x * x end a = a - x / y end d = (a1 - a2) / (a - a1) print "%2d  %.8f\n" % [i, d] d1 = d a2 = a1 a1 = a end end   main()
http://rosettacode.org/wiki/Feigenbaum_constant_calculation
Feigenbaum constant calculation
Task Calculate the Feigenbaum constant. See   Details in the Wikipedia article:   Feigenbaum constant.
#Scala
Scala
object Feigenbaum1 extends App { val (max_it, max_it_j) = (13, 10) var (a1, a2, d1, a) = (1.0, 0.0, 3.2, 0.0)   println(" i d") var i: Int = 2 while (i <= max_it) { a = a1 + (a1 - a2) / d1 for (_ <- 0 until max_it_j) { var (x, y) = (0.0, 0.0) for (_ <- 0 until 1 << i) { y = 1.0 - 2.0 * y * x x = a - x * x } a -= x / y } val d: Double = (a1 - a2) / (a - a1) printf("%2d  %.8f\n", i, d) d1 = d a2 = a1 a1 = a i += 1 }   }
http://rosettacode.org/wiki/File_extension_is_in_extensions_list
File extension is in extensions list
File extension is in extensions list You are encouraged to solve this task according to the task description, using any language you may know. Filename extensions are a rudimentary but commonly used way of identifying files types. Task Given an arbitrary filename and a list of extensions, tell whether the filename has one of those extensions. Notes: The check should be case insensitive. The extension must occur at the very end of the filename, and be immediately preceded by a dot (.). You may assume that none of the given extensions are the empty string, and none of them contain a dot. Other than that they may be arbitrary strings. Extra credit: Allow extensions to contain dots. This way, users of your function/program have full control over what they consider as the extension in cases like: archive.tar.gz Please state clearly whether or not your solution does this. Test cases The following test cases all assume this list of extensions:   zip, rar, 7z, gz, archive, A## Filename Result MyData.a## true MyData.tar.Gz true MyData.gzip false MyData.7z.backup false MyData... false MyData false If your solution does the extra credit requirement, add tar.bz2 to the list of extensions, and check the following additional test cases: Filename Result MyData_v1.0.tar.bz2 true MyData_v1.0.bz2 false Motivation Checking if a file is in a certain category of file formats with known extensions (e.g. archive files, or image files) is a common problem in practice, and may be approached differently from extracting and outputting an arbitrary extension (see e.g. FileNameExtensionFilter in Java). It also requires less assumptions about the format of an extension, because the calling code can decide what extensions are valid. For these reasons, this task exists in addition to the Extract file extension task. Related tasks Extract file extension String matching
#Wren
Wren
import "/str" for Str import "/fmt" for Fmt   var exts = ["zip", "rar", "7z", "gz", "archive", "A##", "tar.bz2"]   var tests = [ "MyData.a##", "MyData.tar.Gz", "MyData.gzip" , "MyData.7z.backup", "MyData...", "MyData", "MyData_v1.0.tar.bz2", "MyData_v1.0.bz2" ]   var ucExts = exts.map { |e| "." + Str.upper(e) } for (test in tests) { var ucTest = Str.upper(test) var hasExt = false var i = 0 for (ext in ucExts) { hasExt = ucTest.endsWith(ext) if (hasExt) { Fmt.print("$-20s $s (extension: $s)", test, hasExt, exts[i]) break } i = i + 1 } if (!hasExt) Fmt.print("$-20s $-5s", test, hasExt) }
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#Ring
Ring
  load "stdlib.ring" see GetFileInfo( "test.ring" )   func GetFileInfo cFile cOutput = systemcmd("dir /T:W " + cFile ) aList = str2list(cOutput) cLine = aList[6] aInfo = split(cLine," ") return aInfo  
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#Ruby
Ruby
#Get modification time: modtime = File.mtime('filename')   #Set the access and modification times: File.utime(actime, mtime, 'path')   #Set just the modification time: File.utime(File.atime('path'), mtime, 'path')   #Set the access and modification times to the current time: File.utime(nil, nil, 'path')
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#Run_BASIC
Run BASIC
files #f, DefaultDir$ + "\*.*" ' all files in the default directory   print "hasanswer: ";#f HASANSWER() ' does it exist print "rowcount: ";#f ROWCOUNT() ' number of files in the directory print ' #f DATEFORMAT("mm/dd/yy") ' set format of file date to template given #f TIMEFORMAT("hh:mm:ss") ' set format of file time to template given   for i = 1 to #f rowcount() ' loop through the files if #f hasanswer() then ' or loop with while #f hasanswer() print "nextfile info: ";#f nextfile$(" ") ' set the delimiter for nextfile info print "name: ";name$ ' file name print "size: ";#f SIZE() ' file size print "date: ";#f DATE$() ' file date print "time: ";#f TIME$() ' file time print "isdir: ";#f ISDIR() ' is it a directory or file   name$ = #f NAME$() shell$("touch -t 201002032359.59 ";name$;""") ' shell to os to set date   print end if next
http://rosettacode.org/wiki/Fibonacci_word/fractal
Fibonacci word/fractal
The Fibonacci word may be represented as a fractal as described here: (Clicking on the above website   (hal.archives-ouvertes.fr)   will leave a cookie.) For F_wordm start with F_wordCharn=1 Draw a segment forward If current F_wordChar is 0 Turn left if n is even Turn right if n is odd next n and iterate until end of F_word Task Create and display a fractal similar to Fig 1. (Clicking on the above website   (hal.archives-ouvertes.fr)   will leave a cookie.)
#Ruby
Ruby
def fibonacci_word(n) words = ["1", "0"] (n-1).times{ words << words[-1] + words[-2] } words[n] end   def print_fractal(word) area = Hash.new(" ") x = y = 0 dx, dy = 0, -1 area[[x,y]] = "S" word.each_char.with_index(1) do |c,n| area[[x+dx, y+dy]] = dx.zero? ? "|" : "-" x, y = x+2*dx, y+2*dy area[[x, y]] = "+" dx,dy = n.even? ? [dy,-dx] : [-dy,dx] if c=="0" end   (xmin, xmax), (ymin, ymax) = area.keys.transpose.map(&:minmax) for y in ymin..ymax puts (xmin..xmax).map{|x| area[[x,y]]}.join end end   word = fibonacci_word(16) print_fractal(word)
http://rosettacode.org/wiki/Fibonacci_word/fractal
Fibonacci word/fractal
The Fibonacci word may be represented as a fractal as described here: (Clicking on the above website   (hal.archives-ouvertes.fr)   will leave a cookie.) For F_wordm start with F_wordCharn=1 Draw a segment forward If current F_wordChar is 0 Turn left if n is even Turn right if n is odd next n and iterate until end of F_word Task Create and display a fractal similar to Fig 1. (Clicking on the above website   (hal.archives-ouvertes.fr)   will leave a cookie.)
#Rust
Rust
// [dependencies] // svg = "0.8.0"   use svg::node::element::path::Data; use svg::node::element::Path;   fn fibonacci_word(n: usize) -> Vec<u8> { let mut f0 = vec![1]; let mut f1 = vec![0]; if n == 0 { return f0; } else if n == 1 { return f1; } let mut i = 2; loop { let mut f = Vec::with_capacity(f1.len() + f0.len()); f.extend(&f1); f.extend(f0); if i == n { return f; } f0 = f1; f1 = f; i += 1; } }   struct FibwordFractal { current_x: f64, current_y: f64, current_angle: i32, line_length: f64, max_x: f64, max_y: f64, }   impl FibwordFractal { fn new(x: f64, y: f64, length: f64, angle: i32) -> FibwordFractal { FibwordFractal { current_x: x, current_y: y, current_angle: angle, line_length: length, max_x: 0.0, max_y: 0.0, } } fn execute(&mut self, n: usize) -> Path { let mut data = Data::new().move_to((self.current_x, self.current_y)); for (i, byte) in fibonacci_word(n).iter().enumerate() { data = self.draw_line(data); if *byte == 0u8 { self.turn(if i % 2 == 1 { -90 } else { 90 }); } } Path::new() .set("fill", "none") .set("stroke", "black") .set("stroke-width", "1") .set("d", data) } fn draw_line(&mut self, data: Data) -> Data { let theta = (self.current_angle as f64).to_radians(); self.current_x += self.line_length * theta.cos(); self.current_y += self.line_length * theta.sin(); if self.current_x > self.max_x { self.max_x = self.current_x; } if self.current_y > self.max_y { self.max_y = self.current_y; } data.line_to((self.current_x, self.current_y)) } fn turn(&mut self, angle: i32) { self.current_angle = (self.current_angle + angle) % 360; } fn save(file: &str, order: usize) -> std::io::Result<()> { use svg::node::element::Rectangle; let x = 5.0; let y = 5.0; let rect = Rectangle::new() .set("width", "100%") .set("height", "100%") .set("fill", "white"); let mut ff = FibwordFractal::new(x, y, 1.0, 0); let path = ff.execute(order); let document = svg::Document::new() .set("width", 5 + ff.max_x as usize) .set("height", 5 + ff.max_y as usize) .add(rect) .add(path); svg::save(file, &document) } }   fn main() { FibwordFractal::save("fibword_fractal.svg", 22).unwrap(); }
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
#Oz
Oz
declare fun {CommonPrefix Sep Paths} fun {GetParts P} {String.tokens P Sep} end Parts = {ZipN {Map Paths GetParts}} EqualParts = {List.takeWhile Parts fun {$ X|Xr} {All Xr {Equals X}} end} in {Join Sep {Map EqualParts Head}} end   fun {ZipN Xs} if {Some Xs {Equals nil}} then nil else {Map Xs Head} | {ZipN {Map Xs Tail}} end end   fun {Join Sep Xs} {FoldR Xs fun {$ X Z} {Append X Sep|Z} end nil} end   fun {Equals C} fun {$ X} X == C end end   fun {Head X|_} X end   fun {Tail _|Xr} Xr end in {System.showInfo {CommonPrefix &/ ["/home/user1/tmp/coverage/test" "/home/user1/tmp/covert/operator" "/home/user1/tmp/coven/members"]}}
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.
#D
D
void main() { import std.algorithm: filter, equal;   immutable data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; auto evens = data.filter!(x => x % 2 == 0); // Lazy. assert(evens.equal([2, 4, 6, 8, 10])); }
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.
#Quackery
Quackery
0 [ 1+ dup echo cr recurse ]
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.
#R
R
#Get the limit options("expressions")   #Set it options(expressions = 10000)   #Test it recurse <- function(x) { print(x) recurse(x+1)   } recurse(0)
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.
#Racket
Racket
#lang racket (define (recursion-limit) (with-handlers ((exn? (lambda (x) 0))) (add1 (recursion-limit))))
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
#Golo
Golo
module FizzBuzz   augment java.lang.Integer { function getFizzAndOrBuzz = |this| -> match { when this % 15 == 0 then "FizzBuzz" when this % 3 == 0 then "Fizz" when this % 5 == 0 then "Buzz" otherwise this } }   function main = |args| { foreach i in [1..101] { println(i: getFizzAndOrBuzz()) } }  
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.
#NewLISP
NewLISP
(println (first (file-info "input.txt"))) (println (first (file-info "/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.
#Nim
Nim
import os echo getFileSize "input.txt" echo getFileSize "/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.
#Objeck
Objeck
  use IO; ... File("input.txt")->Size()->PrintLine(); File("c:\input.txt")->Size()->PrintLine();  
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.
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   /' input.txt contains:   The quick brown fox jumps over the lazy dog. Empty vessels make most noise. Too many chefs spoil the broth. A rolling stone gathers no moss. '/   Open "output.txt" For Output As #1 Open "input.txt" For Input As #2 Dim line_ As String ' note that line is a keyword   While Not Eof(2) Line Input #2, line_ Print #1, line_ Wend   Close #2 Close #1
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.
#Frink
Frink
  contents = read["file:input.txt"] w = new Writer["output.txt"] w.print[contents] w.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
#Icon_and_Unicon
Icon and Unicon
procedure main(A) n := integer(A[1]) | 37 write(right("N",4)," ",right("length",15)," ",left("Entrophy",15)," ", " Fibword") every w := fword(i := 1 to n) do { writes(right(i,4)," ",right(*w,15)," ",left(H(w),15)) if i <= 8 then write(": ",w) else write() } end   procedure fword(n) static fcache initial fcache := table() /fcache[n] := case n of { 1: "1" 2: "0" default: fword(n-1)||fword(n-2) } return fcache[n] end   procedure H(s) P := table(0.0) every P[!s] +:= 1.0/*s every (h := 0.0) -:= P[c := key(P)] * log(P[c],2) return h 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.
#Java
Java
import java.io.*; import java.util.Scanner;   public class ReadFastaFile {   public static void main(String[] args) throws FileNotFoundException {   boolean first = true;   try (Scanner sc = new Scanner(new File("test.fasta"))) { while (sc.hasNextLine()) { String line = sc.nextLine().trim(); if (line.charAt(0) == '>') { if (first) first = false; else System.out.println(); System.out.printf("%s: ", line.substring(1)); } else { System.out.print(line); } } } System.out.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.
#JavaScript
JavaScript
  const fs = require("fs"); const readline = require("readline");   const args = process.argv.slice(2); if (!args.length) { console.error("must supply file name"); process.exit(1); }   const fname = args[0];   const readInterface = readline.createInterface({ input: fs.createReadStream(fname), console: false, });   let sep = ""; readInterface.on("line", (line) => { if (line.startsWith(">")) { process.stdout.write(sep); sep = "\n"; process.stdout.write(line.substring(1) + ": "); } else { process.stdout.write(line); } });   readInterface.on("close", () => process.stdout.write("\n"));  
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
#0815
0815
  <:1:~>|~#:end:>~x}:str:/={^:wei:~%x<:a:x=$~ =}:wei:x<:1:+{>~>x=-#:fin:^:str:}:fin:{{~%  
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.
#APL
APL
fft←{ 1>k←2÷⍨N←⍴⍵:⍵ 0≠1|2⍟N:'Argument must be a power of 2 in length' even←∇(N⍴0 1)/⍵ odd←∇(N⍴1 0)/⍵ T←even×*(0J¯2×(○1)×(¯1+⍳k)÷N) (odd+T),odd-T }
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.)
#360_Assembly
360 Assembly
* Factors of a Mersenne number 11/09/2015 MERSENNE CSECT USING MERSENNE,R15 MVC Q,=F'929' q=929 (M929=2**929-1) LA R6,1 k=1 LOOPK C R6,=F'1048576' do k=1 to 2**20 BNL ELOOPK LR R5,R6 k M R4,Q *q SLA R5,1 *2 by shift left 1 LA R5,1(R5) +1 ST R5,P p=k*q*2+1 L R2,P p N R2,=F'7' p&7 C R2,=F'1' if ((p&7)=1) p='*001' BE OK C R2,=F'7' or if ((p&7)=7) p='*111' BNE NOTOK OK MVI PRIME,X'00' then prime=false is prime? LA R2,2 loop count=2 LA R1,2 j=2 and after j=3 J2J3 L R4,P p SRDA R4,32 r4>>r5 DR R4,R1 p/j LTR R4,R4 if p//j=0 BZ NOTPRIME then goto notprime LA R1,1(R1) j=j+1 BCT R2,J2J3 LA R7,5 d=5 WHILED LR R5,R7 d MR R4,R7 *d C R5,P do while(d*d<=p) BH EWHILED LA R2,2 loop count=2 LA R1,2 j=2 and after j=4 J2J4 L R4,P p SRDA R4,32 r4>>r5 DR R4,R7 /d LTR R4,R4 if p//d=0 BZ NOTPRIME then goto notprime AR R7,R1 d=d+j LA R1,2(R1) j=j+2 BCT R2,J2J4 B WHILED EWHILED MVI PRIME,X'01' prime=true so is prime NOTPRIME L R8,Q i=q MVC Y,=F'1' y=1 MVC Z,=F'2' z=2 WHILEI LTR R8,R8 do while(i^=0) BZ EWHILEI ST R8,PG i TM PG+3,B'00000001' if first bit of i not 1 BZ NOTFIRST L R5,Y y M R4,Z *z LA R4,0 D R4,P /p ST R4,Y y=(y*z)//p NOTFIRST L R5,Z z M R4,Z *z LA R4,0 D R4,P /p ST R4,Z z=(z*z)//p SRA R8,1 i=i/2 by shift right 1 B WHILEI EWHILEI CLI PRIME,X'01' if prime BNE NOTOK CLC Y,=F'1' and if y=1 BNE NOTOK MVC FACTOR,P then factor=p B OKFACTOR NOTOK LA R6,1(R6) k=k+1 B LOOPK ELOOPK MVC FACTOR,=F'0' factor=0 OKFACTOR L R1,Q XDECO R1,PG edit q L R1,FACTOR XDECO R1,PG+12 edit factor XPRNT PG,24 print XR R15,R15 BR R14 PRIME DS X flag for prime Q DS F P DS F Y DS F Z DS F FACTOR DS F a factor of q PG DS CL24 buffer YREGS END MERSENNE
http://rosettacode.org/wiki/Factors_of_a_Mersenne_number
Factors of a Mersenne number
A Mersenne number is a number in the form of 2P-1. If P is prime, the Mersenne number may be a Mersenne prime (if P is not prime, the Mersenne number is also not prime). In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before starting a, potentially lengthy, Lucas-Lehmer test. There are very efficient algorithms for determining if a number divides 2P-1 (or equivalently, if 2P mod (the number) = 1). Some languages already have built-in implementations of this exponent-and-mod operation (called modPow or similar). The following is how to implement this modPow yourself: For example, let's compute 223 mod 47. Convert the exponent 23 to binary, you get 10111. Starting with square = 1, repeatedly square it. Remove the top bit of the exponent, and if it's 1 multiply square by the base of the exponentiation (2), then compute square modulo 47. Use the result of the modulo from the last step as the initial value of square in the next step: remove optional square top bit multiply by 2 mod 47 ──────────── ─────── ───────────── ────── 1*1 = 1 1 0111 1*2 = 2 2 2*2 = 4 0 111 no 4 4*4 = 16 1 11 16*2 = 32 32 32*32 = 1024 1 1 1024*2 = 2048 27 27*27 = 729 1 729*2 = 1458 1 Since 223 mod 47 = 1, 47 is a factor of 2P-1. (To see this, subtract 1 from both sides: 223-1 = 0 mod 47.) Since we've shown that 47 is a factor, 223-1 is not prime. Further properties of Mersenne numbers allow us to refine the process even more. Any factor q of 2P-1 must be of the form 2kP+1, k being a positive integer or zero. Furthermore, q must be 1 or 7 mod 8. Finally any potential factor q must be prime. As in other trial division algorithms, the algorithm stops when 2kP+1 > sqrt(N). These primality tests only work on Mersenne numbers where P is prime. For example, M4=15 yields no factors using these techniques, but factors into 3 and 5, neither of which fit 2kP+1. Task Using the above method find a factor of 2929-1 (aka M929) Related tasks   count in factors   prime decomposition   factors of an integer   Sieve of Eratosthenes   primality by trial division   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division See also   Computers in 1948: 2127 - 1       (Note:   This video is no longer available because the YouTube account associated with this video has been terminated.)
#Ada
Ada
with Ada.Text_IO; -- reuse Is_Prime from [[Primality by Trial Division]] with Is_Prime;   procedure Mersenne is function Is_Set (Number : Natural; Bit : Positive) return Boolean is begin return Number / 2 ** (Bit - 1) mod 2 = 1; end Is_Set;   function Get_Max_Bit (Number : Natural) return Natural is Test : Natural := 0; begin while 2 ** Test <= Number loop Test := Test + 1; end loop; return Test; end Get_Max_Bit;   function Modular_Power (Base, Exponent, Modulus : Positive) return Natural is Maximum_Bit : constant Natural := Get_Max_Bit (Exponent); Square  : Natural := 1; begin for Bit in reverse 1 .. Maximum_Bit loop Square := Square ** 2; if Is_Set (Exponent, Bit) then Square := Square * Base; end if; Square := Square mod Modulus; end loop; return Square; end Modular_Power;   Not_A_Prime_Exponent : exception;   function Get_Factor (Exponent : Positive) return Natural is Factor : Positive; begin if not Is_Prime (Exponent) then raise Not_A_Prime_Exponent; end if; for K in 1 .. 16384 / Exponent loop Factor := 2 * K * Exponent + 1; if Factor mod 8 = 1 or else Factor mod 8 = 7 then if Is_Prime (Factor) and then Modular_Power (2, Exponent, Factor) = 1 then return Factor; end if; end if; end loop; return 0; end Get_Factor;   To_Test : constant Positive := 929; Factor  : Natural; begin Ada.Text_IO.Put ("2 **" & Integer'Image (To_Test) & " - 1 "); begin Factor := Get_Factor (To_Test); if Factor = 0 then Ada.Text_IO.Put_Line ("is prime."); else Ada.Text_IO.Put_Line ("has factor" & Integer'Image (Factor)); end if; exception when Not_A_Prime_Exponent => Ada.Text_IO.Put_Line ("is not a Mersenne number"); end; end Mersenne;
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
#C.2B.2B
C++
#include <iostream>   struct fraction { fraction(int n, int d) : numerator(n), denominator(d) {} int numerator; int denominator; };   std::ostream& operator<<(std::ostream& out, const fraction& f) { out << f.numerator << '/' << f.denominator; return out; }   class farey_sequence { public: explicit farey_sequence(int n) : n_(n), a_(0), b_(1), c_(1), d_(n) {} fraction next() { // See https://en.wikipedia.org/wiki/Farey_sequence#Next_term fraction result(a_, b_); int k = (n_ + b_)/d_; int next_c = k * c_ - a_; int next_d = k * d_ - b_; a_ = c_; b_ = d_; c_ = next_c; d_ = next_d; return result; } bool has_next() const { return a_ <= n_; } private: int n_, a_, b_, c_, d_; };   int main() { for (int n = 1; n <= 11; ++n) { farey_sequence seq(n); std::cout << n << ": " << seq.next(); while (seq.has_next()) std::cout << ' ' << seq.next(); std::cout << '\n'; } for (int n = 100; n <= 1000; n += 100) { int count = 0; for (farey_sequence seq(n); seq.has_next(); seq.next()) ++count; std::cout << n << ": " << count << '\n'; } return 0; }
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®)
#Factor
Factor
USING: formatting kernel math math.parser sequences ;   : nth-fairshare ( n base -- m ) [ >base string>digits sum ] [ mod ] bi ;   : <fairshare> ( n base -- seq ) [ nth-fairshare ] curry { } map-integers ;   { 2 3 5 11 } [ 25 over <fairshare> "%2d -> %u\n" printf ] each
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®)
#FreeBASIC
FreeBASIC
  Function Turn(mibase As Integer, n As Integer) As Integer Dim As Integer sum = 0 While n <> 0 Dim As Integer re = n Mod mibase n \= mibase sum += re Wend Return sum Mod mibase End Function   Sub Fairshare(mibase As Integer, count As Integer) Print Using "mibase ##:"; mibase; For i As Integer = 1 To count Dim As Integer t = Turn(mibase, i - 1) Print Using " ##"; t; Next i Print End Sub   Sub TurnCount(mibase As Integer, count As Integer) Dim As Integer cnt(mibase), i For i = 1 To mibase cnt(i - 1) = 0 Next i   For i = 1 To count Dim As Integer t = Turn(mibase, i - 1) cnt(t) += 1 Next i   Dim As Integer minTurn = 4294967295 'MaxValue of uLong Dim As Integer maxTurn = 0 'MinValue of uLong Dim As Integer portion = 0 For i As Integer = 1 To mibase Dim As Integer num = cnt(i - 1) If num > 0 Then portion += 1 If num < minTurn Then minTurn = num If num > maxTurn Then maxTurn = num Next i   Print Using " With ##### people: "; mibase; If 0 = minTurn Then Print Using "Only & have a turn"; portion Elseif minTurn = maxTurn Then Print minTurn Else Print Using "& or &"; minTurn; maxTurn End If End Sub   Fairshare(2, 25) Fairshare(3, 25) Fairshare(5, 25) Fairshare(11, 25)   Print "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) Sleep  
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)
#Go
Go
package main   import ( "fmt" "math/big" )   func bernoulli(n uint) *big.Rat { a := make([]big.Rat, n+1) z := new(big.Rat) for m := range a { a[m].SetFrac64(1, int64(m+1)) for j := m; j >= 1; j-- { d := &a[j-1] d.Mul(z.SetInt64(int64(j)), d.Sub(d, &a[j])) } } // return the 'first' Bernoulli number if n != 1 { return &a[0] } a[0].Neg(&a[0]) return &a[0] }   func binomial(n, k int) int64 { if n <= 0 || k <= 0 || n < k { return 1 } var num, den int64 = 1, 1 for i := k + 1; i <= n; i++ { num *= int64(i) } for i := 2; i <= n-k; i++ { den *= int64(i) } return num / den }   func faulhaberTriangle(p int) []big.Rat { coeffs := make([]big.Rat, p+1) q := big.NewRat(1, int64(p)+1) t := new(big.Rat) u := new(big.Rat) sign := -1 for j := range coeffs { sign *= -1 d := &coeffs[p-j] t.SetInt64(int64(sign)) u.SetInt64(binomial(p+1, j)) d.Mul(q, t) d.Mul(d, u) d.Mul(d, bernoulli(uint(j))) } return coeffs }   func main() { for i := 0; i < 10; i++ { coeffs := faulhaberTriangle(i) for _, coeff := range coeffs { fmt.Printf("%5s ", coeff.RatString()) } fmt.Println() } fmt.Println() // get coeffs for (k + 1)th row k := 17 cc := faulhaberTriangle(k) n := int64(1000) nn := big.NewRat(n, 1) np := big.NewRat(1, 1) sum := new(big.Rat) tmp := new(big.Rat) for _, c := range cc { np.Mul(np, nn) tmp.Set(np) tmp.Mul(tmp, &c) sum.Add(sum, tmp) } fmt.Println(sum.RatString()) }
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.
#Groovy
Groovy
import java.util.stream.IntStream   class FaulhabersFormula { private static long gcd(long a, long b) { if (b == 0) { return a } return gcd(b, a % b) }   private static class Frac implements Comparable<Frac> { private long num private long denom   public static final Frac ZERO = new Frac(0, 1) public static final Frac ONE = new Frac(1, 1)   Frac(long n, long d) { if (d == 0) throw new IllegalArgumentException("d must not be zero") long nn = n long dd = d if (nn == 0) { dd = 1 } else if (dd < 0) { nn = -nn dd = -dd } long g = Math.abs(gcd(nn, dd)) if (g > 1) { nn /= g dd /= g } num = nn denom = dd }   Frac plus(Frac rhs) { return new Frac(num * rhs.denom + denom * rhs.num, rhs.denom * denom) }   Frac negative() { return new Frac(-num, denom) }   Frac minus(Frac rhs) { return this + -rhs }   Frac multiply(Frac rhs) { return new Frac(this.num * rhs.num, this.denom * rhs.denom) }   @Override int compareTo(Frac o) { double diff = toDouble() - o.toDouble() return Double.compare(diff, 0.0) }   @Override boolean equals(Object obj) { return null != obj && obj instanceof Frac && this == (Frac) obj }   @Override String toString() { if (denom == 1) { return Long.toString(num) } return String.format("%d/%d", num, denom) }   private double toDouble() { return (double) num / denom } }   private static Frac bernoulli(int n) { if (n < 0) throw new IllegalArgumentException("n may not be negative or zero") Frac[] a = new Frac[n + 1] Arrays.fill(a, Frac.ZERO) for (int m = 0; m <= n; ++m) { a[m] = new Frac(1, m + 1) for (int j = m; j >= 1; --j) { a[j - 1] = (a[j - 1] - a[j]) * new Frac(j, 1) } } // returns 'first' Bernoulli number if (n != 1) return a[0] return -a[0] }   private static int binomial(int n, int k) { if (n < 0 || k < 0 || n < k) throw new IllegalArgumentException() if (n == 0 || k == 0) return 1 int num = IntStream.rangeClosed(k + 1, n).reduce(1, { a, b -> a * b }) int den = IntStream.rangeClosed(2, n - k).reduce(1, { acc, i -> acc * i }) return num / den }   private static void faulhaber(int p) { print("$p : ") Frac q = new Frac(1, p + 1) int sign = -1 for (int j = 0; j <= p; ++j) { sign *= -1 Frac coeff = q * new Frac(sign, 1) * new Frac(binomial(p + 1, j), 1) * bernoulli(j) if (Frac.ZERO == coeff) continue if (j == 0) { if (Frac.ONE != coeff) { if (-Frac.ONE == coeff) { print("-") } else { print(coeff) } } } else { if (Frac.ONE == coeff) { print(" + ") } else if (-Frac.ONE == coeff) { print(" - ") } else if (coeff > Frac.ZERO) { print(" + $coeff") } else { print(" - ${-coeff}") } } int pwr = p + 1 - j if (pwr > 1) { print("n^$pwr") } else { print("n") } } println() }   static void main(String[] args) { for (int i = 0; i <= 9; ++i) { faulhaber(i) } } }
http://rosettacode.org/wiki/Fermat_numbers
Fermat numbers
In mathematics, a Fermat number, named after Pierre de Fermat who first studied them, is a positive integer of the form Fn = 22n + 1 where n is a non-negative integer. Despite the simplicity of generating Fermat numbers, they have some powerful mathematical properties and are extensively used in cryptography & pseudo-random number generation, and are often linked to other number theoric fields. As of this writing, (mid 2019), there are only five known prime Fermat numbers, the first five (F0 through F4). Only the first twelve Fermat numbers have been completely factored, though many have been partially factored. Task Write a routine (function, procedure, whatever) to generate Fermat numbers. Use the routine to find and display here, on this page, the first 10 Fermat numbers - F0 through F9. Find and display here, on this page, the prime factors of as many Fermat numbers as you have patience for. (Or as many as can be found in five minutes or less of processing time). Note: if you make it past F11, there may be money, and certainly will be acclaim in it for you. See also Wikipedia - Fermat numbers OEIS:A000215 - Fermat numbers OEIS:A019434 - Fermat primes
#Rust
Rust
struct DivisorGen { curr: u64, last: u64, }   impl Iterator for DivisorGen { type Item = u64;   fn next(&mut self) -> Option<u64> { self.curr += 2u64;   if self.curr < self.last{ None } else { Some(self.curr) } } }   fn divisor_gen(num : u64) -> DivisorGen { DivisorGen { curr: 0u64, last: (num / 2u64) + 1u64 } }   fn is_prime(num : u64) -> bool{ if num == 2 || num == 3 { return true; } else if num % 2 == 0 || num % 3 == 0 || num <= 1{ return false; }else{ for i in divisor_gen(num){ if num % i == 0{ return false; } } } return true; }     fn main() { let fermat_closure = |i : u32| -> u64 {2u64.pow(2u32.pow(i + 1u32))}; let mut f_numbers : Vec<u64> = Vec::new();   println!("First 4 Fermat numbers:"); for i in 0..4 { let f = fermat_closure(i) + 1u64; f_numbers.push(f); println!("F{}: {}", i, f); }   println!("Factor of the first four numbers:"); for f in f_numbers.iter(){ let is_prime : bool = f % 4 == 1 && is_prime(*f); let not_or_not = if is_prime {" "} else {" not "}; println!("{} is{}prime", f, not_or_not); } }
http://rosettacode.org/wiki/Fermat_numbers
Fermat numbers
In mathematics, a Fermat number, named after Pierre de Fermat who first studied them, is a positive integer of the form Fn = 22n + 1 where n is a non-negative integer. Despite the simplicity of generating Fermat numbers, they have some powerful mathematical properties and are extensively used in cryptography & pseudo-random number generation, and are often linked to other number theoric fields. As of this writing, (mid 2019), there are only five known prime Fermat numbers, the first five (F0 through F4). Only the first twelve Fermat numbers have been completely factored, though many have been partially factored. Task Write a routine (function, procedure, whatever) to generate Fermat numbers. Use the routine to find and display here, on this page, the first 10 Fermat numbers - F0 through F9. Find and display here, on this page, the prime factors of as many Fermat numbers as you have patience for. (Or as many as can be found in five minutes or less of processing time). Note: if you make it past F11, there may be money, and certainly will be acclaim in it for you. See also Wikipedia - Fermat numbers OEIS:A000215 - Fermat numbers OEIS:A019434 - Fermat primes
#Scala
Scala
import scala.collection.mutable import scala.collection.mutable.ListBuffer   object FermatNumbers { def main(args: Array[String]): Unit = { println("First 10 Fermat numbers:") for (i <- 0 to 9) { println(f"F[$i] = ${fermat(i)}") } println() println("First 12 Fermat numbers factored:") for (i <- 0 to 12) { println(f"F[$i] = ${getString(getFactors(i, fermat(i)))}") } }   private val TWO = BigInt(2)   def fermat(n: Int): BigInt = { TWO.pow(math.pow(2.0, n).intValue()) + 1 }   def getString(factors: List[BigInt]): String = { if (factors.size == 1) { return s"${factors.head} (PRIME)" }   factors.map(a => a.toString) .map(a => if (a.startsWith("-")) "(C" + a.replace("-", "") + ")" else a) .reduce((a, b) => a + " * " + b) }   val COMPOSITE: mutable.Map[Int, String] = scala.collection.mutable.Map( 9 -> "5529", 10 -> "6078", 11 -> "1037", 12 -> "5488", 13 -> "2884" )   def getFactors(fermatIndex: Int, n: BigInt): List[BigInt] = { var n2 = n var factors = new ListBuffer[BigInt] var loop = true while (loop) { if (n2.isProbablePrime(100)) { factors += n2 loop = false } else { if (COMPOSITE.contains(fermatIndex)) { val stop = COMPOSITE(fermatIndex) if (n2.toString.startsWith(stop)) { factors += -n2.toString().length loop = false } } if (loop) { val factor = pollardRhoFast(n2) if (factor == 0) { factors += n2 loop = false } else { factors += factor n2 = n2 / factor } } } }   factors.toList }   def pollardRhoFast(n: BigInt): BigInt = { var x = BigInt(2) var y = BigInt(2) var z = BigInt(1) var d = BigInt(1) var count = 0   var loop = true while (loop) { x = pollardRhoG(x, n) y = pollardRhoG(pollardRhoG(y, n), n) d = (x - y).abs z = (z * d) % n count += 1 if (count == 100) { d = z.gcd(n) if (d != 1) { loop = false } else { z = BigInt(1) count = 0 } } }   println(s" Pollard rho try factor $n") if (d == n) { return 0 } d }   def pollardRhoG(x: BigInt, n: BigInt): BigInt = ((x * x) + 1) % 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
#Bracmat
Bracmat
( ( nacci = Init Cnt N made tail . ( plus = n .  !arg:#%?n ?arg&!n+plus$!arg | 0 ) & !arg:(?Init.?Cnt) & !Init:? [?N & !Init:?made & !Cnt+-1*!N:?times & -1+-1*!N:?M & whl ' ( !times+-1:~<0:?times & !made:? [!M ?tail & !made plus$!tail:?made ) & !made ) & ( pad = len w . @(!arg:? [?len) & @(" ":? [!len ?w) & !w !arg ) & (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) (lucas.2 1)  : ?L & whl ' ( !L:(?name.?Init) ?L & out$(str$(pad$!name ": ") nacci$(!Init.12)) ) );
http://rosettacode.org/wiki/Feigenbaum_constant_calculation
Feigenbaum constant calculation
Task Calculate the Feigenbaum constant. See   Details in the Wikipedia article:   Feigenbaum constant.
#Sidef
Sidef
var a1 = 1 var a2 = 0 var δ = 3.2.float   say " i\tδ"   for i in (2..15) { var a0 = ((a1 - a2)/δ + a1) 10.times { var (x, y) = (0, 0) 2**i -> times { y = (1 - 2*x*y) x = (a0 - x²) } a0 -= x/y } δ = ((a1 - a2) / (a0 - a1)) (a2, a1) = (a1, a0) printf("%2d %.8f\n", i, δ) }
http://rosettacode.org/wiki/Feigenbaum_constant_calculation
Feigenbaum constant calculation
Task Calculate the Feigenbaum constant. See   Details in the Wikipedia article:   Feigenbaum constant.
#Swift
Swift
import Foundation   func feigenbaum(iterations: Int = 13) { var a = 0.0 var a1 = 1.0 var a2 = 0.0 var d = 0.0 var d1 = 3.2   print(" i d")   for i in 2...iterations { a = a1 + (a1 - a2) / d1   for _ in 1...10 { var x = 0.0 var y = 0.0   for _ in 1...1<<i { y = 1.0 - 2.0 * y * x x = a - x * x }   a -= x / y }   d = (a1 - a2) / (a - a1) d1 = d (a1, a2) = (a, a1)   print(String(format: "%2d  %.8f", i, d)) } }   feigenbaum()
http://rosettacode.org/wiki/Feigenbaum_constant_calculation
Feigenbaum constant calculation
Task Calculate the Feigenbaum constant. See   Details in the Wikipedia article:   Feigenbaum constant.
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Sub Main() Dim maxIt = 13 Dim maxItJ = 10 Dim a1 = 1.0 Dim a2 = 0.0 Dim d1 = 3.2 Console.WriteLine(" i d") For i = 2 To maxIt Dim a = a1 + (a1 - a2) / d1 For j = 1 To maxItJ Dim x = 0.0 Dim y = 0.0 For k = 1 To 1 << i y = 1.0 - 2.0 * y * x x = a - x * x Next a -= x / y Next Dim d = (a1 - a2) / (a - a1) Console.WriteLine("{0,2:d} {1:f8}", i, d) d1 = d a2 = a1 a1 = a Next End Sub   End Module
http://rosettacode.org/wiki/File_extension_is_in_extensions_list
File extension is in extensions list
File extension is in extensions list You are encouraged to solve this task according to the task description, using any language you may know. Filename extensions are a rudimentary but commonly used way of identifying files types. Task Given an arbitrary filename and a list of extensions, tell whether the filename has one of those extensions. Notes: The check should be case insensitive. The extension must occur at the very end of the filename, and be immediately preceded by a dot (.). You may assume that none of the given extensions are the empty string, and none of them contain a dot. Other than that they may be arbitrary strings. Extra credit: Allow extensions to contain dots. This way, users of your function/program have full control over what they consider as the extension in cases like: archive.tar.gz Please state clearly whether or not your solution does this. Test cases The following test cases all assume this list of extensions:   zip, rar, 7z, gz, archive, A## Filename Result MyData.a## true MyData.tar.Gz true MyData.gzip false MyData.7z.backup false MyData... false MyData false If your solution does the extra credit requirement, add tar.bz2 to the list of extensions, and check the following additional test cases: Filename Result MyData_v1.0.tar.bz2 true MyData_v1.0.bz2 false Motivation Checking if a file is in a certain category of file formats with known extensions (e.g. archive files, or image files) is a common problem in practice, and may be approached differently from extracting and outputting an arbitrary extension (see e.g. FileNameExtensionFilter in Java). It also requires less assumptions about the format of an extension, because the calling code can decide what extensions are valid. For these reasons, this task exists in addition to the Extract file extension task. Related tasks Extract file extension String matching
#zkl
zkl
fcn hasExtension(fnm){ var [const] extensions=T(".zip",".rar",".7z",".gz",".archive",".a##"); nm,ext:=File.splitFileName(fnm)[-2,*].apply("toLower"); if(extensions.holds(ext)) True; else if(ext==".bz2" and ".tar"==File.splitFileName(nm)[-1]) True; else False } nms:=T("MyData.a##","MyData.tar.Gz","MyData.gzip","MyData.7z.backup", "MyData...","MyData", "MyData_v1.0.tAr.bz2","MyData_v1.0.bz2"); foreach nm in (nms){ println("%20s : %s".fmt(nm,hasExtension(nm))); }
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#Rust
Rust
use std::fs;   fn main() -> std::io::Result<()> { let metadata = fs::metadata("foo.txt")?;   if let Ok(time) = metadata.accessed() { println!("{:?}", time); } else { println!("Not supported on this platform"); } Ok(()) }  
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#Scala
Scala
import java.io.File import java.util.Date   object FileModificationTime extends App { def test(file: File) { val (t, init) = (file.lastModified(), s"The following ${if (file.isDirectory()) "directory" else "file"} called ${file.getPath()}")   println(init + (if (t == 0) " does not exist." else " was modified at " + new Date(t).toInstant())) println(init + (if (file.setLastModified(System.currentTimeMillis())) " was modified to current time." else " does not exist.")) println(init + (if (file.setLastModified(t)) " was reset to previous time." else " does not exist.")) }   // main List(new File("output.txt"), new File("docs")).foreach(test) }
http://rosettacode.org/wiki/Fibonacci_word/fractal
Fibonacci word/fractal
The Fibonacci word may be represented as a fractal as described here: (Clicking on the above website   (hal.archives-ouvertes.fr)   will leave a cookie.) For F_wordm start with F_wordCharn=1 Draw a segment forward If current F_wordChar is 0 Turn left if n is even Turn right if n is odd next n and iterate until end of F_word Task Create and display a fractal similar to Fig 1. (Clicking on the above website   (hal.archives-ouvertes.fr)   will leave a cookie.)
#Scala
Scala
  def fibIt = Iterator.iterate(("1","0")){case (f1,f2) => (f2,f1+f2)}.map(_._1)   def turnLeft(c: Char): Char = c match { case 'R' => 'U' case 'U' => 'L' case 'L' => 'D' case 'D' => 'R' }   def turnRight(c: Char): Char = c match { case 'R' => 'D' case 'D' => 'L' case 'L' => 'U' case 'U' => 'R' }   def directions(xss: List[(Char,Char)], current: Char = 'R'): List[Char] = xss match { case Nil => current :: Nil case x :: xs => x._1 match { case '1' => current :: directions(xs, current) case '0' => x._2 match { case 'E' => current :: directions(xs, turnLeft(current)) case 'O' => current :: directions(xs, turnRight(current)) } } }   def buildIt(xss: List[Char], old: Char = 'X', count: Int = 1): List[String] = xss match { case Nil => s"$old$count" :: Nil case x :: xs if x == old => buildIt(xs,old,count+1) case x :: xs => s"$old$count" :: buildIt(xs,x) }   def convertToLine(s: String, c: Int): String = (s.head, s.tail) match { case ('R',n) => s"l ${c * n.toInt} 0" case ('U',n) => s"l 0 ${-c * n.toInt}" case ('L',n) => s"l ${-c * n.toInt} 0" case ('D',n) => s"l 0 ${c * n.toInt}" }   def drawSVG(xStart: Int, yStart: Int, width: Int, height: Int, fibWord: String, lineMultiplier: Int, color: String): String = { val xs = fibWord.zipWithIndex.map{case (c,i) => (c, if(c == '1') '_' else i % 2 match{case 0 => 'E'; case 1 => 'O'})}.toList val fractalPath = buildIt(directions(xs)).tail.map(convertToLine(_,lineMultiplier)) s"""<?xml version="1.0" encoding="utf-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="${width}px" height="${height}px" viewBox="0 0 $width $height"><path d="M $xStart $yStart ${fractalPath.mkString(" ")}" style="stroke:#$color;stroke-width:1" stroke-linejoin="miter" fill="none"/></svg>""" }   drawSVG(0,25,550,530,fibIt.drop(18).next,3,"000")  
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
#PARI.2FGP
PARI/GP
cdp(v)={ my(s=""); v=apply(t->Vec(t),v); for(i=1,vecmin(apply(length,v)), for(j=2,#v, if(v[j][i]!=v[1][i],return(s))); if(i>1&v[1][i]=="/",s=concat(vecextract(v[1],1<<(i-1)-1)) ) ); if(vecmax(apply(length,v))==vecmin(apply(length,v)),concat(v[1]),s) }; cdp(["/home/user1/tmp/coverage/test","/home/user1/tmp/covert/operator","/home/user1/tmp/coven/members"])
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.
#Delphi
Delphi
program FilterEven;   {$APPTYPE CONSOLE}   uses SysUtils, Types;   const SOURCE_ARRAY: array[0..9] of Integer = (0,1,2,3,4,5,6,7,8,9); var i: Integer; lEvenArray: TIntegerDynArray; begin for i in SOURCE_ARRAY do begin if not Odd(i) then begin SetLength(lEvenArray, Length(lEvenArray) + 1); lEvenArray[Length(lEvenArray) - 1] := i; end; end;   for i in lEvenArray do Write(i:3); Writeln; end.
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.
#Raku
Raku
my $x = 0; recurse;   sub recurse () { ++$x; say $x if $x %% 1_000_000; recurse; }
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.
#Retro
Retro
: try -6 5 out wait 5 in putn cr try ;
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
#Gosu
Gosu
for (i in 1..100) {   if (i % 3 == 0 && i % 5 == 0) { print("FizzBuzz") continue }   if (i % 3 == 0) { print("Fizz") continue }   if (i % 5 == 0) { print("Buzz") continue }   // default print(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.
#Objective-C
Objective-C
NSFileManager *fm = [NSFileManager defaultManager];   // Pre-OS X 10.5 NSLog(@"%llu", [[fm fileAttributesAtPath:@"input.txt" traverseLink:YES] fileSize]);   // OS X 10.5+ NSLog(@"%llu", [[fm attributesOfItemAtPath:@"input.txt" error:NULL] fileSize]);
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.
#OCaml
OCaml
let printFileSize filename = let ic = open_in filename in Printf.printf "%d\n" (in_channel_length ic); close_in ic ;;   printFileSize "input.txt" ;; printFileSize "/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.
#Gambas
Gambas
Public Sub Main() Dim sOutput As String = "Hello " Dim sInput As String = File.Load(User.Home &/ "input.txt") 'Has the word 'World!' stored   File.Save(User.Home &/ "output.txt", sOutput) File.Save(User.Home &/ "input.txt", sOutput & sInput)   Print "'input.txt' contains - " & sOutput & sInput Print "'output.txt' contains - " & sOutput   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.
#GAP
GAP
CopyFile := function(src, dst) local f, g, line; f := InputTextFile(src); g := OutputTextFile(dst, false); while true do line := ReadLine(f); if line = fail then break else WriteLine(g, Chomp(line)); fi; od; CloseStream(f); CloseStream(g); 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
#J
J
F_Words=: (,<@;@:{~&_1 _2)@]^:(2-~[)&('1';'0')
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
#Java
Java
import java.util.*;   public class FWord { private /*v*/ String fWord0 = ""; private /*v*/ String fWord1 = "";   private String nextFWord () { final String result;   if ( "".equals ( fWord1 ) ) result = "1"; else if ( "".equals ( fWord0 ) ) result = "0"; else result = fWord1 + fWord0;   fWord0 = fWord1; fWord1 = result;   return result; }   public static double entropy ( final String source ) { final int length = source.length (); final Map < Character, Integer > counts = new HashMap < Character, Integer > (); /*v*/ double result = 0.0;   for ( int i = 0; i < length; i++ ) { final char c = source.charAt ( i );   if ( counts.containsKey ( c ) ) counts.put ( c, counts.get ( c ) + 1 ); else counts.put ( c, 1 ); }   for ( final int count : counts.values () ) { final double proportion = ( double ) count / length;   result -= proportion * ( Math.log ( proportion ) / Math.log ( 2 ) ); }   return result; }   public static void main ( final String [] args ) { final FWord fWord = new FWord ();   for ( int i = 0; i < 37; ) { final String word = fWord.nextFWord ();   System.out.printf ( "%3d %10d %s %n", ++i, word.length (), entropy ( 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.
#jq
jq
  def fasta: foreach (inputs, ">") as $line # state: [accumulator, print ] ( [null, null]; if $line[0:1] == ">" then [($line[1:] + ": "), .[0]] else [ (.[0] + $line), false] end; if .[1] then .[1] else empty end )  ;   fasta
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.
#Julia
Julia
for line in eachline("data/fasta.txt") if startswith(line, '>') print(STDOUT, "\n$(line[2:end]): ") else print(STDOUT, "$line") 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.
#Kotlin
Kotlin
// version 1.1.2   import java.util.Scanner import java.io.File   fun checkNoSpaces(s: String) = ' ' !in s && '\t' !in s   fun main(args: Array<String>) { var first = true val sc = Scanner(File("input.fasta")) while (sc.hasNextLine()) { val line = sc.nextLine() if (line[0] == '>') { if (!first) println() print("${line.substring(1)}: ") if (first) first = false } else if (first) { println("Error : File does not begin with '>'") break } else if (checkNoSpaces(line)) print(line) else { println("\nError : Sequence contains space(s)") break } } sc.close() }
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
#11l
11l
F factor(n) V factors = Set[Int]() L(x) 1..Int(sqrt(n)) I n % x == 0 factors.add(x) factors.add(n I/ x) R sorted(Array(factors))   L(i) (45, 53, 64) print(i‘: factors: ’String(factor(i)))
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.
#BBC_BASIC
BBC BASIC
@% = &60A   DIM Complex{r#, i#} DIM in{(7)} = Complex{}, out{(7)} = Complex{} DATA 1, 1, 1, 1, 0, 0, 0, 0   PRINT "Input (real, imag):" FOR I% = 0 TO 7 READ in{(I%)}.r# PRINT in{(I%)}.r# "," in{(I%)}.i# NEXT   PROCfft(out{()}, in{()}, 0, 1, DIM(in{()},1)+1)   PRINT "Output (real, imag):" FOR I% = 0 TO 7 PRINT out{(I%)}.r# "," out{(I%)}.i# NEXT END   DEF PROCfft(b{()}, o{()}, B%, S%, N%) LOCAL I%, t{} : DIM t{} = Complex{} IF S% < N% THEN PROCfft(o{()}, b{()}, B%, S%*2, N%) PROCfft(o{()}, b{()}, B%+S%, S%*2, N%) FOR I% = 0 TO N%-1 STEP 2*S% t.r# = COS(-PI*I%/N%) t.i# = SIN(-PI*I%/N%) PROCcmul(t{}, o{(B%+I%+S%)}) b{(B%+I% DIV 2)}.r# = o{(B%+I%)}.r# + t.r# b{(B%+I% DIV 2)}.i# = o{(B%+I%)}.i# + t.i# b{(B%+(I%+N%) DIV 2)}.r# = o{(B%+I%)}.r# - t.r# b{(B%+(I%+N%) DIV 2)}.i# = o{(B%+I%)}.i# - t.i# NEXT ENDIF ENDPROC   DEF PROCcmul(c{},d{}) LOCAL r#, i# r# = c.r#*d.r# - c.i#*d.i# i# = c.r#*d.i# + c.i#*d.r# c.r# = r# c.i# = i# ENDPROC  
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.)
#ALGOL_68
ALGOL 68
MODE ISPRIMEINT = INT; PR READ "prelude/is_prime.a68" PR;   MODE POWMODSTRUCT = INT; PR READ "prelude/pow_mod.a68" PR;   PROC m factor = (INT p)INT:BEGIN INT m factor; INT max k, msb, n, q;   FOR i FROM bits width - 2 BY -1 TO 0 WHILE ( BIN p SHR i AND 2r1 ) = 2r0 DO msb := i OD;   max k := ENTIER sqrt(max int) OVER p; # limit for k to prevent overflow of max int # FOR k FROM 1 TO max k DO q := 2*p*k + 1; IF NOT is prime(q) THEN SKIP ELIF q MOD 8 /= 1 AND q MOD 8 /= 7 THEN SKIP ELSE n := pow mod(2,p,q); IF n = 1 THEN m factor := q; return FI FI OD; m factor := 0; return: m factor END;   BEGIN   INT exponent, factor; print("Enter exponent of Mersenne number:"); read(exponent); IF NOT is prime(exponent) THEN print(("Exponent is not prime: ", exponent, new line)) ELSE factor := m factor(exponent); IF factor = 0 THEN print(("No factor found for M", exponent, new line)) ELSE print(("M", exponent, " has a factor: ", factor, new line)) FI FI   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
#Common_Lisp
Common Lisp
(defun farey (n) (labels ((helper (begin end) (let ((med (/ (+ (numerator begin) (numerator end)) (+ (denominator begin) (denominator end))))) (if (<= (denominator med) n) (append (helper begin med) (list med) (helper med end)))))) (append (list 0) (helper 0 1) (list 1))))     ;; Force printing of integers in X/1 format (defun print-ratio (stream object &optional colonp at-sign-p) (format stream "~d/~d" (numerator object) (denominator object)))   (loop for i from 1 to 11 do (format t "~a: ~{~/print-ratio/ ~}~%" i (farey i)))   (loop for i from 100 to 1001 by 100 do (format t "Farey sequence of order ~a has ~a terms.~%" i (length (farey i))))  
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®)
#Go
Go
package main   import ( "fmt" "sort" "strconv" "strings" )   func fairshare(n, base int) []int { res := make([]int, n) for i := 0; i < n; i++ { j := i sum := 0 for j > 0 { sum += j % base j /= base } res[i] = sum % base } return res }   func turns(n int, fss []int) string { m := make(map[int]int) for _, fs := range fss { m[fs]++ } m2 := make(map[int]int) for _, v := range m { m2[v]++ } res := []int{} sum := 0 for k, v := range m2 { sum += v res = append(res, k) } if sum != n { return fmt.Sprintf("only %d have a turn", sum) } sort.Ints(res) res2 := make([]string, len(res)) for i := range res { res2[i] = strconv.Itoa(res[i]) } return strings.Join(res2, " or ") }   func main() { for _, base := range []int{2, 3, 5, 11} { fmt.Printf("%2d : %2d\n", base, fairshare(25, base)) } fmt.Println("\nHow many times does each get a turn in 50000 iterations?") for _, base := range []int{191, 1377, 49999, 50000, 50001} { t := turns(base, fairshare(50000, base)) fmt.Printf(" With %d people: %s\n", base, t) } }
http://rosettacode.org/wiki/Faulhaber%27s_triangle
Faulhaber's triangle
Named after Johann Faulhaber, the rows of Faulhaber's triangle are the coefficients of polynomials that represent sums of integer powers, which are extracted from Faulhaber's formula: ∑ k = 1 n k p = 1 p + 1 ∑ j = 0 p ( p + 1 j ) B j n p + 1 − j {\displaystyle \sum _{k=1}^{n}k^{p}={1 \over p+1}\sum _{j=0}^{p}{p+1 \choose j}B_{j}n^{p+1-j}} where B n {\displaystyle B_{n}} is the nth-Bernoulli number. The first 5 rows of Faulhaber's triangle, are: 1 1/2 1/2 1/6 1/2 1/3 0 1/4 1/2 1/4 -1/30 0 1/3 1/2 1/5 Using the third row of the triangle, we have: ∑ k = 1 n k 2 = 1 6 n + 1 2 n 2 + 1 3 n 3 {\displaystyle \sum _{k=1}^{n}k^{2}={1 \over 6}n+{1 \over 2}n^{2}+{1 \over 3}n^{3}} Task show the first 10 rows of Faulhaber's triangle. using the 18th row of Faulhaber's triangle, compute the sum: ∑ k = 1 1000 k 17 {\displaystyle \sum _{k=1}^{1000}k^{17}} (extra credit). See also Bernoulli numbers Evaluate binomial coefficients Faulhaber's formula (Wikipedia) Faulhaber's triangle (PDF)
#Groovy
Groovy
import java.math.MathContext import java.util.stream.LongStream   class FaulhabersTriangle { private static final MathContext MC = new MathContext(256)   private static long gcd(long a, long b) { if (b == 0) { return a } return gcd(b, a % b) }   private static class Frac implements Comparable<Frac> { private long num private long denom   public static final Frac ZERO = new Frac(0, 1)   Frac(long n, long d) { if (d == 0) throw new IllegalArgumentException("d must not be zero") long nn = n long dd = d if (nn == 0) { dd = 1 } else if (dd < 0) { nn = -nn dd = -dd } long g = Math.abs(gcd(nn, dd)) if (g > 1) { nn /= g dd /= g } num = nn denom = dd }   Frac plus(Frac rhs) { return new Frac(num * rhs.denom + denom * rhs.num, rhs.denom * denom) }   Frac negative() { return new Frac(-num, denom) }   Frac minus(Frac rhs) { return this + -rhs }   Frac multiply(Frac rhs) { return new Frac(this.num * rhs.num, this.denom * rhs.denom) }   @Override int compareTo(Frac o) { double diff = toDouble() - o.toDouble() return Double.compare(diff, 0.0) }   @Override boolean equals(Object obj) { return null != obj && obj instanceof Frac && this == (Frac) obj }   @Override String toString() { if (denom == 1) { return Long.toString(num) } return String.format("%d/%d", num, denom) }   double toDouble() { return (double) num / denom }   BigDecimal toBigDecimal() { return BigDecimal.valueOf(num).divide(BigDecimal.valueOf(denom), MC) } }   private static Frac bernoulli(int n) { if (n < 0) throw new IllegalArgumentException("n may not be negative or zero") Frac[] a = new Frac[n + 1] Arrays.fill(a, Frac.ZERO) for (int m = 0; m <= n; ++m) { a[m] = new Frac(1, m + 1) for (int j = m; j >= 1; --j) { a[j - 1] = (a[j - 1] - a[j]) * new Frac(j, 1) } } // returns 'first' Bernoulli number if (n != 1) return a[0] return -a[0] }   private static long binomial(int n, int k) { if (n < 0 || k < 0 || n < k) throw new IllegalArgumentException() if (n == 0 || k == 0) return 1 long num = LongStream.rangeClosed(k + 1, n).reduce(1, { a, b -> a * b }) long den = LongStream.rangeClosed(2, n - k).reduce(1, { acc, i -> acc * i }) return num / den }   private static Frac[] faulhaberTriangle(int p) { Frac[] coeffs = new Frac[p + 1] Arrays.fill(coeffs, Frac.ZERO) Frac q = new Frac(1, p + 1) int sign = -1 for (int j = 0; j <= p; ++j) { sign *= -1 coeffs[p - j] = q * new Frac(sign, 1) * new Frac(binomial(p + 1, j), 1) * bernoulli(j) } return coeffs }   static void main(String[] args) { for (int i = 0; i <= 9; ++i) { Frac[] coeffs = faulhaberTriangle(i) for (Frac coeff : coeffs) { printf("%5s ", coeff) } println() } println() // get coeffs for (k + 1)th row int k = 17 Frac[] cc = faulhaberTriangle(k) int n = 1000 BigDecimal nn = BigDecimal.valueOf(n) BigDecimal np = BigDecimal.ONE BigDecimal sum = BigDecimal.ZERO for (Frac c : cc) { np = np * nn sum = sum.add(np * c.toBigDecimal()) } println(sum.toBigInteger()) } }
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.
#Haskell
Haskell
import Data.Ratio ((%), numerator, denominator) import Data.List (intercalate, transpose) import Data.Bifunctor (bimap) import Data.Char (isSpace) import Data.Monoid ((<>)) import Data.Bool (bool)   ------------------------- FAULHABER ------------------------ faulhaber :: [[Rational]] faulhaber = tail $ scanl (\rs n -> let xs = zipWith ((*) . (n %)) [2 ..] rs in 1 - sum xs : xs) [] [0 ..]   polynomials :: [[(String, String)]] polynomials = fmap ((ratioPower =<<) . reverse . flip zip [1 ..]) faulhaber     ---------------------------- TEST -------------------------- main :: IO () main = (putStrLn . unlines . expressionTable . take 10) polynomials     --------------------- EXPRESSION STRINGS -------------------   -- Rows of (Power string, Ratio string) tuples -> Printable lines expressionTable :: [[(String, String)]] -> [String] expressionTable ps = let cols = transpose (fullTable ps) in expressionRow <$> zip [0 ..] (transpose $ zipWith (\(lw, rw) col -> fmap (bimap (justifyLeft lw ' ') (justifyLeft rw ' ')) col) (colWidths cols) cols)   -- Value pair -> String pair (lifted into list for use with >>=) ratioPower :: (Rational, Integer) -> [(String, String)] ratioPower (nd, j) = let (num, den) = ((,) . numerator <*> denominator) nd sn | num == 0 = [] | (j /= 1) = ("n^" <> show j) | otherwise = "n" sr | num == 0 = [] | den == 1 && num == 1 = [] | den == 1 = show num <> "n" | otherwise = intercalate "/" [show num, show den] s = sr <> sn in bool [(sn, sr)] [] (null s)   -- Rows of uneven length -> All rows padded to length of longest fullTable :: [[(String, String)]] -> [[(String, String)]] fullTable xs = let lng = maximum $ length <$> xs in (<>) <*> (flip replicate ([], []) . (-) lng . length) <$> xs   justifyLeft :: Int -> Char -> String -> String justifyLeft n c s = take n (s <> replicate n c)   -- (Row index, Expression pairs) -> String joined by conjunctions expressionRow :: (Int, [(String, String)]) -> String expressionRow (i, row) = concat [ show i , " -> " , foldr (\s a -> concat [s, bool " + " " " (blank a || head a == '-'), a]) [] (polyTerm <$> row) ]   -- (Power string, Ratio String) -> Combined string with possible '*' polyTerm :: (String, String) -> String polyTerm (l, r) | blank l || blank r = l <> r | head r == '-' = concat ["- ", l, " * ", tail r] | otherwise = intercalate " * " [l, r]   blank :: String -> Bool blank = all isSpace   -- Maximum widths of power and ratio elements in each column colWidths :: [[(String, String)]] -> [(Int, Int)] colWidths = fmap (foldr (\(ls, rs) (lMax, rMax) -> (max (length ls) lMax, max (length rs) rMax)) (0, 0))   -- Length of string excluding any leading '-' unsignedLength :: String -> Int unsignedLength xs = let l = length xs in bool (bool l (l - 1) ('-' == head xs)) 0 (0 == l)
http://rosettacode.org/wiki/Fermat_numbers
Fermat numbers
In mathematics, a Fermat number, named after Pierre de Fermat who first studied them, is a positive integer of the form Fn = 22n + 1 where n is a non-negative integer. Despite the simplicity of generating Fermat numbers, they have some powerful mathematical properties and are extensively used in cryptography & pseudo-random number generation, and are often linked to other number theoric fields. As of this writing, (mid 2019), there are only five known prime Fermat numbers, the first five (F0 through F4). Only the first twelve Fermat numbers have been completely factored, though many have been partially factored. Task Write a routine (function, procedure, whatever) to generate Fermat numbers. Use the routine to find and display here, on this page, the first 10 Fermat numbers - F0 through F9. Find and display here, on this page, the prime factors of as many Fermat numbers as you have patience for. (Or as many as can be found in five minutes or less of processing time). Note: if you make it past F11, there may be money, and certainly will be acclaim in it for you. See also Wikipedia - Fermat numbers OEIS:A000215 - Fermat numbers OEIS:A019434 - Fermat primes
#Sidef
Sidef
func fermat_number(n) { 2**(2**n) + 1 }   func fermat_one_factor(n) { fermat_number(n).ecm_factor }   for n in (0..9) { say "F_#{n} = #{fermat_number(n)}" }   say ''   for n in (0..13) { var f = fermat_one_factor(n) say ("F_#{n} = ", join(' * ', f.shift, f.map { <C P>[.is_prime] + .len }...)) }
http://rosettacode.org/wiki/Fermat_numbers
Fermat numbers
In mathematics, a Fermat number, named after Pierre de Fermat who first studied them, is a positive integer of the form Fn = 22n + 1 where n is a non-negative integer. Despite the simplicity of generating Fermat numbers, they have some powerful mathematical properties and are extensively used in cryptography & pseudo-random number generation, and are often linked to other number theoric fields. As of this writing, (mid 2019), there are only five known prime Fermat numbers, the first five (F0 through F4). Only the first twelve Fermat numbers have been completely factored, though many have been partially factored. Task Write a routine (function, procedure, whatever) to generate Fermat numbers. Use the routine to find and display here, on this page, the first 10 Fermat numbers - F0 through F9. Find and display here, on this page, the prime factors of as many Fermat numbers as you have patience for. (Or as many as can be found in five minutes or less of processing time). Note: if you make it past F11, there may be money, and certainly will be acclaim in it for you. See also Wikipedia - Fermat numbers OEIS:A000215 - Fermat numbers OEIS:A019434 - Fermat primes
#Tcl
Tcl
namespace import ::tcl::mathop::* package require math::numtheory 1.1.1; # Buggy before tcllib-1.20   proc fermat n { + [** 2 [** 2 $n]] 1 }     for {set i 0} {$i < 10} {incr i} { puts "F$i = [fermat $i]" }   for {set i 1} {1} {incr i} { puts -nonewline "F$i... " flush stdout set F [fermat $i] set factors [math::numtheory::primeFactors $F] if {[llength $factors] == 1} { puts "is prime" } else { puts "factors: $factors" } }
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
#BQN
BQN
NStep ← ⊑(1↓⊢∾+´)∘⊢⍟⊣ Nacci ← (2⋆0∾↕)∘(⊢-1˙)   >((↕10) NStep¨ <)¨ (Nacci¨ 2‿3‿4) ∾ <2‿1
http://rosettacode.org/wiki/Feigenbaum_constant_calculation
Feigenbaum constant calculation
Task Calculate the Feigenbaum constant. See   Details in the Wikipedia article:   Feigenbaum constant.
#Vlang
Vlang
fn feigenbaum() { max_it, max_itj := 13, 10 mut a1, mut a2, mut d1 := 1.0, 0.0, 3.2 println(" i d") for i := 2; i <= max_it; i++ { mut a := a1 + (a1-a2)/d1 for j := 1; j <= max_itj; j++ { mut x, mut y := 0.0, 0.0 for k := 1; k <= 1<<u32(i); k++ { y = 1.0 - 2.0*y*x x = a - x*x } a -= x / y } d := (a1 - a2) / (a - a1) println("${i:2} ${d:.8f}") d1, a2, a1 = d, a1, a } }   fn main() { feigenbaum() }
http://rosettacode.org/wiki/Feigenbaum_constant_calculation
Feigenbaum constant calculation
Task Calculate the Feigenbaum constant. See   Details in the Wikipedia article:   Feigenbaum constant.
#Wren
Wren
import "/fmt" for Fmt   var feigenbaum = Fn.new { var maxIt = 13 var maxItJ = 10 var a1 = 1 var a2 = 0 var d1 = 3.2 System.print(" i d") for (i in 2..maxIt) { var a = a1 + (a1 - a2)/d1 for (j in 1..maxItJ) { var x = 0 var y = 0 for (k in 1..(1<<i)) { y = 1 - 2*y*x x = a - x*x } a = a - x/y } var d = (a1 - a2)/(a - a1) System.print("%(Fmt.d(2, i))  %(Fmt.f(0, d, 8))") d1 = d a2 = a1 a1 = a } }   feigenbaum.call()
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#Seed7
Seed7
$ include "seed7_05.s7i"; include "osfiles.s7i"; include "time.s7i";   const proc: main is func local var time: modificationTime is time.value; begin modificationTime := getMTime("data.txt"); setMTime("data.txt", modificationTime); end func;
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#Sidef
Sidef
var file = File.new(__FILE__); say file.stat.mtime; # seconds since the epoch   # keep atime unchanged # set mtime to current time file.utime(file.stat.atime, Time.now);
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#Slate
Slate
slate[1]> (File newNamed: 'LICENSE') fileInfo modificationTimestamp. 1240349799
http://rosettacode.org/wiki/Fibonacci_word/fractal
Fibonacci word/fractal
The Fibonacci word may be represented as a fractal as described here: (Clicking on the above website   (hal.archives-ouvertes.fr)   will leave a cookie.) For F_wordm start with F_wordCharn=1 Draw a segment forward If current F_wordChar is 0 Turn left if n is even Turn right if n is odd next n and iterate until end of F_word Task Create and display a fractal similar to Fig 1. (Clicking on the above website   (hal.archives-ouvertes.fr)   will leave a cookie.)
#Scilab
Scilab
final_length = 37;   word_n = ''; word_n_1 = ''; word_n_2 = '';   for i = 1:final_length if i == 1 then word_n = '1'; elseif i == 2 word_n = '0'; elseif i == 3 word_n = '01'; word_n_1 = '0'; else word_n_2 = word_n_1; word_n_1 = word_n; word_n = word_n_1 + word_n_2; end end   word = strsplit(word_n); fractal_size = sum(word' == '0'); fractal = zeros(1+fractal_size,2);   direction_vectors = [1,0; 0,-1; -1,0; 0,1]; direction = direction_vectors(4,:); direction_name = 'N';   for j = 1:length(word_n); fractal(j+1,:) = fractal(j,:) + direction; if word(j) == '0' then if pmodulo(j,2) then //right select direction_name case 'N' then direction = direction_vectors(1,:); direction_name = 'E'; case 'E' then direction = direction_vectors(2,:); direction_name = 'S'; case 'S' then direction = direction_vectors(3,:); direction_name = 'W'; case 'W' then direction = direction_vectors(4,:); direction_name = 'N'; end else //left select direction_name case 'N' then direction = direction_vectors(3,:); direction_name = 'W'; case 'W' then direction = direction_vectors(2,:); direction_name = 'S'; case 'S' then direction = direction_vectors(1,:); direction_name = 'E'; case 'E' then direction = direction_vectors(4,:); direction_name = 'N'; end end end end   scf(0); clf(); plot2d(fractal(:,1),fractal(:,2)); set(gca(),'isoview','on');
http://rosettacode.org/wiki/Fibonacci_word/fractal
Fibonacci word/fractal
The Fibonacci word may be represented as a fractal as described here: (Clicking on the above website   (hal.archives-ouvertes.fr)   will leave a cookie.) For F_wordm start with F_wordCharn=1 Draw a segment forward If current F_wordChar is 0 Turn left if n is even Turn right if n is odd next n and iterate until end of F_word Task Create and display a fractal similar to Fig 1. (Clicking on the above website   (hal.archives-ouvertes.fr)   will leave a cookie.)
#Sidef
Sidef
var(m=17, scale=3) = ARGV.map{.to_i}...   (var world = Hash.new){0}{0} = 1 var loc = 0 var dir = 1i   var fib = ['1', '0'] func fib_word(n) { fib[n] \\= (fib_word(n-1) + fib_word(n-2)) }   func step { scale.times { loc += dir world{loc.im}{loc.re} = 1 } }   func turn_left { dir *= 1i } func turn_right { dir *= -1i }   var n = 1 fib_word(m).each { |c| if (c == '0') { step() n % 2 == 0 ? turn_left()  : turn_right() } else { n++ } }   func braille_graphics(a) { var (xlo, xhi, ylo, yhi) = ([Inf, -Inf]*2)...   a.each_key { |y| ylo.min!(y.to_i) yhi.max!(y.to_i) a{y}.each_key { |x| xlo.min!(x.to_i) xhi.max!(x.to_i) } }   for y in (ylo..yhi `by` 4) { for x in (xlo..xhi `by` 2) { var cell = 0x2800   a{y+0}{x+0} && (cell += 1) a{y+1}{x+0} && (cell += 2) a{y+2}{x+0} && (cell += 4) a{y+0}{x+1} && (cell += 8) a{y+1}{x+1} && (cell += 16) a{y+2}{x+1} && (cell += 32) a{y+3}{x+0} && (cell += 64) a{y+3}{x+1} && (cell += 128)   print cell.chr } print "\n" } }   braille_graphics(world)
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
#Perl
Perl
sub common_prefix { my $sep = shift; my $paths = join "\0", map { $_.$sep } @_; $paths =~ /^ ( [^\0]* ) $sep [^\0]* (?: \0 \1 $sep [^\0]* )* $/x; return $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
#Phix
Phix
with javascript_semantics function common_directory_path(sequence paths, integer sep='/') sequence res = {} if length(paths) then res = split(paths[1],sep)[1..-2] for i=2 to length(paths) do sequence pi = split(paths[i],sep)[1..-2] for j=1 to length(res) do if j>length(pi) or res[j]!=pi[j] then res = res[1..j-1] exit end if end for if length(res)=0 then exit end if end for end if return join(res,sep) end function constant test = {"/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members"} ?common_directory_path(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.
#Dyalect
Dyalect
func Array.Filter(pred) { var arr = [] for x in this when pred(x) { arr.Add(x) } arr }   var arr = [1..20].Filter(x => x % 2 == 0) print(arr)
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.
#REXX
REXX
/*REXX program finds the recursion limit: a subroutine that repeatably calls itself. */ parse version x; say x; say /*display which REXX is being used. */ #=0 /*initialize the numbers of invokes to 0*/ call self /*invoke the SELF subroutine. */ /* [↓] this will never be executed. */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ self: procedure expose # /*declaring that SELF is a subroutine.*/ #=#+1 /*bump number of times SELF is invoked. */ say # /*display the number of invocations. */ call self /*invoke ourselves recursively. */
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.
#Ring
Ring
  recurse(0)   func recurse x see ""+ x + nl recurse(x+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
#Groovy
Groovy
1.upto(100) { i -> println "${i % 3 ? '' : 'Fizz'}${i % 5 ? '' : 'Buzz'}" ?: 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.
#Oforth
Oforth
File new("input.txt") size println File new("/input.txt") size println
http://rosettacode.org/wiki/File_size
File size
Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
#ooRexx
ooRexx
Parse Version v Say v fid='test.txt' x=sysfiletree(fid,a.) Say a.0 Say a.1 Say left(copies('123456789.',10),length(a.1)) Parse Var a.1 20 size . Say 'file size:' size s=charin(fid,,1000) Say length(s) Say 'file' fid 'type' fid
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.
#Oz
Oz
declare [Path] = {Module.link ['x-oz://system/os/Path.ozf']} in {Show {Path.size "input.txt"}} {Show {Path.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.
#GML
GML
var file, str; file = file_text_open_read("input.txt"); str = ""; while (!file_text_eof(file)) { str += file_text_read_string(file); if (!file_text_eof(file)) { str += " "; //It is important to note that a linebreak is actually inserted here rather than a character code of some kind file_text_readln(file); } } file_text_close(file);   file = file_text_open_write("output.txt"); file_text_write_string(file,str); file_text_close(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
#JavaScript
JavaScript
//makes outputting a table possible in environments //that don't support console.table() function console_table(xs) { function pad(n,s) { var res = s; for (var i = s.length; i < n; i++) res += " "; return res; }   if (xs.length === 0) console.log("No data"); else { var widths = []; var cells = []; for (var i = 0; i <= xs.length; i++) cells.push([]);   for (var s in xs[0]) { var len = s.length; cells[0].push(s);   for (var i = 0; i < xs.length; i++) { var ss = "" + xs[i][s]; len = Math.max(len, ss.length); cells[i+1].push(ss); } widths.push(len); } var s = ""; for (var x = 0; x < cells.length; x++) { for (var y = 0; y < widths.length; y++) s += "|" + pad(widths[y], cells[x][y]); s += "|\n"; } console.log(s); } }   //returns the entropy of a string as a number function entropy(s) { //create an object containing each individual char //and the amount of iterations per char function prob(s) { var h = Object.create(null); s.split('').forEach(function(c) { h[c] && h[c]++ || (h[c] = 1); }); return h; }   s = s.toString(); //just in case var e = 0, l = s.length, h = prob(s);   for (var i in h ) { var p = h[i]/l; e -= p * Math.log(p) / Math.log(2); } return e; }   //creates Fibonacci Word to n as described on Rosetta Code //see rosettacode.org/wiki/Fibonacci_word function fibWord(n) { var wOne = "1", wTwo = "0", wNth = [wOne, wTwo], w = "", o = [];   for (var i = 0; i < n; i++) { if (i === 0 || i === 1) { w = wNth[i]; } else { w = wNth[i - 1] + wNth[i - 2]; wNth.push(w); } var l = w.length; var e = entropy(w);   if (l <= 21) { o.push({ N: i + 1, Length: l, Entropy: e, Word: w }); } else { o.push({ N: i + 1, Length: l, Entropy: e, Word: "..." }); } }   try { console.table(o); } catch (err) { console_table(o); } }   fibWord(37);