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/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.
#Lua
Lua
local file = io.open("input.txt","r") local data = file:read("*a") file:close()   local output = {} local key = nil   -- iterate through lines for line in data:gmatch("(.-)\r?\n") do if line:match("%s") then error("line contained space") elseif line:sub(1,1) == ">" then key = line:sub(2) -- if key already exists, append to the previous input output[key] = output[key] or "" elseif key ~= nil then output[key] = output[key] .. line end end   -- print result for k,v in pairs(output) do print(k..": "..v) 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.
#M2000_Interpreter
M2000 Interpreter
  Module CheckIt { Class FASTA_MACHINE { Events "GetBuffer", "header", "DataLine", "Quit" Public: Module Run { Const lineFeed$=chr$(13)+chr$(10) Const WhiteSpace$=" "+chr$(9)+chrcode$(160) Def long state=1, idstate=1 Def boolean Quit=False Def Buf$, waste$, Packet$ GetNextPacket: Call Event "Quit", &Quit If Quit then exit Call Event "GetBuffer", &Packet$ Buf$+=Packet$ If len(Buf$)=0 Then exit On State Goto GetStartIdentifier, GetIdentifier, GetStartData, GetData, GetStartIdentifier2 exit GetStartIdentifier: waste$=rightpart$(Buf$, ">") GetStartIdentifier2: If len(waste$)=0 Then waste$=rightpart$(Buf$, ";") : idstate=2 If len(waste$)=0 Then idstate=1 : Goto GetNextPacket ' we have to read more buf$=waste$ state=2 GetIdentifier: If Len(Buf$)=len(lineFeed$) then { if buf$<>lineFeed$ then Goto GetNextPacket waste$="" } Else { if instr(buf$, lineFeed$)=0 then Goto GetNextPacket waste$=rightpart$(Buf$, lineFeed$) } If idstate=2 Then { idstate=1 \\ it's a comment, drop it state=1 Goto GetNextPacket } Else Call Event "header", filter$(leftpart$(Buf$,lineFeed$), WhiteSpace$) Buf$=waste$ State=3 GetStartData: while left$(buf$, 2)=lineFeed$ {buf$=Mid$(buf$,3)} waste$=Leftpart$(Buf$, lineFeed$) If len(waste$)=0 Then Goto GetNextPacket ' we have to read more waste$=Filter$(waste$,WhiteSpace$) Call Event "DataLine", leftpart$(Buf$,lineFeed$) Buf$=Rightpart$(Buf$,lineFeed$) state=4 GetData: while left$(buf$, 2)=lineFeed$ {buf$=Mid$(buf$,3)} waste$=Leftpart$(Buf$, lineFeed$) If len(waste$)=0 Then Goto GetNextPacket ' we have to read more If Left$(waste$,1)=";" Then wast$="": state=5 : Goto GetStartIdentifier2 If Left$(waste$,1)=">" Then state=1 : Goto GetStartIdentifier waste$=Filter$(waste$,WhiteSpace$) Call Event "DataLine", waste$ Buf$=Rightpart$(Buf$,lineFeed$) Goto GetNextPacket } } Group WithEvents K=FASTA_MACHINE() Document Final$, Inp$   \\ In documents, "="" used for append data. Final$="append this" Const NewLine$=chr$(13)+chr$(10) Const Center=2 \\ Event's Functions Function K_GetBuffer (New &a$) { Input "IN:", a$ inp$=a$+NewLine$ while right$(a$, 1)="\" { Input "IN:", b$ inp$=b$+NewLine$ if b$="" then b$="n" a$+=b$ } a$= replace$("\N","\n", a$) a$= replace$("\n",NewLine$, a$) } Function K_header (New a$) { iF Doc.Len(Final$)=0 then { Final$=a$+": " } Else Final$=Newline$+a$+": " } Function K_DataLine (New a$) { Final$=a$ } Function K_Quit (New &q) { q=keypress(1) } Cls , 0 Report Center, "FASTA Format" Report "Simulate input channel in packets (\n for new line). Use empty input to exit after new line, or press left mouse button and Enter to quit. Use ; to write comments. Use > to open a title" Cls, row ' scroll from current row K.Run Cls Report Center, "Input File" Report Inp$ Report Center, "Output File" Report Final$ } checkit  
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: Fn = Fn+2 - Fn+1, if n<0 support for negative     n     in the solution is optional. Related tasks   Fibonacci n-step number sequences‎   Leonardo numbers References   Wikipedia, Fibonacci number   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#0815
0815
  %<:0D:>~$<:01:~%>=<:a94fad42221f2702:>~> }:_s:{x{={~$x+%{=>~>x~-x<:0D:~>~>~^:_s:?  
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
#360_Assembly
360 Assembly
* Factors of an integer - 07/10/2015 FACTOR CSECT USING FACTOR,R15 set base register LA R7,PG pgi=@pg LA R6,1 i L R3,N loop count LOOP L R5,N n LA R4,0 DR R4,R6 n/i LTR R4,R4 if mod(n,i)=0 BNZ NEXT XDECO R6,PG+120 edit i MVC 0(6,R7),PG+126 output i LA R7,6(R7) pgi=pgi+6 NEXT LA R6,1(R6) i=i+1 BCT R3,LOOP loop XPRNT PG,120 print buffer XR R15,R15 set return code BR R14 return to caller N DC F'12345' <== input value PG DC CL132' ' buffer YREGS END FACTOR
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.
#C
C
    #include <stdio.h> #include <math.h> #include <complex.h>   double PI; typedef double complex cplx;   void _fft(cplx buf[], cplx out[], int n, int step) { if (step < n) { _fft(out, buf, n, step * 2); _fft(out + step, buf + step, n, step * 2);   for (int i = 0; i < n; i += 2 * step) { cplx t = cexp(-I * PI * i / n) * out[i + step]; buf[i / 2] = out[i] + t; buf[(i + n)/2] = out[i] - t; } } }   void fft(cplx buf[], int n) { cplx out[n]; for (int i = 0; i < n; i++) out[i] = buf[i];   _fft(buf, out, n, 1); }     void show(const char * s, cplx buf[]) { printf("%s", s); for (int i = 0; i < 8; i++) if (!cimag(buf[i])) printf("%g ", creal(buf[i])); else printf("(%g, %g) ", creal(buf[i]), cimag(buf[i])); }   int main() { PI = atan2(1, 1) * 4; cplx buf[] = {1, 1, 1, 1, 0, 0, 0, 0};   show("Data: ", buf); fft(buf, 8); show("\nFFT : ", buf);   return 0; }    
http://rosettacode.org/wiki/Factors_of_a_Mersenne_number
Factors of a Mersenne number
A Mersenne number is a number in the form of 2P-1. If P is prime, the Mersenne number may be a Mersenne prime (if P is not prime, the Mersenne number is also not prime). In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before starting a, potentially lengthy, Lucas-Lehmer test. There are very efficient algorithms for determining if a number divides 2P-1 (or equivalently, if 2P mod (the number) = 1). Some languages already have built-in implementations of this exponent-and-mod operation (called modPow or similar). The following is how to implement this modPow yourself: For example, let's compute 223 mod 47. Convert the exponent 23 to binary, you get 10111. Starting with square = 1, repeatedly square it. Remove the top bit of the exponent, and if it's 1 multiply square by the base of the exponentiation (2), then compute square modulo 47. Use the result of the modulo from the last step as the initial value of square in the next step: remove optional square top bit multiply by 2 mod 47 ──────────── ─────── ───────────── ────── 1*1 = 1 1 0111 1*2 = 2 2 2*2 = 4 0 111 no 4 4*4 = 16 1 11 16*2 = 32 32 32*32 = 1024 1 1 1024*2 = 2048 27 27*27 = 729 1 729*2 = 1458 1 Since 223 mod 47 = 1, 47 is a factor of 2P-1. (To see this, subtract 1 from both sides: 223-1 = 0 mod 47.) Since we've shown that 47 is a factor, 223-1 is not prime. Further properties of Mersenne numbers allow us to refine the process even more. Any factor q of 2P-1 must be of the form 2kP+1, k being a positive integer or zero. Furthermore, q must be 1 or 7 mod 8. Finally any potential factor q must be prime. As in other trial division algorithms, the algorithm stops when 2kP+1 > sqrt(N). These primality tests only work on Mersenne numbers where P is prime. For example, M4=15 yields no factors using these techniques, but factors into 3 and 5, neither of which fit 2kP+1. Task Using the above method find a factor of 2929-1 (aka M929) Related tasks   count in factors   prime decomposition   factors of an integer   Sieve of Eratosthenes   primality by trial division   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division See also   Computers in 1948: 2127 - 1       (Note:   This video is no longer available because the YouTube account associated with this video has been terminated.)
#Arturo
Arturo
mersenneFactors: function [q][ if not? prime? q -> print "number not prime!" r: new q while -> r > 0 -> shl 'r 1 d: new 1 + 2 * q while [true][ i: new 1 p: new r while [p <> 0][ i: new (i * i) % d if p < 0 -> 'i * 2 if i > d -> 'i - d shl 'p 1 ] if? i <> 1 -> 'd + 2 * q else -> break ] print ["2 ^" q "- 1 = 0 ( mod" d ")"] ]   mersenneFactors 929
http://rosettacode.org/wiki/Factors_of_a_Mersenne_number
Factors of a Mersenne number
A Mersenne number is a number in the form of 2P-1. If P is prime, the Mersenne number may be a Mersenne prime (if P is not prime, the Mersenne number is also not prime). In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before starting a, potentially lengthy, Lucas-Lehmer test. There are very efficient algorithms for determining if a number divides 2P-1 (or equivalently, if 2P mod (the number) = 1). Some languages already have built-in implementations of this exponent-and-mod operation (called modPow or similar). The following is how to implement this modPow yourself: For example, let's compute 223 mod 47. Convert the exponent 23 to binary, you get 10111. Starting with square = 1, repeatedly square it. Remove the top bit of the exponent, and if it's 1 multiply square by the base of the exponentiation (2), then compute square modulo 47. Use the result of the modulo from the last step as the initial value of square in the next step: remove optional square top bit multiply by 2 mod 47 ──────────── ─────── ───────────── ────── 1*1 = 1 1 0111 1*2 = 2 2 2*2 = 4 0 111 no 4 4*4 = 16 1 11 16*2 = 32 32 32*32 = 1024 1 1 1024*2 = 2048 27 27*27 = 729 1 729*2 = 1458 1 Since 223 mod 47 = 1, 47 is a factor of 2P-1. (To see this, subtract 1 from both sides: 223-1 = 0 mod 47.) Since we've shown that 47 is a factor, 223-1 is not prime. Further properties of Mersenne numbers allow us to refine the process even more. Any factor q of 2P-1 must be of the form 2kP+1, k being a positive integer or zero. Furthermore, q must be 1 or 7 mod 8. Finally any potential factor q must be prime. As in other trial division algorithms, the algorithm stops when 2kP+1 > sqrt(N). These primality tests only work on Mersenne numbers where P is prime. For example, M4=15 yields no factors using these techniques, but factors into 3 and 5, neither of which fit 2kP+1. Task Using the above method find a factor of 2929-1 (aka M929) Related tasks   count in factors   prime decomposition   factors of an integer   Sieve of Eratosthenes   primality by trial division   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division See also   Computers in 1948: 2127 - 1       (Note:   This video is no longer available because the YouTube account associated with this video has been terminated.)
#AutoHotkey
AutoHotkey
MsgBox % MFact(27) ;-1: 27 is not prime MsgBox % MFact(2) ; 0 MsgBox % MFact(3) ; 0 MsgBox % MFact(5) ; 0 MsgBox % MFact(7) ; 0 MsgBox % MFact(11) ; 23 MsgBox % MFact(13) ; 0 MsgBox % MFact(17) ; 0 MsgBox % MFact(19) ; 0 MsgBox % MFact(23) ; 47 MsgBox % MFact(29) ; 233 MsgBox % MFact(31) ; 0 MsgBox % MFact(37) ; 223 MsgBox % MFact(41) ; 13367 MsgBox % MFact(43) ; 431 MsgBox % MFact(47) ; 2351 MsgBox % MFact(53) ; 6361 MsgBox % MFact(929) ; 13007   MFact(p) { ; blank if 2**p-1 can be prime, otherwise a prime divisor < 2**32 If !IsPrime32(p) Return -1 ; Error (p must be prime) Loop % 2.0**(p<64 ? p/2-1 : 31)/p ; test prime divisors < 2**32, up to sqrt(2**p-1) If (((q:=2*p*A_Index+1)&7 = 1 || q&7 = 7) && IsPrime32(q) && PowMod(2,p,q)=1) Return q Return 0 }   IsPrime32(n) { ; n < 2**32 If n in 2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97 Return 1 If (!(n&1)||!mod(n,3)||!mod(n,5)||!mod(n,7)||!mod(n,11)||!mod(n,13)||!mod(n,17)||!mod(n,19)) Return 0 n1 := d := n-1, s := 0 While !(d&1) d>>=1, s++ Loop 3 { x := PowMod( A_Index=1 ? 2 : A_Index=2 ? 7 : 61, d, n) If (x=1 || x=n1) Continue Loop % s-1 If (1 = x:=PowMod(x,2,n)) Return 0 Else If (x = n1) Break IfLess x,%n1%, Return 0 } Return 1 }   PowMod(x,n,m) { ; x**n mod m y := 1, i := n, z := x While i>0 y := i&1 ? mod(y*z,m) : y, z := mod(z*z,m), i >>= 1 Return y }
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
#Crystal
Crystal
require "big"   def farey(n) a, b, c, d = 0, 1, 1, n fracs = [] of BigRational fracs << BigRational.new(0,1) while c <= n k = (n + b) // d a, b, c, d = c, d, k * c - a, k * d - b fracs << BigRational.new(a,b) end fracs.uniq.sort end   puts "Farey sequence for order 1 through 11 (inclusive):" (1..11).each do |n| puts "F(#{n}): 0/1 #{farey(n)[1..-2].join(" ")} 1/1" end   puts "Number of fractions in the Farey sequence:" (100..1000).step(100) do |i| puts "F(%4d) =%7d" % [i, farey(i).size] end  
http://rosettacode.org/wiki/Fairshare_between_two_and_more
Fairshare between two and more
The Thue-Morse sequence is a sequence of ones and zeros that if two people take turns in the given order, the first persons turn for every '0' in the sequence, the second for every '1'; then this is shown to give a fairer, more equitable sharing of resources. (Football penalty shoot-outs for example, might not favour the team that goes first as much if the penalty takers take turns according to the Thue-Morse sequence and took 2^n penalties) The Thue-Morse sequence of ones-and-zeroes can be generated by: "When counting in binary, the digit sum modulo 2 is the Thue-Morse sequence" Sharing fairly between two or more Use this method: When counting base b, the digit sum modulo b is the Thue-Morse sequence of fairer sharing between b people. Task Counting from zero;   using a function/method/routine to express an integer count in base b, sum the digits modulo b to produce the next member of the Thue-Morse fairshare series for b people. Show the first 25 terms of the fairshare sequence:   For two people:   For three people   For five people   For eleven people Related tasks   Non-decimal radices/Convert   Thue-Morse See also   A010060, A053838, A053840: The On-Line Encyclopedia of Integer Sequences® (OEIS®)
#Haskell
Haskell
import Data.Bool (bool) import Data.List (intercalate, unfoldr) import Data.Tuple (swap)   ------------- FAIR SHARE BETWEEN TWO AND MORE ------------   thueMorse :: Int -> [Int] thueMorse base = baseDigitsSumModBase base <$> [0 ..]   baseDigitsSumModBase :: Int -> Int -> Int baseDigitsSumModBase base n = mod ( sum $ unfoldr ( bool Nothing . Just . swap . flip quotRem base <*> (0 <) ) n ) base   --------------------------- TEST ------------------------- main :: IO () main = putStrLn $ fTable ( "First 25 fairshare terms " <> "for a given number of players:\n" ) show ( ('[' :) . (<> "]") . intercalate "," . fmap show ) (take 25 . thueMorse) [2, 3, 5, 11]   ------------------------- DISPLAY ------------------------ fTable :: String -> (a -> String) -> (b -> String) -> (a -> b) -> [a] -> String fTable s xShow fxShow f xs = unlines $ s : fmap ( ((<>) . justifyRight w ' ' . xShow) <*> ((" -> " <>) . fxShow . f) ) xs where w = maximum (length . xShow <$> xs)   justifyRight :: Int -> Char -> String -> String justifyRight n c = (drop . length) <*> (replicate n c <>)
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)
#Haskell
Haskell
import Data.Ratio (Ratio, denominator, numerator, (%))   ------------------------ FAULHABER -----------------------   faulhaber :: Int -> Rational -> Rational faulhaber p n = sum $ zipWith ((*) . (n ^)) [1 ..] (faulhaberTriangle !! p)     faulhaberTriangle :: [[Rational]] faulhaberTriangle = tail $ scanl ( \rs n -> let xs = zipWith ((*) . (n %)) [2 ..] rs in 1 - sum xs : xs ) [] [0 ..]     --------------------------- TEST ------------------------- main :: IO () main = do let triangle = take 10 faulhaberTriangle widths = maxWidths triangle mapM_ putStrLn [ unlines ( (justifyRatio widths 8 ' ' =<<) <$> triangle ), (show . numerator) (faulhaber 17 1000) ]   ------------------------- DISPLAY ------------------------   justifyRatio :: (Int, Int) -> Int -> Char -> Rational -> String justifyRatio (wn, wd) n c nd = go $ [numerator, denominator] <*> [nd] where -- Minimum column width, or more if specified. w = max n (wn + wd + 2) go [num, den] | 1 == den = center w c (show num) | otherwise = let (q, r) = quotRem (w - 1) 2 in concat [ justifyRight q c (show num), "/", justifyLeft (q + r) c (show den) ]   justifyLeft :: Int -> a -> [a] -> [a] justifyLeft n c s = take n (s <> replicate n c)   justifyRight :: Int -> a -> [a] -> [a] justifyRight n c = (drop . length) <*> (replicate n c <>)   center :: Int -> a -> [a] -> [a] center n c s = let (q, r) = quotRem (n - length s) 2 pad = replicate q c in concat [pad, s, pad, replicate r c]   maxWidths :: [[Rational]] -> (Int, Int) maxWidths xss = let widest f xs = maximum $ fmap (length . show . f) xs in ((,) . widest numerator <*> widest denominator) $ concat xss
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.
#J
J
Bsecond=:verb define"0 +/,(<:*(_1^[)*!*(y^~1+[)%1+])"0/~i.1x+y )   Bfirst=: Bsecond - 1&=   Faul=:adverb define (0,|.(%m+1x) * (_1x&^ * !&(m+1) * Bfirst) i.1+m)&p. )
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
#Wren
Wren
import "/big" for BigInt   var fermat = Fn.new { |n| BigInt.two.pow(2.pow(n)) + 1 }   var fns = List.filled(10, null) System.print("The first 10 Fermat numbers are:") for (i in 0..9) { fns[i] = fermat.call(i) System.print("F%(String.fromCodePoint(0x2080+i)) = %(fns[i])") }   System.print("\nFactors of the first 7 Fermat numbers:") for (i in 0..6) { System.write("F%(String.fromCodePoint(0x2080+i)) = ") var factors = BigInt.primeFactors(fns[i]) System.write("%(factors)") if (factors.count == 1) { System.print(" (prime)") } else if (!factors[1].isProbablePrime(5)) { System.print(" (second factor is composite)") } else { System.print() } }
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
#C
C
/* The function anynacci determines the n-arity of the sequence from the number of seed elements. 0 ended arrays are used since C does not have a way of determining the length of dynamic and function-passed integer arrays.*/   #include<stdlib.h> #include<stdio.h>   int * anynacci (int *seedArray, int howMany) { int *result = malloc (howMany * sizeof (int)); int i, j, initialCardinality;   for (i = 0; seedArray[i] != 0; i++); initialCardinality = i;   for (i = 0; i < initialCardinality; i++) result[i] = seedArray[i];   for (i = initialCardinality; i < howMany; i++) { result[i] = 0; for (j = i - initialCardinality; j < i; j++) result[i] += result[j]; } return result; }   int main () { int fibo[] = { 1, 1, 0 }, tribo[] = { 1, 1, 2, 0 }, tetra[] = { 1, 1, 2, 4, 0 }, luca[] = { 2, 1, 0 }; int *fibonacci = anynacci (fibo, 10), *tribonacci = anynacci (tribo, 10), *tetranacci = anynacci (tetra, 10), *lucas = anynacci(luca, 10); int i;   printf ("\nFibonacci\tTribonacci\tTetranacci\tLucas\n");   for (i = 0; i < 10; i++) printf ("\n%d\t\t%d\t\t%d\t\t%d", fibonacci[i], tribonacci[i], tetranacci[i], lucas[i]);   return 0; }
http://rosettacode.org/wiki/Feigenbaum_constant_calculation
Feigenbaum constant calculation
Task Calculate the Feigenbaum constant. See   Details in the Wikipedia article:   Feigenbaum constant.
#zkl
zkl
fcn feigenbaum{ maxIt,maxItJ,a1,a2,d1,a,d := 13, 10, 1.0, 0.0, 3.2, 0, 0; println(" i d"); foreach i in ([2..maxIt]){ a=a1 + (a1 - a2)/d1; foreach j in ([1..maxItJ]){ x,y := 0.0, 0.0; foreach k in ([1..(1).shiftLeft(i)]){ y,x = 1.0 - 2.0*y*x, a - x*x; } a-=x/y } d=(a1 - a2)/(a - a1); println("%2d  %.8f".fmt(i,d)); d1,a2,a1 = d,a1,a; } }();
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#Smalltalk
Smalltalk
|a| a := File name: 'input.txt'. (a lastModifyTime) printNl.
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#Standard_ML
Standard ML
val mtime = OS.FileSys.modTime filename; (* returns a Time.time data structure *)   (* unfortunately it seems like you have to set modification & access times together *) OS.FileSys.setTime (filename, NONE); (* sets modification & access time to now *) (* equivalent to: *) OS.FileSys.setTime (filename, SOME (Time.now ()))
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#Tcl
Tcl
# Get the modification time: set timestamp [file mtime $filename]   # Set the modification time to ‘now’: file mtime $filename [clock seconds]
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.)
#Tcl
Tcl
package require Tk   # OK, this stripped down version doesn't work for n<2… proc fibword {n} { set fw {1 0} while {[llength $fw] < $n} { lappend fw [lindex $fw end][lindex $fw end-1] } return [lindex $fw end] } proc drawFW {canv fw {w {[$canv cget -width]}} {h {[$canv cget -height]}}} { set w [subst $w] set h [subst $h]   # Generate the coordinate list using line segments of unit length set d 3; # Match the orientation in the sample paper set eo [set x [set y 0]] set coords [list $x $y] foreach c [split $fw ""] { switch $d { 0 {lappend coords [incr x] $y} 1 {lappend coords $x [incr y]} 2 {lappend coords [incr x -1] $y} 3 {lappend coords $x [incr y -1]} } if {$c == 0} { set d [expr {($d + ($eo ? -1 : 1)) % 4}] } set eo [expr {!$eo}] }   # Draw, and rescale to fit in canvas set id [$canv create line $coords] lassign [$canv bbox $id] x1 y1 x2 y2 set sf [expr {min(($w-20.) / ($y2-$y1), ($h-20.) / ($x2-$x1))}] $canv move $id [expr {-$x1}] [expr {-$y1}] $canv scale $id 0 0 $sf $sf $canv move $id 10 10 # Return the item ID to allow user reconfiguration return $id }   pack [canvas .c -width 500 -height 500] drawFW .c [fibword 23]
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
#PHP
PHP
<?php   /* This works with dirs and files in any number of combinations. */   function _commonPath($dirList) { $arr = array(); foreach($dirList as $i => $path) { $dirList[$i] = explode('/', $path); unset($dirList[$i][0]);   $arr[$i] = count($dirList[$i]); }   $min = min($arr);   for($i = 0; $i < count($dirList); $i++) { while(count($dirList[$i]) > $min) { array_pop($dirList[$i]); }   $dirList[$i] = '/' . implode('/' , $dirList[$i]); }   $dirList = array_unique($dirList); while(count($dirList) !== 1) { $dirList = array_map('dirname', $dirList); $dirList = array_unique($dirList); } reset($dirList);   return current($dirList); }   /* TEST */   $dirs = array( '/home/user1/tmp/coverage/test', '/home/user1/tmp/covert/operator', '/home/user1/tmp/coven/members', );     if('/home/user1/tmp' !== common_path($dirs)) { echo 'test fail'; } else { echo 'test success'; }   ?>
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.C3.A9j.C3.A0_Vu
Déjà Vu
filter pred lst: ] for value in copy lst: if pred @value: @value [   even x: = 0 % x 2   !. filter @even [ 0 1 2 3 4 5 6 7 8 9 ]
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.
#Ruby
Ruby
def recurse x puts x recurse(x+1) end   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.
#Run_BASIC
Run BASIC
a = recurTest(1)   function recurTest(n) if n mod 100000 then cls:print n if n > 327000 then [ext] n = recurTest(n+1) [ext] end function
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
#GW-BASIC
GW-BASIC
fizzbuzz :: Int -> String fizzbuzz x | f 15 = "FizzBuzz" | f 3 = "Fizz" | f 5 = "Buzz" | otherwise = show x where f = (0 ==) . rem x   main :: IO () main = mapM_ (putStrLn . fizzbuzz) [1 .. 100]
http://rosettacode.org/wiki/File_size
File size
Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
#Pascal
Pascal
my $size1 = -s 'input.txt'; my $size2 = -s '/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.
#Perl
Perl
my $size1 = -s 'input.txt'; my $size2 = -s '/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.
#Phix
Phix
function file_size(sequence file_name) object d = dir(file_name) if atom(d) or length(d)!=1 then return -1 end if return d[1][D_SIZE] end function procedure test(sequence file_name) integer size = file_size(file_name) if size<0 then printf(1,"%s file does not exist.\n",{file_name}) else printf(1,"%s size is %d.\n",{file_name,size}) end if end procedure test("input.txt") -- in the current working directory test("/input.txt") -- in the file system root
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.
#Go
Go
package main   import ( "fmt" "io/ioutil" )   func main() { b, err := ioutil.ReadFile("input.txt") if err != nil { fmt.Println(err) return } if err = ioutil.WriteFile("output.txt", b, 0666); err != nil { fmt.Println(err) } }
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.
#Groovy
Groovy
content = new File('input.txt').text new File('output.txt').write(content)
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
#jq
jq
# Input: an array of strings. # Output: an object with the strings as keys, # the values of which are the corresponding frequencies. def counter: reduce .[] as $item ( {}; .[$item] += 1 ) ;   # entropy in bits of the input string def entropy: (explode | map( [.] | implode ) | counter | [ .[] | . * (.|log) ] | add) as $sum | ((length|log) - ($sum / length)) / (2|log) ;
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
#Julia
Julia
using DataStructures entropy(s::AbstractString) = -sum(x -> x / length(s) * log2(x / length(s)), values(counter(s)))   function fibboword(n::Int64) # Initialize the result r = Array{String}(n) # First element r[1] = "0" # If more than 2, set the second element if n ≥ 2 r[2] = "1" end # Recursively create elements > 3 for i in 3:n r[i] = r[i - 1] * r[i - 2] end return r end   function testfibbo(n::Integer) fib = fibboword(n) for i in 1:length(fib) @printf("%3d%9d%12.6f\n", i, length(fib[i]), entropy(fib[i])) end return 0 end   println(" n\tlength\tentropy") testfibbo(37)
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ImportString[">Rosetta_Example_1 THERECANBENOSPACE >Rosetta_Example_2 THERECANBESEVERAL LINESBUTTHEYALLMUST BECONCATENATED ", "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.
#Nim
Nim
  import strutils   let input = """>Rosetta_Example_1 THERECANBENOSPACE >Rosetta_Example_2 THERECANBESEVERAL LINESBUTTHEYALLMUST BECONCATENATED""".unindent   proc fasta*(input: string) = var row = "" for line in input.splitLines: if line.startsWith(">"): if row != "": echo row row = line[1..^1] & ": " else: row &= line.strip echo row   fasta(input)  
http://rosettacode.org/wiki/FASTA_format
FASTA format
In bioinformatics, long character strings are often encoded in a format called FASTA. A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line. Task Write a program that reads a FASTA file such as: >Rosetta_Example_1 THERECANBENOSPACE >Rosetta_Example_2 THERECANBESEVERAL LINESBUTTHEYALLMUST BECONCATENATED Output: Rosetta_Example_1: THERECANBENOSPACE Rosetta_Example_2: THERECANBESEVERALLINESBUTTHEYALLMUSTBECONCATENATED Note that a high-quality implementation will not hold the entire file in memory at once; real FASTA files can be multiple gigabytes in size.
#Objeck
Objeck
class Fasta { function : Main(args : String[]) ~ Nil { if(args->Size() = 1) { is_line := false; tokens := System.Utility.Parser->Tokenize(System.IO.File.FileReader->ReadFile(args[0]))<String>; each(i : tokens) { token := tokens->Get(i); if(token->Get(0) = '>') { is_line := true; if(i <> 0) { "\n"->Print(); }; } else if(is_line) { "{$token}: "->Print(); is_line := false; } else { token->Print(); }; }; }; }; } }  
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: Fn = Fn+2 - Fn+1, if n<0 support for negative     n     in the solution is optional. Related tasks   Fibonacci n-step number sequences‎   Leonardo numbers References   Wikipedia, Fibonacci number   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#11l
11l
F fib_iter(n) I n < 2 R n V fib_prev = 1 V fib = 1 L 2 .< n (fib_prev, fib) = (fib, fib + fib_prev) R fib   L(i) 1..20 print(fib_iter(i), end' ‘ ’) print()
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
#68000_Assembly
68000 Assembly
;max input range equals 0 to 0xFFFFFFFF.       jsr GetInput ;unimplemented routine to get user input for a positive (nonzero) integer. ;output of this routine will be in D0.   MOVE.L D0,D1 ;D1 will be used for temp storage. MOVE.L #1,D2 ;start with 1.   computeFactors: DIVU D2,D1 ;remainder is in top 2 bytes, quotient in bottom 2. MOVE.L D1,D3 ;temporarily store into D3 to check the remainder SWAP D3 ;swap the high and low words of D3. Now bottom 2 bytes contain remainder. CMP.W #0,D3 ;is the bottom word equal to 0? BNE D2_Wasnt_A_Divisor ;if not, D2 was not a factor of D1.   JSR PrintD2 ;unimplemented routine to print D2 to the screen as a decimal number.     D2_Wasnt_A_Divisor: MOVE.L D0,D1 ;restore D1. ADDQ.L #1,D2 ;increment D2 CMP.L D2,D1 ;is D2 now greater than D1? BLS computeFactors ;if not, loop again     ;end of program
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.
#C.23
C#
using System; using System.Numerics; using System.Linq; using System.Diagnostics;   // Fast Fourier Transform in C# public class Program {   /* Performs a Bit Reversal Algorithm on a postive integer * for given number of bits * e.g. 011 with 3 bits is reversed to 110 */ public static int BitReverse(int n, int bits) { int reversedN = n; int count = bits - 1;   n >>= 1; while (n > 0) { reversedN = (reversedN << 1) | (n & 1); count--; n >>= 1; }   return ((reversedN << count) & ((1 << bits) - 1)); }   /* Uses Cooley-Tukey iterative in-place algorithm with radix-2 DIT case * assumes no of points provided are a power of 2 */ public static void FFT(Complex[] buffer) { #if false int bits = (int)Math.Log(buffer.Length, 2); for (int j = 1; j < buffer.Length / 2; j++) {   int swapPos = BitReverse(j, bits); var temp = buffer[j]; buffer[j] = buffer[swapPos]; buffer[swapPos] = temp; } // Said Zandian // The above section of the code is incorrect and does not work correctly and has two bugs. // BUG 1 // The bug is that when you reach and index that was swapped previously it does swap it again // Ex. binary value n = 0010 and Bits = 4 as input to BitReverse routine and returns 4. The code section above // swaps it. Cells 2 and 4 are swapped. just fine. // now binary value n = 0010 and Bits = 4 as input to BitReverse routine and returns 2. The code Section // swap it. Cells 4 and 2 are swapped. WROOOOONG // // Bug 2 // The code works on the half section of the cells. In the case of Bits = 4 it means that we are having 16 cells // The code works on half the cells for (int j = 1; j < buffer.Length / 2; j++) buffer.Length returns 16 // and divide by 2 makes 8, so j goes from 1 to 7. This covers almost everything but what happened to 1011 value // which must be swap with 1101. and this is the second bug. // // use the following corrected section of the code. I have seen this bug in other languages that uses bit // reversal routine.   #else for (int j = 1; j < buffer.Length; j++) { int swapPos = BitReverse(j, bits); if (swapPos <= j) { continue; } var temp = buffer[j]; buffer[j] = buffer[swapPos]; buffer[swapPos] = temp; }   // First the full length is used and 1011 value is swapped with 1101. Second if new swapPos is less than j // then it means that swap was happen when j was the swapPos.   #endif   for (int N = 2; N <= buffer.Length; N <<= 1) { for (int i = 0; i < buffer.Length; i += N) { for (int k = 0; k < N / 2; k++) {   int evenIndex = i + k; int oddIndex = i + k + (N / 2); var even = buffer[evenIndex]; var odd = buffer[oddIndex];   double term = -2 * Math.PI * k / (double)N; Complex exp = new Complex(Math.Cos(term), Math.Sin(term)) * odd;   buffer[evenIndex] = even + exp; buffer[oddIndex] = even - exp;   } } } }   public static void Main(string[] args) { Complex[] input = {1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0};   FFT(input);   Console.WriteLine("Results:"); foreach (Complex c in input) { Console.WriteLine(c); } } }
http://rosettacode.org/wiki/Factors_of_a_Mersenne_number
Factors of a Mersenne number
A Mersenne number is a number in the form of 2P-1. If P is prime, the Mersenne number may be a Mersenne prime (if P is not prime, the Mersenne number is also not prime). In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before starting a, potentially lengthy, Lucas-Lehmer test. There are very efficient algorithms for determining if a number divides 2P-1 (or equivalently, if 2P mod (the number) = 1). Some languages already have built-in implementations of this exponent-and-mod operation (called modPow or similar). The following is how to implement this modPow yourself: For example, let's compute 223 mod 47. Convert the exponent 23 to binary, you get 10111. Starting with square = 1, repeatedly square it. Remove the top bit of the exponent, and if it's 1 multiply square by the base of the exponentiation (2), then compute square modulo 47. Use the result of the modulo from the last step as the initial value of square in the next step: remove optional square top bit multiply by 2 mod 47 ──────────── ─────── ───────────── ────── 1*1 = 1 1 0111 1*2 = 2 2 2*2 = 4 0 111 no 4 4*4 = 16 1 11 16*2 = 32 32 32*32 = 1024 1 1 1024*2 = 2048 27 27*27 = 729 1 729*2 = 1458 1 Since 223 mod 47 = 1, 47 is a factor of 2P-1. (To see this, subtract 1 from both sides: 223-1 = 0 mod 47.) Since we've shown that 47 is a factor, 223-1 is not prime. Further properties of Mersenne numbers allow us to refine the process even more. Any factor q of 2P-1 must be of the form 2kP+1, k being a positive integer or zero. Furthermore, q must be 1 or 7 mod 8. Finally any potential factor q must be prime. As in other trial division algorithms, the algorithm stops when 2kP+1 > sqrt(N). These primality tests only work on Mersenne numbers where P is prime. For example, M4=15 yields no factors using these techniques, but factors into 3 and 5, neither of which fit 2kP+1. Task Using the above method find a factor of 2929-1 (aka M929) Related tasks   count in factors   prime decomposition   factors of an integer   Sieve of Eratosthenes   primality by trial division   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division See also   Computers in 1948: 2127 - 1       (Note:   This video is no longer available because the YouTube account associated with this video has been terminated.)
#BBC_BASIC
BBC BASIC
PRINT "A factor of M929 is "; FNmersenne_factor(929) PRINT "A factor of M937 is "; FNmersenne_factor(937) END   DEF FNmersenne_factor(P%) LOCAL K%, Q% IF NOT FNisprime(P%) THEN = -1 FOR K% = 1 TO 1000000 Q% = 2*K%*P% + 1 IF (Q% AND 7) = 1 OR (Q% AND 7) = 7 THEN IF FNisprime(Q%) IF FNmodpow(2, P%, Q%) = 1 THEN = Q% ENDIF NEXT K% = 0   DEF FNisprime(N%) LOCAL D% IF N% MOD 2=0 THEN = (N% = 2) IF N% MOD 3=0 THEN = (N% = 3) D% = 5 WHILE D% * D% <= N% IF N% MOD D% = 0 THEN = FALSE D% += 2 IF N% MOD D% = 0 THEN = FALSE D% += 4 ENDWHILE = TRUE   DEF FNmodpow(X%, N%, M%) LOCAL I%, Y%, Z% I% = N% : Y% = 1 : Z% = X% WHILE I% IF I% AND 1 THEN Y% = (Y% * Z%) MOD M% Z% = (Z% * Z%) MOD M% I% = I% >>> 1 ENDWHILE = Y%  
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.)
#Bracmat
Bracmat
( ( modPow = square P divisor highbit log 2pow .  !arg:(?P.?divisor) & 1:?square & 2\L!P:#%?log+? & 2^!log:?2pow & whl ' ( mod $ ( ( div$(!P.!2pow):1&2 | 1 ) * !square^2 . !divisor )  : ?square & mod$(!P.!2pow):?P & 1/2*!2pow:~/:?2pow ) & !square ) & ( isPrime = incs nextincs primeCandidate nextPrimeCandidate quotient . 1 1 2 2 (4 2 4 2 4 6 2 6:?incs)  : ?nextincs & 1:?primeCandidate & ( nextPrimeCandidate = ( !nextincs:&!incs:?nextincs | ) & !nextincs:%?inc ?nextincs & !inc+!primeCandidate:?primeCandidate ) & whl ' ( (!nextPrimeCandidate:?divisor)^2:~>!arg & !arg*!divisor^-1:?quotient:/ ) & !quotient:/ ) & ( Factors-of-a-Mersenne-Number = P k candidate bignum .  !arg:?P & 2^!P+-1:?bignum & 0:?k & whl ' ( 2*(1+!k:?k)*!P+1:?candidate & !candidate^2:~>!bignum & ( ~(mod$(!candidate.8):(1|7)) | ~(isPrime$!candidate) | modPow$(!P.!candidate):?mp:~1 ) ) & !mp:1 & (!candidate.(2^!P+-1)*!candidate^-1) ) & ( Factors-of-a-Mersenne-Number$929:(?divisorA.?divisorB) & out $ ( str $ ("found some divisors of 2^" !P "-1 : " !divisorA " and " !divisorB) ) | out$"no divisors found" ) );
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
#D
D
import std.stdio, std.algorithm, std.range, arithmetic_rational;   auto farey(in int n) pure nothrow @safe { return rational(0, 1).only.chain( iota(1, n + 1) .map!(k => iota(1, k + 1).map!(m => rational(m, k))) .join.sort().uniq); }   void main() @safe { writefln("Farey sequence for order 1 through 11:\n%(%s\n%)", iota(1, 12).map!farey); writeln("\nFarey sequence fractions, 100 to 1000 by hundreds:\n", iota(100, 1_001, 100).map!(i => i.farey.walkLength)); }
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®)
#J
J
fairshare=: [ | [: +/"1 #.inv 2 3 5 11 fairshare"0 1/i.25 0 1 1 0 1 0 0 1 1 0 0 1 0 1 1 0 1 0 0 1 0 1 1 0 0 0 1 2 1 2 0 2 0 1 1 2 0 2 0 1 0 1 2 2 0 1 0 1 2 1 0 1 2 3 4 1 2 3 4 0 2 3 4 0 1 3 4 0 1 2 4 0 1 2 3 0 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 0 2 3 4 NB. In the 1st 50000 how many turns does each get? answered: <@({.,#)/.~"1 ] 2 3 5 11 fairshare"0 1/i.50000 +-------+-------+-------+-------+-------+------+------+------+------+------+-------+ |0 25000|1 25000| | | | | | | | | | +-------+-------+-------+-------+-------+------+------+------+------+------+-------+ |0 16667|1 16667|2 16666| | | | | | | | | +-------+-------+-------+-------+-------+------+------+------+------+------+-------+ |0 10000|1 10000|2 10000|3 10000|4 10000| | | | | | | +-------+-------+-------+-------+-------+------+------+------+------+------+-------+ |0 4545 |1 4545 |2 4545 |3 4545 |4 4546 |5 4546|6 4546|7 4546|8 4546|9 4545|10 4545| +-------+-------+-------+-------+-------+------+------+------+------+------+-------+
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®)
#Java
Java
  import java.util.ArrayList; import java.util.Arrays; import java.util.List;   public class FairshareBetweenTwoAndMore {   public static void main(String[] args) { for ( int base : Arrays.asList(2, 3, 5, 11) ) { System.out.printf("Base %d = %s%n", base, thueMorseSequence(25, base)); } }   private static List<Integer> thueMorseSequence(int terms, int base) { List<Integer> sequence = new ArrayList<Integer>(); for ( int i = 0 ; i < terms ; i++ ) { int sum = 0; int n = i; while ( n > 0 ) { // Compute the digit sum sum += n % base; n /= base; } // Compute the digit sum module base. sequence.add(sum % base); } return sequence; }   }  
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)
#J
J
faulhaberTriangle=: ([: %. [: x: (1 _2 (p.) 2 | +/~) * >:/~ * (!~/~ >:))@:i. faulhaberTriangle 10 1 0 0 0 0 0 0 0 0 0 1r2 1r2 0 0 0 0 0 0 0 0 1r6 1r2 1r3 0 0 0 0 0 0 0 0 1r4 1r2 1r4 0 0 0 0 0 0 _1r30 0 1r3 1r2 1r5 0 0 0 0 0 0 _1r12 0 5r12 1r2 1r6 0 0 0 0 1r42 0 _1r6 0 1r2 1r2 1r7 0 0 0 0 1r12 0 _7r24 0 7r12 1r2 1r8 0 0 _1r30 0 2r9 0 _7r15 0 2r3 1r2 1r9 0 0 _3r20 0 1r2 0 _7r10 0 3r4 1r2 1r10 NB.-------------------------------------------------------------- NB. matrix inverse (%.) of the extended precision (x:) product of (!~/~ >:)@:i. 5 NB. Pascal's triangle 1 1 0 0 0 1 2 1 0 0 1 3 3 1 0 1 4 6 4 1 1 5 10 10 5 NB. second task in progress (>:/~)@: i. 5 NB. lower triangle 1 0 0 0 0 1 1 0 0 0 1 1 1 0 0 1 1 1 1 0 1 1 1 1 1 (1 _2 p. (2 | +/~))@:i. 5 NB. 1 + (-2) * (parity table) 1 _1 1 _1 1 _1 1 _1 1 _1 1 _1 1 _1 1 _1 1 _1 1 _1 1 _1 1 _1 1
http://rosettacode.org/wiki/Faulhaber%27s_formula
Faulhaber's formula
In mathematics,   Faulhaber's formula,   named after Johann Faulhaber,   expresses the sum of the p-th powers of the first n positive integers as a (p + 1)th-degree polynomial function of n,   the coefficients involving Bernoulli numbers. Task Generate the first 10 closed-form expressions, starting with p = 0. Related tasks   Bernoulli numbers.   evaluate binomial coefficients. See also   The Wikipedia entry:   Faulhaber's formula.   The Wikipedia entry:   Bernoulli numbers.   The Wikipedia entry:   binomial coefficients.
#Java
Java
import java.util.Arrays; import java.util.stream.IntStream;   public 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);   public 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; }   public Frac plus(Frac rhs) { return new Frac(num * rhs.denom + denom * rhs.num, rhs.denom * denom); }   public Frac unaryMinus() { return new Frac(-num, denom); }   public Frac minus(Frac rhs) { return this.plus(rhs.unaryMinus()); }   public Frac times(Frac rhs) { return new Frac(this.num * rhs.num, this.denom * rhs.denom); }   @Override public int compareTo(Frac o) { double diff = toDouble() - o.toDouble(); return Double.compare(diff, 0.0); }   @Override public boolean equals(Object obj) { return null != obj && obj instanceof Frac && this.compareTo((Frac) obj) == 0; }   @Override public 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].minus(a[j]).times(new Frac(j, 1)); } } // returns 'first' Bernoulli number if (n != 1) return a[0]; return a[0].unaryMinus(); }   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) { System.out.printf("%d : ", p); Frac q = new Frac(1, p + 1); int sign = -1; for (int j = 0; j <= p; ++j) { sign *= -1; Frac coeff = q.times(new Frac(sign, 1)).times(new Frac(binomial(p + 1, j), 1)).times(bernoulli(j)); if (Frac.ZERO.equals(coeff)) continue; if (j == 0) { if (!Frac.ONE.equals(coeff)) { if (Frac.ONE.unaryMinus().equals(coeff)) { System.out.print("-"); } else { System.out.print(coeff); } } } else { if (Frac.ONE.equals(coeff)) { System.out.print(" + "); } else if (Frac.ONE.unaryMinus().equals(coeff)) { System.out.print(" - "); } else if (coeff.compareTo(Frac.ZERO) > 0) { System.out.printf(" + %s", coeff); } else { System.out.printf(" - %s", coeff.unaryMinus()); } } int pwr = p + 1 - j; if (pwr > 1) System.out.printf("n^%d", pwr); else System.out.print("n"); } System.out.println(); }   public 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
#zkl
zkl
fermatsW:=[0..].tweak(fcn(n){ BI(2).pow(BI(2).pow(n)) + 1 }); println("First 10 Fermat numbers:"); foreach n in (10){ println("F",n,": ",fermatsW.next()) }
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
#C.23
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text;   namespace Fibonacci { class Program { static void Main(string[] args) { PrintNumberSequence("Fibonacci", GetNnacciNumbers(2, 10)); PrintNumberSequence("Lucas", GetLucasNumbers(10)); PrintNumberSequence("Tribonacci", GetNnacciNumbers(3, 10)); PrintNumberSequence("Tetranacci", GetNnacciNumbers(4, 10)); Console.ReadKey(); }   private static IList<ulong> GetLucasNumbers(int length) { IList<ulong> seedSequence = new List<ulong>() { 2, 1 }; return GetFibLikeSequence(seedSequence, length); }   private static IList<ulong> GetNnacciNumbers(int seedLength, int length) { return GetFibLikeSequence(GetNacciSeed(seedLength), length); }   private static IList<ulong> GetNacciSeed(int seedLength) { IList<ulong> seedSquence = new List<ulong>() { 1 };   for (uint i = 0; i < seedLength - 1; i++) { seedSquence.Add((ulong)Math.Pow(2, i)); }   return seedSquence; }   private static IList<ulong> GetFibLikeSequence(IList<ulong> seedSequence, int length) { IList<ulong> sequence = new List<ulong>();   int count = seedSequence.Count();   if (length <= count) { sequence = seedSequence.Take((int)length).ToList(); } else { sequence = seedSequence;   for (int i = count; i < length; i++) { ulong num = 0;   for (int j = 0; j < count; j++) { num += sequence[sequence.Count - 1 - j]; }   sequence.Add(num); } }   return sequence; }   private static void PrintNumberSequence(string Title, IList<ulong> numbersequence) { StringBuilder output = new StringBuilder(Title).Append(" ");   foreach (long item in numbersequence) { output.AppendFormat("{0}, ", item); }   Console.WriteLine(output.ToString()); } } }
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#TUSCRIPT
TUSCRIPT
  $$ MODE TUSCRIPT file="rosetta.txt" ERROR/STOP OPEN (file,READ,-std-) modified=MODIFIED (file) PRINT "file ",file," last modified: ",modified  
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#UNIX_Shell
UNIX Shell
T=`stat -c %Y $F`
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#Ursa
Ursa
decl java.util.Date d decl file f   f.open "example.txt" d.setTime (f.lastmodified) out d endl console   f.setlastmodified 10
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.)
#Wren
Wren
import "graphics" for Canvas, Color import "dome" for Window   class FibonacciWordFractal { construct new(width, height, n) { Window.title = "Fibonacci Word Fractal" Window.resize(width, height) Canvas.resize(width, height) _fore = Color.green _wordFractal = wordFractal(n) }   init() { drawWordFractal(20, 20, 1, 0) }   wordFractal(i) { if (i < 2) return (i == 1) ? "1" : "" var f1 = "1" var f2 = "0" for (j in i-2...0) { var tmp = f2 f2 = f2 + f1 f1 = tmp } return f2 }   drawWordFractal(x, y, dx, dy) { for (i in 0..._wordFractal.count) { Canvas.line(x, y, x + dx, y + dy, _fore) x = x + dx y = y + dy if (_wordFractal[i] == "0") { var tx = dx dx = (i % 2 == 0) ? -dy : dy dy = (i % 2 == 0) ? tx : - tx } } }   update() {}   draw(alpha) {} }   var Game = FibonacciWordFractal.new(450, 620, 23)
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
#Picat
Picat
find_common_directory_path(Dirs) = Path => maxof( (common_prefix(Dirs, Path,Len), append(_,"/",Path)), Len).   % % Find a common prefix of all lists/strings in Ls. % Using append/3. % common_prefix(Ls, Prefix,Len) => foreach(L in Ls) append(Prefix,_,L) end, Len = Prefix.length.
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
#PicoLisp
PicoLisp
(de commonPath (Lst Chr) (glue Chr (make (apply find (mapcar '((L) (split (chop L) Chr)) Lst) '(@ (or (pass <>) (nil (link (next))))) ) ) ) )
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.
#E
E
pragma.enable("accumulator") accum [] for x ? (x %% 2 <=> 0) in [1,2,3,4,5,6,7,8,9,10] { _.with(x) }
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.
#Rust
Rust
fn recurse(n: i32) { println!("depth: {}", n); recurse(n + 1) }   fn main() { 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.
#Sather
Sather
class MAIN is attr r:INT; recurse is r := r + 1; #OUT + r + "\n"; recurse; end; main is r := 0; recurse; end; 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.
#Scala
Scala
def recurseTest(i:Int):Unit={ try{ recurseTest(i+1) } catch { case e:java.lang.StackOverflowError => println("Recursion depth on this system is " + i + ".") } } recurseTest(0)
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) The   FizzBuzz   problem was presented as the lowest level of comprehension required to illustrate adequacy. Also see   (a blog)   dont-overthink-fizzbuzz   (a blog)   fizzbuzz-the-programmers-stairway-to-heaven
#Haskell
Haskell
fizzbuzz :: Int -> String fizzbuzz x | f 15 = "FizzBuzz" | f 3 = "Fizz" | f 5 = "Buzz" | otherwise = show x where f = (0 ==) . rem x   main :: IO () main = mapM_ (putStrLn . fizzbuzz) [1 .. 100]
http://rosettacode.org/wiki/File_size
File size
Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
#PHP
PHP
<?php echo filesize('input.txt'), "\n"; echo filesize('/input.txt'), "\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.
#PicoLisp
PicoLisp
(println (car (info "input.txt"))) (println (car (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.
#Pike
Pike
import Stdio;   int main(){ write(file_size("input.txt") + "\n"); write(file_size("/input.txt") + "\n"); }
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.
#GUISS
GUISS
Start,My Documents,Rightclick:input.txt,Copy,Menu,Edit,Paste, Rightclick:Copy of input.txt,Rename,Type:output.txt[enter]
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.
#Haskell
Haskell
main = readFile "input.txt" >>= writeFile "output.txt"
http://rosettacode.org/wiki/Fibonacci_word
Fibonacci word
The   Fibonacci Word   may be created in a manner analogous to the   Fibonacci Sequence   as described here: Define   F_Word1   as   1 Define   F_Word2   as   0 Form     F_Word3   as   F_Word2     concatenated with   F_Word1   i.e.:   01 Form     F_Wordn   as   F_Wordn-1   concatenated with   F_wordn-2 Task Perform the above steps for     n = 37. You may display the first few but not the larger values of   n. {Doing so will get the task's author into trouble with them what be (again!).} Instead, create a table for   F_Words   1   to   37   which shows:   The number of characters in the word   The word's Entropy Related tasks   Fibonacci word/fractal   Entropy   Entropy/Narcissist
#Kotlin
Kotlin
// version 1.0.6   fun fibWord(n: Int): String { if (n < 1) throw IllegalArgumentException("Argument can't be less than 1") if (n == 1) return "1" val words = Array(n){ "" } words[0] = "1" words[1] = "0" for (i in 2 until n) words[i] = words[i - 1] + words[i - 2] return words[n - 1] }   fun log2(d: Double) = Math.log(d) / Math.log(2.0)   fun shannon(s: String): Double { if (s.length <= 1) return 0.0 val count0 = s.count { it == '0' } val count1 = s.length - count0 val nn = s.length.toDouble() return -(count0 / nn * log2(count0 / nn) + count1 / nn * log2(count1 / nn)) }   fun main(args: Array<String>) { println("N Length Entropy Word") println("-- -------- ------------------ ----------------------------------") for (i in 1..37) { val s = fibWord(i) print(String.format("%2d  %8d  %18.16f", i, s.length, shannon(s))) if (i < 10) println(" $s") else 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.
#OCaml
OCaml
  (* This program reads from the standard input and writes to standard output. * Examples of use: * $ ocaml fasta.ml < fasta_file.txt * $ ocaml fasta.ml < fasta_file.txt > my_result.txt * * The FASTA file is assumed to have a specific format, where the first line * contains a label in the form of '>blablabla', i.e. with a '>' as the first * character. *)   let labelstart = '>'   let is_label s = s.[0] = labelstart let get_label s = String.sub s 1 (String.length s - 1)   let read_in channel = input_line channel |> String.trim   let print_fasta chan = let rec doloop currlabel line = if is_label line then begin if currlabel <> "" then print_newline (); let newlabel = get_label line in print_string (newlabel ^ ": "); doloop newlabel (read_in chan) end else begin print_string line; doloop currlabel (read_in chan) end in try match read_in chan with | line when is_label line -> doloop "" line | _ -> failwith "Badly formatted FASTA file?" with End_of_file -> print_newline ()     let () = print_fasta stdin  
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.
#Pascal
Pascal
  program FASTA_Format; // FPC 3.0.2 var InF, OutF: Text; ch: char; First: Boolean=True; InDef: Boolean=False;   begin Assign(InF,''); Reset(InF); Assign(OutF,''); Rewrite(OutF); While Not Eof(InF) do begin Read(InF,ch); Case Ch of '>': begin if Not(First) then Write(OutF,#13#10) else First:=False; InDef:=true; end; #13: Begin if InDef then begin InDef:=false; Write(OutF,': '); end; Ch:=#0; end; #10: ch:=#0; else Write(OutF,Ch); end; end; Close(OutF); Close(InF); end.  
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: Fn = Fn+2 - Fn+1, if n<0 support for negative     n     in the solution is optional. Related tasks   Fibonacci n-step number sequences‎   Leonardo numbers References   Wikipedia, Fibonacci number   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#360_Assembly
360 Assembly
* Fibonacci sequence 05/11/2014 * integer (31 bits) = 10 decimals -> max fibo(46) FIBONACC CSECT USING FIBONACC,R12 base register SAVEAREA B STM-SAVEAREA(R15) skip savearea DC 17F'0' savearea DC CL8'FIBONACC' eyecatcher STM STM R14,R12,12(R13) save previous context ST R13,4(R15) link backward ST R15,8(R13) link forward LR R12,R15 set addressability * ---- LA R1,0 f(n-2)=0 LA R2,1 f(n-1)=1 LA R4,2 n=2 LA R6,1 step LH R7,NN limit LOOP EQU * for n=2 to nn LR R3,R2 f(n)=f(n-1) AR R3,R1 f(n)=f(n-1)+f(n-2) CVD R4,PW n convert binary to packed (PL8) UNPK ZW,PW packed (PL8) to zoned (ZL16) MVC CW,ZW zoned (ZL16) to char (CL16) OI CW+L'CW-1,X'F0' zap sign MVC WTOBUF+5(2),CW+14 output CVD R3,PW f(n) binary to packed decimal (PL8) MVC ZN,EM load mask ED ZN,PW packed dec (PL8) to char (CL20) MVC WTOBUF+9(14),ZN+6 output WTO MF=(E,WTOMSG) write buffer LR R1,R2 f(n-2)=f(n-1) LR R2,R3 f(n-1)=f(n) BXLE R4,R6,LOOP endfor n * ---- LM R14,R12,12(R13) restore previous savearea pointer XR R15,R15 return code set to 0 BR R14 return to caller * ---- DATA NN DC H'46' nn max n PW DS PL8 15num ZW DS ZL16 CW DS CL16 ZN DS CL20 * ' b 0 0 0 , 0 0 0 , 0 0 0 , 0 0 0 , 0 0 0' 15num EM DC XL20'402020206B2020206B2020206B2020206B202120' mask WTOMSG DS 0F DC H'80',XL2'0000' * fibo(46)=1836311903 WTOBUF DC CL80'fibo(12)=1234567890' REGEQU END FIBONACC
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
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program factorst64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM64.inc"   .equ CHARPOS, '@'   /*******************************************/ /* Initialized data */ /*******************************************/ .data szMessDeb: .ascii "Factors of : @ are : \n" szMessFactor: .asciz "@ \n" szCarriageReturn: .asciz "\n" /*******************************************/ /* UnInitialized data */ /*******************************************/ .bss sZoneConversion: .skip 100 /*******************************************/ /* code section */ /*******************************************/ .text .global main main: // entry of program   mov x0,#100 bl factors mov x0,#97 bl factors ldr x0,qNumber bl factors   100: // standard end of the program mov x0, #0 // return code mov x8, #EXIT // request to exit program svc 0 // perform the system call   qNumber: .quad 32767 qAdrszCarriageReturn: .quad szCarriageReturn /******************************************************************/ /* calcul factors of number */ /******************************************************************/ /* x0 contains the number to factorize */ factors: stp x1,lr,[sp,-16]! // save registers stp x2,x3,[sp,-16]! // save registers   mov x5,x0 // limit calcul ldr x1,qAdrsZoneConversion // conversion register in decimal string bl conversion10S ldr x0,qAdrszMessDeb // display message ldr x1,qAdrsZoneConversion bl strInsertAtChar bl affichageMess mov x6,#1 // counter loop 1: // loop udiv x0,x5,x6 // division msub x3,x0,x6,x5 // compute remainder cbnz x3,2f // remainder not = zero -> loop // display result if yes mov x0,x6 ldr x1,qAdrsZoneConversion bl conversion10S ldr x0,qAdrszMessFactor // display message ldr x1,qAdrsZoneConversion bl strInsertAtChar bl affichageMess 2: add x6,x6,#1 // add 1 to loop counter cmp x6,x5 // <= number ? ble 1b // yes loop 100: ldp x2,x3,[sp],16 // restaur 2 registers ldp x1,lr,[sp],16 // restaur 2 registers ret   qAdrszMessDeb: .quad szMessDeb qAdrszMessFactor: .quad szMessFactor qAdrsZoneConversion: .quad sZoneConversion /******************************************************************/ /* insert string at character insertion */ /******************************************************************/ /* x0 contains the address of string 1 */ /* x1 contains the address of insertion string */ /* x0 return the address of new string on the heap */ /* or -1 if error */ strInsertAtChar: stp x2,lr,[sp,-16]! // save registers stp x3,x4,[sp,-16]! // save registers stp x5,x6,[sp,-16]! // save registers stp x7,x8,[sp,-16]! // save registers mov x3,#0 // length counter 1: // compute length of string 1 ldrb w4,[x0,x3] cmp w4,#0 cinc x3,x3,ne // increment to one if not equal bne 1b // loop if not equal mov x5,#0 // length counter insertion string 2: // compute length to insertion string ldrb w4,[x1,x5] cmp x4,#0 cinc x5,x5,ne // increment to one if not equal bne 2b // and loop cmp x5,#0 beq 99f // string empty -> error add x3,x3,x5 // add 2 length add x3,x3,#1 // +1 for final zero mov x6,x0 // save address string 1 mov x0,#0 // allocation place heap mov x8,BRK // call system 'brk' svc #0 mov x5,x0 // save address heap for output string add x0,x0,x3 // reservation place x3 length mov x8,BRK // call system 'brk' svc #0 cmp x0,#-1 // allocation error beq 99f   mov x2,0 mov x4,0 3: // loop copy string begin ldrb w3,[x6,x2] cmp w3,0 beq 99f cmp w3,CHARPOS // insertion character ? beq 5f // yes strb w3,[x5,x4] // no store character in output string add x2,x2,1 add x4,x4,1 b 3b // and loop 5: // x4 contains position insertion add x8,x4,1 // init index character output string // at position insertion + one mov x3,#0 // index load characters insertion string 6: ldrb w0,[x1,x3] // load characters insertion string cmp w0,#0 // end string ? beq 7f // yes strb w0,[x5,x4] // store in output string add x3,x3,#1 // increment index add x4,x4,#1 // increment output index b 6b // and loop 7: // loop copy end string ldrb w0,[x6,x8] // load other character string 1 strb w0,[x5,x4] // store in output string cmp x0,#0 // end string 1 ? beq 8f // yes -> end add x4,x4,#1 // increment output index add x8,x8,#1 // increment index b 7b // and loop 8: mov x0,x5 // return output string address b 100f 99: // error mov x0,#-1 100: ldp x7,x8,[sp],16 // restaur 2 registers ldp x5,x6,[sp],16 // restaur 2 registers ldp x3,x4,[sp],16 // restaur 2 registers ldp x2,lr,[sp],16 // restaur 2 registers ret   /********************************************************/ /* File Include fonctions */ /********************************************************/ /* for this file see task include a file in language AArch64 assembly */ .include "../includeARM64.inc"    
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.
#C.2B.2B
C++
#include <complex> #include <iostream> #include <valarray>   const double PI = 3.141592653589793238460;   typedef std::complex<double> Complex; typedef std::valarray<Complex> CArray;   // Cooley–Tukey FFT (in-place, divide-and-conquer) // Higher memory requirements and redundancy although more intuitive void fft(CArray& x) { const size_t N = x.size(); if (N <= 1) return;   // divide CArray even = x[std::slice(0, N/2, 2)]; CArray odd = x[std::slice(1, N/2, 2)];   // conquer fft(even); fft(odd);   // combine for (size_t k = 0; k < N/2; ++k) { Complex t = std::polar(1.0, -2 * PI * k / N) * odd[k]; x[k ] = even[k] + t; x[k+N/2] = even[k] - t; } }   // Cooley-Tukey FFT (in-place, breadth-first, decimation-in-frequency) // Better optimized but less intuitive // !!! Warning : in some cases this code make result different from not optimased version above (need to fix bug) // The bug is now fixed @2017/05/30 void fft(CArray &x) { // DFT unsigned int N = x.size(), k = N, n; double thetaT = 3.14159265358979323846264338328L / N; Complex phiT = Complex(cos(thetaT), -sin(thetaT)), T; while (k > 1) { n = k; k >>= 1; phiT = phiT * phiT; T = 1.0L; for (unsigned int l = 0; l < k; l++) { for (unsigned int a = l; a < N; a += n) { unsigned int b = a + k; Complex t = x[a] - x[b]; x[a] += x[b]; x[b] = t * T; } T *= phiT; } } // Decimate unsigned int m = (unsigned int)log2(N); for (unsigned int a = 0; a < N; a++) { unsigned int b = a; // Reverse bits b = (((b & 0xaaaaaaaa) >> 1) | ((b & 0x55555555) << 1)); b = (((b & 0xcccccccc) >> 2) | ((b & 0x33333333) << 2)); b = (((b & 0xf0f0f0f0) >> 4) | ((b & 0x0f0f0f0f) << 4)); b = (((b & 0xff00ff00) >> 8) | ((b & 0x00ff00ff) << 8)); b = ((b >> 16) | (b << 16)) >> (32 - m); if (b > a) { Complex t = x[a]; x[a] = x[b]; x[b] = t; } } //// Normalize (This section make it not working correctly) //Complex f = 1.0 / sqrt(N); //for (unsigned int i = 0; i < N; i++) // x[i] *= f; }   // inverse fft (in-place) void ifft(CArray& x) { // conjugate the complex numbers x = x.apply(std::conj);   // forward fft fft( x );   // conjugate the complex numbers again x = x.apply(std::conj);   // scale the numbers x /= x.size(); }   int main() { const Complex test[] = { 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0 }; CArray data(test, 8);   // forward fft fft(data);   std::cout << "fft" << std::endl; for (int i = 0; i < 8; ++i) { std::cout << data[i] << std::endl; }   // inverse fft ifft(data);   std::cout << std::endl << "ifft" << std::endl; for (int i = 0; i < 8; ++i) { std::cout << data[i] << std::endl; } return 0; }
http://rosettacode.org/wiki/Factors_of_a_Mersenne_number
Factors of a Mersenne number
A Mersenne number is a number in the form of 2P-1. If P is prime, the Mersenne number may be a Mersenne prime (if P is not prime, the Mersenne number is also not prime). In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before starting a, potentially lengthy, Lucas-Lehmer test. There are very efficient algorithms for determining if a number divides 2P-1 (or equivalently, if 2P mod (the number) = 1). Some languages already have built-in implementations of this exponent-and-mod operation (called modPow or similar). The following is how to implement this modPow yourself: For example, let's compute 223 mod 47. Convert the exponent 23 to binary, you get 10111. Starting with square = 1, repeatedly square it. Remove the top bit of the exponent, and if it's 1 multiply square by the base of the exponentiation (2), then compute square modulo 47. Use the result of the modulo from the last step as the initial value of square in the next step: remove optional square top bit multiply by 2 mod 47 ──────────── ─────── ───────────── ────── 1*1 = 1 1 0111 1*2 = 2 2 2*2 = 4 0 111 no 4 4*4 = 16 1 11 16*2 = 32 32 32*32 = 1024 1 1 1024*2 = 2048 27 27*27 = 729 1 729*2 = 1458 1 Since 223 mod 47 = 1, 47 is a factor of 2P-1. (To see this, subtract 1 from both sides: 223-1 = 0 mod 47.) Since we've shown that 47 is a factor, 223-1 is not prime. Further properties of Mersenne numbers allow us to refine the process even more. Any factor q of 2P-1 must be of the form 2kP+1, k being a positive integer or zero. Furthermore, q must be 1 or 7 mod 8. Finally any potential factor q must be prime. As in other trial division algorithms, the algorithm stops when 2kP+1 > sqrt(N). These primality tests only work on Mersenne numbers where P is prime. For example, M4=15 yields no factors using these techniques, but factors into 3 and 5, neither of which fit 2kP+1. Task Using the above method find a factor of 2929-1 (aka M929) Related tasks   count in factors   prime decomposition   factors of an integer   Sieve of Eratosthenes   primality by trial division   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division See also   Computers in 1948: 2127 - 1       (Note:   This video is no longer available because the YouTube account associated with this video has been terminated.)
#C
C
int isPrime(int n){ if (n%2==0) return n==2; if (n%3==0) return n==3; int d=5; while(d*d<=n){ if(n%d==0) return 0; d+=2; if(n%d==0) return 0; d+=4;} return 1;}   main() {int i,d,p,r,q=929; if (!isPrime(q)) return 1; r=q; while(r>0) r<<=1; d=2*q+1; do { for(p=r, i= 1; p; p<<= 1){ i=((long long)i * i) % d; if (p < 0) i *= 2; if (i > d) i -= d;} if (i != 1) d += 2*q; else break; } while(1); printf("2^%d - 1 = 0 (mod %d)\n", q, d);}
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
#Delphi
Delphi
  (define distinct-divisors (compose make-set prime-factors))   ;; euler totient : Φ : n / product(p_i) * product (p_i - 1) ;; # of divisors <= n   (define (Φ n) (let ((pdiv (distinct-divisors n))) (/ (* n (for/product ((p pdiv)) (1- p))) (for/product ((p pdiv)) p))))   ;; farey-sequence length |Fn| = 1 + sigma (m=1..) Φ(m)   (define ( F-length n) (1+ (for/sum ((m (1+ n))) (Φ m))))   ;; farey sequence ;; apply the definition : O(n^2) (define (Farey N) (set! N (1+ N)) (make-set (for*/list ((n N) (d (in-range n N))) (rational n d))))    
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®)
#JavaScript
JavaScript
(() => { 'use strict';   // thueMorse :: Int -> [Int] const thueMorse = base => // Thue-Morse sequence for a given base fmapGen(baseDigitsSumModBase(base))( enumFrom(0) )   // baseDigitsSumModBase :: Int -> Int -> Int const baseDigitsSumModBase = base => // For any integer n, the sum of its digits // in a given base, modulo that base. n => sum(unfoldl( x => 0 < x ? ( Just(quotRem(x)(base)) ) : Nothing() )(n)) % base     // ------------------------TEST------------------------ const main = () => console.log( fTable( 'First 25 fairshare terms for a given number of players:' )(str)( xs => '[' + map( compose(justifyRight(2)(' '), str) )(xs) + ' ]' )( compose(take(25), thueMorse) )([2, 3, 5, 11]) );   // -----------------GENERIC FUNCTIONS------------------   // Just :: a -> Maybe a const Just = x => ({ type: 'Maybe', Nothing: false, Just: x });   // Nothing :: Maybe a const Nothing = () => ({ type: 'Maybe', Nothing: true, });   // Tuple (,) :: a -> b -> (a, b) const Tuple = a => b => ({ type: 'Tuple', '0': a, '1': b, length: 2 });   // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c const compose = (...fs) => x => fs.reduceRight((a, f) => f(a), x);   // enumFrom :: Enum a => a -> [a] function* enumFrom(x) { // A non-finite succession of enumerable // values, starting with the value x. let v = x; while (true) { yield v; v = 1 + v; } }   // fTable :: String -> (a -> String) -> (b -> String) // -> (a -> b) -> [a] -> String const fTable = s => xShow => fxShow => f => xs => { // Heading -> x display function -> // fx display function -> // f -> values -> tabular string const ys = xs.map(xShow), w = Math.max(...ys.map(length)); return s + '\n' + zipWith( a => b => a.padStart(w, ' ') + ' -> ' + b )(ys)( xs.map(x => fxShow(f(x))) ).join('\n'); };   // fmapGen <$> :: (a -> b) -> Gen [a] -> Gen [b] const fmapGen = f => function*(gen) { let v = take(1)(gen); while (0 < v.length) { yield(f(v[0])) v = take(1)(gen) } };   // justifyRight :: Int -> Char -> String -> String const justifyRight = n => // The string s, preceded by enough padding (with // the character c) to reach the string length n. c => s => n > s.length ? ( s.padStart(n, c) ) : s;   // length :: [a] -> Int const length = xs => // Returns Infinity over objects without finite // length. This enables zip and zipWith to choose // the shorter argument when one is non-finite, // like cycle, repeat etc (Array.isArray(xs) || 'string' === typeof xs) ? ( xs.length ) : Infinity;   // map :: (a -> b) -> [a] -> [b] const map = f => // The list obtained by applying f to each element of xs. // (The image of xs under f). xs => (Array.isArray(xs) ? ( xs ) : xs.split('')).map(f);   // quotRem :: Int -> Int -> (Int, Int) const quotRem = m => n => Tuple(Math.floor(m / n))( m % n );   // str :: a -> String const str = x => x.toString();   // sum :: [Num] -> Num const sum = xs => // The numeric sum of all values in xs. xs.reduce((a, x) => a + x, 0);   // take :: Int -> [a] -> [a] // take :: Int -> String -> String const take = n => // The first n elements of a list, // string of characters, or stream. xs => 'GeneratorFunction' !== xs .constructor.constructor.name ? ( xs.slice(0, n) ) : [].concat.apply([], Array.from({ length: n }, () => { const x = xs.next(); return x.done ? [] : [x.value]; }));     // unfoldl :: (b -> Maybe (b, a)) -> b -> [a] const unfoldl = f => v => { // Dual to reduce or foldl. // Where these reduce a list to a summary value, unfoldl // builds a list from a seed value. // Where f returns Just(a, b), a is appended to the list, // and the residual b is used as the argument for the next // application of f. // Where f returns Nothing, the completed list is returned. let xr = [v, v], xs = []; while (true) { const mb = f(xr[0]); if (mb.Nothing) { return xs } else { xr = mb.Just; xs = [xr[1]].concat(xs); } } };   // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] const zipWith = f => xs => ys => { const lng = Math.min(length(xs), length(ys)), vs = take(lng)(ys); return take(lng)(xs) .map((x, i) => f(x)(vs[i])); };   // MAIN --- return main(); })();
http://rosettacode.org/wiki/Faulhaber%27s_triangle
Faulhaber's triangle
Named after Johann Faulhaber, the rows of Faulhaber's triangle are the coefficients of polynomials that represent sums of integer powers, which are extracted from Faulhaber's formula: ∑ k = 1 n k p = 1 p + 1 ∑ j = 0 p ( p + 1 j ) B j n p + 1 − j {\displaystyle \sum _{k=1}^{n}k^{p}={1 \over p+1}\sum _{j=0}^{p}{p+1 \choose j}B_{j}n^{p+1-j}} where B n {\displaystyle B_{n}} is the nth-Bernoulli number. The first 5 rows of Faulhaber's triangle, are: 1 1/2 1/2 1/6 1/2 1/3 0 1/4 1/2 1/4 -1/30 0 1/3 1/2 1/5 Using the third row of the triangle, we have: ∑ k = 1 n k 2 = 1 6 n + 1 2 n 2 + 1 3 n 3 {\displaystyle \sum _{k=1}^{n}k^{2}={1 \over 6}n+{1 \over 2}n^{2}+{1 \over 3}n^{3}} Task show the first 10 rows of Faulhaber's triangle. using the 18th row of Faulhaber's triangle, compute the sum: ∑ k = 1 1000 k 17 {\displaystyle \sum _{k=1}^{1000}k^{17}} (extra credit). See also Bernoulli numbers Evaluate binomial coefficients Faulhaber's formula (Wikipedia) Faulhaber's triangle (PDF)
#Java
Java
import java.math.BigDecimal; import java.math.MathContext; import java.util.Arrays; import java.util.stream.LongStream;   public 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);   public 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; }   public Frac plus(Frac rhs) { return new Frac(num * rhs.denom + denom * rhs.num, rhs.denom * denom); }   public Frac unaryMinus() { return new Frac(-num, denom); }   public Frac minus(Frac rhs) { return this.plus(rhs.unaryMinus()); }   public Frac times(Frac rhs) { return new Frac(this.num * rhs.num, this.denom * rhs.denom); }   @Override public int compareTo(Frac o) { double diff = toDouble() - o.toDouble(); return Double.compare(diff, 0.0); }   @Override public boolean equals(Object obj) { return null != obj && obj instanceof Frac && this.compareTo((Frac) obj) == 0; }   @Override public String toString() { if (denom == 1) { return Long.toString(num); } return String.format("%d/%d", num, denom); }   public double toDouble() { return (double) num / denom; }   public 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].minus(a[j]).times(new Frac(j, 1)); } } // returns 'first' Bernoulli number if (n != 1) return a[0]; return a[0].unaryMinus(); }   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.times(new Frac(sign, 1)).times(new Frac(binomial(p + 1, j), 1)).times(bernoulli(j)); } return coeffs; }   public static void main(String[] args) { for (int i = 0; i <= 9; ++i) { Frac[] coeffs = faulhaberTriangle(i); for (Frac coeff : coeffs) { System.out.printf("%5s ", coeff); } System.out.println(); } System.out.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.multiply(nn); sum = sum.add(np.multiply(c.toBigDecimal())); } System.out.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.
#Julia
Julia
module Faulhaber   function bernoulli(n::Integer) n ≥ 0 || throw(DomainError(n, "n must be a positive-or-0 number")) a = fill(0 // 1, n + 1) for m in 1:n a[m] = 1 // (m + 1) for j in m:-1:2 a[j - 1] = (a[j - 1] - a[j]) * j end end return ifelse(n != 1, a[1], -a[1]) end   const _exponents = collect(Char, "⁰¹²³⁴⁵⁶⁷⁸⁹") toexponent(n) = join(_exponents[reverse(digits(n)) .+ 1])   function formula(p::Integer) print(p, ": ") q = 1 // (p + 1) s = -1 for j in 0:p s *= -1 coeff = q * s * binomial(p + 1, j) * bernoulli(j) iszero(coeff) && continue if iszero(j) print(coeff == 1 ? "" : coeff == -1 ? "-" : "$coeff") else print(coeff == 1 ? " + " : coeff == -1 ? " - " : coeff > 0 ? " + $coeff " : " - $(-coeff) ") end pwr = p + 1 - j if pwr > 1 print("n", toexponent(pwr)) else print("n") end end println() end   end # module Faulhaber
http://rosettacode.org/wiki/Fibonacci_n-step_number_sequences
Fibonacci n-step number sequences
These number series are an expansion of the ordinary Fibonacci sequence where: For n = 2 {\displaystyle n=2} we have the Fibonacci sequence; with initial values [ 1 , 1 ] {\displaystyle [1,1]} and F k 2 = F k − 1 2 + F k − 2 2 {\displaystyle F_{k}^{2}=F_{k-1}^{2}+F_{k-2}^{2}} For n = 3 {\displaystyle n=3} we have the tribonacci sequence; with initial values [ 1 , 1 , 2 ] {\displaystyle [1,1,2]} and F k 3 = F k − 1 3 + F k − 2 3 + F k − 3 3 {\displaystyle F_{k}^{3}=F_{k-1}^{3}+F_{k-2}^{3}+F_{k-3}^{3}} For n = 4 {\displaystyle n=4} we have the tetranacci sequence; with initial values [ 1 , 1 , 2 , 4 ] {\displaystyle [1,1,2,4]} and F k 4 = F k − 1 4 + F k − 2 4 + F k − 3 4 + F k − 4 4 {\displaystyle F_{k}^{4}=F_{k-1}^{4}+F_{k-2}^{4}+F_{k-3}^{4}+F_{k-4}^{4}} ... For general n > 2 {\displaystyle n>2} we have the Fibonacci n {\displaystyle n} -step sequence - F k n {\displaystyle F_{k}^{n}} ; with initial values of the first n {\displaystyle n} values of the ( n − 1 ) {\displaystyle (n-1)} 'th Fibonacci n {\displaystyle n} -step sequence F k n − 1 {\displaystyle F_{k}^{n-1}} ; and k {\displaystyle k} 'th value of this n {\displaystyle n} 'th sequence being F k n = ∑ i = 1 ( n ) F k − i ( n ) {\displaystyle F_{k}^{n}=\sum _{i=1}^{(n)}{F_{k-i}^{(n)}}} For small values of n {\displaystyle n} , Greek numeric prefixes are sometimes used to individually name each series. Fibonacci n {\displaystyle n} -step sequences n {\displaystyle n} Series name Values 2 fibonacci 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ... 3 tribonacci 1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ... 4 tetranacci 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ... 5 pentanacci 1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ... 6 hexanacci 1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ... 7 heptanacci 1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ... 8 octonacci 1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ... 9 nonanacci 1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ... 10 decanacci 1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ... Allied sequences can be generated where the initial values are changed: The Lucas series sums the two preceding values like the fibonacci series for n = 2 {\displaystyle n=2} but uses [ 2 , 1 ] {\displaystyle [2,1]} as its initial values. Task Write a function to generate Fibonacci n {\displaystyle n} -step number sequences given its initial values and assuming the number of initial values determines how many previous values are summed to make the next number of the series. Use this to print and show here at least the first ten members of the Fibo/tribo/tetra-nacci and Lucas sequences. Related tasks   Fibonacci sequence   Wolfram Mathworld   Hofstadter Q sequence‎   Leonardo numbers Also see   Lucas Numbers - Numberphile (Video)   Tribonacci Numbers (and the Rauzy Fractal) - Numberphile (Video)   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#C.2B.2B
C++
#include <vector> #include <iostream> #include <numeric> #include <iterator> #include <memory> #include <string> #include <algorithm> #include <iomanip>   std::vector<int> nacci ( const std::vector<int> & start , int arity ) { std::vector<int> result ( start ) ; int sumstart = 1 ;//summing starts at vector's begin + sumstart as //soon as the vector is longer than arity while ( result.size( ) < 15 ) { //we print out the first 15 numbers if ( result.size( ) <= arity ) result.push_back( std::accumulate( result.begin( ) , result.begin( ) + result.size( ) , 0 ) ) ; else { result.push_back( std::accumulate ( result.begin( ) + sumstart , result.begin( ) + sumstart + arity , 0 )) ; sumstart++ ; } } return std::move ( result ) ; }   int main( ) { std::vector<std::string> naccinames {"fibo" , "tribo" , "tetra" , "penta" , "hexa" , "hepta" , "octo" , "nona" , "deca" } ; const std::vector<int> fibo { 1 , 1 } , lucas { 2 , 1 } ; for ( int i = 2 ; i < 11 ; i++ ) { std::vector<int> numberrow = nacci ( fibo , i ) ; std::cout << std::left << std::setw( 10 ) << naccinames[ i - 2 ].append( "nacci" ) << std::setw( 2 ) << " : " ; std::copy ( numberrow.begin( ) , numberrow.end( ) , std::ostream_iterator<int>( std::cout , " " ) ) ; std::cout << "...\n" ; numberrow = nacci ( lucas , i ) ; std::cout << "Lucas-" << i ; if ( i < 10 ) //for formatting purposes std::cout << "  : " ; else std::cout << "  : " ; std::copy ( numberrow.begin( ) , numberrow.end( ) , std::ostream_iterator<int>( std::cout , " " ) ) ; std::cout << "...\n" ; } return 0 ; }
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#VBScript
VBScript
  WScript.Echo CreateObject("Scripting.FileSystemObject").GetFile("input.txt").DateLastModified  
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#Vedit_macro_language
Vedit macro language
Num_Type(File_Stamp_Time("input.txt"))
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#Visual_Basic_.NET
Visual Basic .NET
Dim file As New IO.FileInfo("test.txt")   'Creation Time Dim createTime = file.CreationTime file.CreationTime = createTime.AddHours(1)   'Write Time Dim writeTime = file.LastWriteTime file.LastWriteTime = writeTime.AddHours(1)   'Access Time Dim accessTime = file.LastAccessTime file.LastAccessTime = accessTime.AddHours(1)
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.)
#zkl
zkl
fcn drawFibonacci(img,x,y,word){ // word is "01001010...", 75025 characters dx:=0; dy:=1; // turtle direction foreach i,c in ([1..].zip(word)){ // Walker.zip(list)-->Walker of zipped list a:=x; b:=y; x+=dx; y+=dy; img.line(a,b, x,y, 0x00ff00); if (c=="0"){ dxy:=dx+dy; if(i.isEven){ dx=(dx - dxy)%2; dy=(dxy - dy)%2; }// turn left else { dx=(dxy - dx)%2; dy=(dy - dxy)%2; }// turn right } } }   img:=PPM(1050,1050); fibWord:=L("1","0"); do(23){ fibWord.append(fibWord[-1] + fibWord[-2]); } drawFibonacci(img,20,20,fibWord[-1]); img.write(File("foo.ppm","wb"));
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
#Pike
Pike
array paths = ({ "/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members" });   // append a / to each entry, so that a path like "/home/user1/tmp" will be recognized as a prefix // without it the prefix would end up being "/home/user1/" paths = paths[*]+"/";   string cp = String.common_prefix(paths); cp = cp[..sizeof(cp)-search(reverse(cp), "/")-2]; Result: "/home/user1/tmp"
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
#PowerBASIC
PowerBASIC
#COMPILE EXE #DIM ALL #COMPILER PBCC 6 $PATH_SEPARATOR = "/"   FUNCTION CommonDirectoryPath(Paths() AS STRING) AS STRING LOCAL s AS STRING LOCAL i, j, k AS LONG k = 1 DO FOR i = 0 TO UBOUND(Paths) IF i THEN IF INSTR(k, Paths(i), $PATH_SEPARATOR) <> j THEN EXIT DO ELSEIF LEFT$(Paths(i), j) <> LEFT$(Paths(0), j) THEN EXIT DO END IF ELSE j = INSTR(k, Paths(i), $PATH_SEPARATOR) IF j = 0 THEN EXIT DO END IF END IF NEXT i s = LEFT$(Paths(0), j + CLNG(k <> 1)) k = j + 1 LOOP FUNCTION = s   END FUNCTION     FUNCTION PBMAIN () AS LONG   ' testing the above function   LOCAL s() AS STRING LOCAL i AS LONG   REDIM s(0 TO 2) ARRAY ASSIGN s() = "/home/user1/tmp/coverage/test", _ "/home/user1/tmp/covert/operator", _ "/home/user1/tmp/coven/members" FOR i = 0 TO UBOUND(s()): CON.PRINT s(i): NEXT i CON.PRINT CommonDirectoryPath(s()) & " <- common" CON.PRINT   REDIM s(0 TO 3) ARRAY ASSIGN s() = "/home/user1/tmp/coverage/test", _ "/home/user1/tmp/covert/operator", _ "/home/user1/tmp/coven/members", _ "/home/user1/abc/coven/members" FOR i = 0 TO UBOUND(s()): CON.PRINT s(i): NEXT i CON.PRINT CommonDirectoryPath(s()) & " <- common" CON.PRINT   REDIM s(0 TO 2) ARRAY ASSIGN s() = "/home/user1/tmp/coverage/test", _ "/hope/user1/tmp/covert/operator", _ "/home/user1/tmp/coven/members" FOR i = 0 TO UBOUND(s()): CON.PRINT s(i): NEXT i CON.PRINT CommonDirectoryPath(s()) & " <- common" CON.PRINT   CON.PRINT "hit any key to end program" CON.WAITKEY$   END FUNCTION
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.
#EasyLang
EasyLang
a[] = [ 1 2 3 4 5 6 7 8 9 ] for i range len a[] if a[i] mod 2 = 0 b[] &= a[i] . . print b[]
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.
#Scheme
Scheme
(define (recurse number) (begin (display number) (newline) (recurse (+ number 1))))   (recurse 1)
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.
#SenseTalk
SenseTalk
put recurse(1)   function recurse n put n get the recurse of (n+1) end recurse
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
#hexiscript
hexiscript
for let i 1; i <= 100; i++ if i % 3 = 0 && i % 5 = 0; println "FizzBuzz" elif i % 3 = 0; println "Fizz" elif i % 5 = 0; println "Buzz" else println i; endif endfor
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.
#PL.2FI
PL/I
  /* To obtain file size of files in root as well as from current directory. */   test: proc options (main); declare ch character (1); declare i fixed binary (31); declare in1 file record;   /* Open a file in the root directory. */ open file (in1) title ('//asd.log,type(fixed),recsize(1)'); on endfile (in1) go to next1; do i = 0 by 1; read file (in1) into (ch); end; next1: put skip list ('file size in root directory =' || trim(i)); close file (in1);   /* Open a file in the current dorectory. */ open file (in1) title ('/asd.txt,type(fixed),recsize(1)'); on endfile (in1) go to next2; do i = 0 by 1; read file (in1) into (ch); end; next2: put skip list ('local file size=' || trim(i)); end test;  
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.
#Pop11
Pop11
;;; prints file size in bytes sysfilesize('input.txt') => sysfilesize('/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.
#PostScript
PostScript
(input.txt ) print (input.txt) status pop pop pop = pop (/input.txt ) print (/input.txt) status pop pop pop = pop
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.
#hexiscript
hexiscript
let in openin "input.txt" let out openout "output.txt" while !(catch (let c read char in)) write c out endwhile close in; close out
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.
#HicEst
HicEst
CHARACTER input='input.txt ', output='output.txt ', c, buffer*4096 SYSTEM(COPY=input//output, ERror=11) ! on error branch to label 11 (not shown)
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
#Lua
Lua
-- Return the base two logarithm of x function log2 (x) return math.log(x) / math.log(2) end   -- Return the Shannon entropy of X function entropy (X) local N, count, sum, i = X:len(), {}, 0 for char = 1, N do i = X:sub(char, char) if count[i] then count[i] = count[i] + 1 else count[i] = 1 end end for n_i, count_i in pairs(count) do sum = sum + count_i / N * log2(count_i / N) end return -sum end   -- Return a table of the first n Fibonacci words function fibWords (n) local fw = {1, 0} while #fw < n do fw[#fw + 1] = fw[#fw] .. fw[#fw - 1] end return fw end   -- Main procedure print("n\tWord length\tEntropy") for k, v in pairs(fibWords(37)) do v = tostring(v) io.write(k .. "\t" .. #v) if string.len(#v) < 8 then io.write("\t") end print("\t" .. entropy(v)) 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.
#Perl
Perl
my $fasta_example = <<'END_FASTA_EXAMPLE'; >Rosetta_Example_1 THERECANBENOSPACE >Rosetta_Example_2 THERECANBESEVERAL LINESBUTTHEYALLMUST BECONCATENATED END_FASTA_EXAMPLE   my $num_newlines = 0; while ( < $fasta_example > ) { if (/\A\>(.*)/) { print "\n" x $num_newlines, $1, ': '; } else { $num_newlines = 1; print; } }
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.
#Phix
Phix
bool first = true integer fn = open("fasta.txt","r") if fn=-1 then ?9/0 end if while true do object line = trim(gets(fn)) if atom(line) then puts(1,"\n") exit end if if length(line) then if line[1]=='>' then if not first then puts(1,"\n") end if printf(1,"%s: ",{line[2..$]}) first = false elsif first then printf(1,"Error : File does not begin with '>'\n") exit elsif not find_any(" \t",line) then puts(1,line) else printf(1,"\nError : Sequence contains space(s)\n") exit end if end if end while close(fn)
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: Fn = Fn+2 - Fn+1, if n<0 support for negative     n     in the solution is optional. Related tasks   Fibonacci n-step number sequences‎   Leonardo numbers References   Wikipedia, Fibonacci number   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#6502_Assembly
6502 Assembly
LDA #0 STA $F0  ; LOWER NUMBER LDA #1 STA $F1  ; HIGHER NUMBER LDX #0 LOOP: LDA $F1 STA $0F1B,X STA $F2  ; OLD HIGHER NUMBER ADC $F0 STA $F1  ; NEW HIGHER NUMBER LDA $F2 STA $F0  ; NEW LOWER NUMBER INX CPX #$0A  ; STOP AT FIB(10) BMI LOOP RTS  ; RETURN FROM SUBROUTINE
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
#ACL2
ACL2
(defun factors-r (n i) (declare (xargs :measure (nfix (- n i)))) (cond ((zp (- n i)) (list n)) ((= (mod n i) 0) (cons i (factors-r n (1+ i)))) (t (factors-r n (1+ i)))))   (defun factors (n) (factors-r n 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.
#Common_Lisp
Common Lisp
  (defun fft (a &key (inverse nil) &aux (n (length a))) "Perform the FFT recursively on input vector A. Vector A must have length N of power of 2." (declare (type boolean inverse) (type (integer 1) n)) (if (= n 1) a (let* ((n/2 (/ n 2)) (2iπ/n (complex 0 (/ (* 2 pi) n (if inverse -1 1)))) (⍵_n (exp 2iπ/n)) (⍵ #c(1.0d0 0.0d0)) (a0 (make-array n/2)) (a1 (make-array n/2))) (declare (type (integer 1) n/2) (type (complex double-float) ⍵ ⍵_n)) (symbol-macrolet ((a0[j] (svref a0 j)) (a1[j] (svref a1 j)) (a[i] (svref a i)) (a[i+1] (svref a (1+ i)))) (loop :for i :below (1- n) :by 2 :for j :from 0 :do (setf a0[j] a[i] a1[j] a[i+1]))) (let ((â0 (fft a0 :inverse inverse)) (â1 (fft a1 :inverse inverse)) (â (make-array n))) (symbol-macrolet ((â[k] (svref â k)) (â[k+n/2] (svref â (+ k n/2))) (â0[k] (svref â0 k)) (â1[k] (svref â1 k))) (loop :for k :below n/2 :do (setf â[k] (+ â0[k] (* ⍵ â1[k])) â[k+n/2] (- â0[k] (* ⍵ â1[k]))) :when inverse :do (setf â[k] (/ â[k] 2) â[k+n/2] (/ â[k+n/2] 2)) :do (setq ⍵ (* ⍵ ⍵_n)) :finally (return â)))))))  
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.)
#C.23
C#
using System;   namespace prog { class MainClass { public static void Main (string[] args) { int q = 929; if ( !isPrime(q) ) return; int r = q; while( r > 0 ) r <<= 1; int d = 2 * q + 1; do { int i = 1; for( int p=r; p!=0; p<<=1 ) { i = (i*i) % d; if (p < 0) i *= 2; if (i > d) i -= d; } if (i != 1) d += 2 * q; else break; } while(true);   Console.WriteLine("2^"+q+"-1 = 0 (mod "+d+")"); }   static bool isPrime(int n) { if ( n % 2 == 0 ) return n == 2; if ( n % 3 == 0 ) return n == 3; int d = 5; while( d*d <= n ) { if ( n % d == 0 ) return false; d += 2; if ( n % d == 0 ) return false; d += 4; } return true; } } }
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
#EchoLisp
EchoLisp
  (define distinct-divisors (compose make-set prime-factors))   ;; euler totient : Φ : n / product(p_i) * product (p_i - 1) ;; # of divisors <= n   (define (Φ n) (let ((pdiv (distinct-divisors n))) (/ (* n (for/product ((p pdiv)) (1- p))) (for/product ((p pdiv)) p))))   ;; farey-sequence length |Fn| = 1 + sigma (m=1..) Φ(m)   (define ( F-length n) (1+ (for/sum ((m (1+ n))) (Φ m))))   ;; farey sequence ;; apply the definition : O(n^2) (define (Farey N) (set! N (1+ N)) (make-set (for*/list ((n N) (d (in-range n N))) (rational n d))))    
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®)
#jq
jq
# Using a "reverse array" representations of the integers base b (b>=2), # generate an unbounded stream of the integers from [0] onwards. # E.g. for binary: [0], [1], [0,1], [1,1] ...   def integers($base): def add1: [foreach (.[], null) as $d ({carry: 1}; if $d then ($d + .carry ) as $r | if $r >= $base then {carry: 1, emit: ($r - $base)} else {carry: 0, emit: $r } end elif (.carry == 0) then .emit = null else .emit = .carry end; select(.emit).emit)];   [0] | recurse(add1);   def fairshare($base; $numberOfTerms): limit($numberOfTerms; integers($base) | add | . % $base);   # The task: (2,3,5,11) | "Fairshare \((select(.>2)|"among") // "between") \(.) people: \([fairshare(.; 25)])"  
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®)
#Julia
Julia
fairshare(nplayers,len) = [sum(digits(n, base=nplayers)) % nplayers for n in 0:len-1]   for n in [2, 3, 5, 11] println("Fairshare ", n > 2 ? "among" : "between", " $n people: ", fairshare(n, 25)) end  
http://rosettacode.org/wiki/Fairshare_between_two_and_more
Fairshare between two and more
The Thue-Morse sequence is a sequence of ones and zeros that if two people take turns in the given order, the first persons turn for every '0' in the sequence, the second for every '1'; then this is shown to give a fairer, more equitable sharing of resources. (Football penalty shoot-outs for example, might not favour the team that goes first as much if the penalty takers take turns according to the Thue-Morse sequence and took 2^n penalties) The Thue-Morse sequence of ones-and-zeroes can be generated by: "When counting in binary, the digit sum modulo 2 is the Thue-Morse sequence" Sharing fairly between two or more Use this method: When counting base b, the digit sum modulo b is the Thue-Morse sequence of fairer sharing between b people. Task Counting from zero;   using a function/method/routine to express an integer count in base b, sum the digits modulo b to produce the next member of the Thue-Morse fairshare series for b people. Show the first 25 terms of the fairshare sequence:   For two people:   For three people   For five people   For eleven people Related tasks   Non-decimal radices/Convert   Thue-Morse See also   A010060, A053838, A053840: The On-Line Encyclopedia of Integer Sequences® (OEIS®)
#Kotlin
Kotlin
fun turn(base: Int, n: Int): Int { var sum = 0 var n2 = n while (n2 != 0) { val re = n2 % base n2 /= base sum += re } return sum % base }   fun fairShare(base: Int, count: Int) { print(String.format("Base %2d:", base)) for (i in 0 until count) { val t = turn(base, i) print(String.format(" %2d", t)) } println() }   fun turnCount(base: Int, count: Int) { val cnt = IntArray(base) { 0 } for (i in 0 until count) { val t = turn(base, i) cnt[t]++ }   var minTurn = Int.MAX_VALUE var maxTurn = Int.MIN_VALUE var portion = 0 for (i in 0 until base) { val num = cnt[i] if (num > 0) { portion++ } if (num < minTurn) { minTurn = num } if (num > maxTurn) { maxTurn = num } }   print(" With $base people: ") when (minTurn) { 0 -> { println("Only $portion have a turn") } maxTurn -> { println(minTurn) } else -> { println("$minTurn or $maxTurn") } } }   fun main() { fairShare(2, 25) fairShare(3, 25) fairShare(5, 25) fairShare(11, 25)   println("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)
#JavaScript
JavaScript
(() => {   // Order of Faulhaber's triangle -> rows of Faulhaber's triangle // faulHaberTriangle :: Int -> [[Ratio Int]] const faulhaberTriangle = n => map(x => tail( scanl((a, x) => { const ys = map((nd, i) => ratioMult(nd, Ratio(x, i + 2)), a); return cons(ratioMinus(Ratio(1, 1), ratioSum(ys)), ys); }, [], enumFromTo(0, x)) ), enumFromTo(0, n));   // p -> n -> Sum of the p-th powers of the first n positive integers // faulhaber :: Int -> Ratio Int -> Ratio Int const faulhaber = (p, n) => ratioSum(map( (nd, i) => ratioMult(nd, Ratio(raise(n, i + 1), 1)), last(faulhaberTriangle(p)) ));   // RATIOS -----------------------------------------------------------------   // (Max numr + denr widths) -> Column width -> Filler -> Ratio -> String // justifyRatio :: (Int, Int) -> Int -> Char -> Ratio Integer -> String const justifyRatio = (ws, n, c, nd) => { const w = max(n, ws.nMax + ws.dMax + 2), [num, den] = [nd.num, nd.den]; return all(Number.isSafeInteger, [num, den]) ? ( den === 1 ? center(w, c, show(num)) : (() => { const [q, r] = quotRem(w - 1, 2); return concat([ justifyRight(q, c, show(num)), '/', justifyLeft(q + r, c, (show(den))) ]); })() ) : "JS integer overflow ... "; };   // Ratio :: Int -> Int -> Ratio const Ratio = (n, d) => ({ num: n, den: d });   // ratioMinus :: Ratio -> Ratio -> Ratio const ratioMinus = (nd, nd1) => { const d = lcm(nd.den, nd1.den); return simpleRatio({ num: (nd.num * (d / nd.den)) - (nd1.num * (d / nd1.den)), den: d }); };   // ratioMult :: Ratio -> Ratio -> Ratio const ratioMult = (nd, nd1) => simpleRatio({ num: nd.num * nd1.num, den: nd.den * nd1.den });   // ratioPlus :: Ratio -> Ratio -> Ratio const ratioPlus = (nd, nd1) => { const d = lcm(nd.den, nd1.den); return simpleRatio({ num: (nd.num * (d / nd.den)) + (nd1.num * (d / nd1.den)), den: d }); };   // ratioSum :: [Ratio] -> Ratio const ratioSum = xs => simpleRatio(foldl((a, x) => ratioPlus(a, x), { num: 0, den: 1 }, xs));   // ratioWidths :: [[Ratio]] -> {nMax::Int, dMax::Int} const ratioWidths = xss => { return foldl((a, x) => { const [nw, dw] = ap( [compose(length, show)], [x.num, x.den] ), [an, ad] = ap( [curry(flip(lookup))(a)], ['nMax', 'dMax'] ); return { nMax: nw > an ? nw : an, dMax: dw > ad ? dw : ad }; }, { nMax: 0, dMax: 0 }, concat(xss)); };   // simpleRatio :: Ratio -> Ratio const simpleRatio = nd => { const g = gcd(nd.num, nd.den); return { num: nd.num / g, den: nd.den / g }; };   // GENERIC FUNCTIONS ------------------------------------------------------   // all :: (a -> Bool) -> [a] -> Bool const all = (f, xs) => xs.every(f);   // A list of functions applied to a list of arguments // <*> :: [(a -> b)] -> [a] -> [b] const ap = (fs, xs) => // [].concat.apply([], fs.map(f => // [].concat.apply([], xs.map(x => [f(x)]))));   // Size of space -> filler Char -> Text -> Centered Text // center :: Int -> Char -> Text -> Text const center = (n, c, s) => { const [q, r] = quotRem(n - s.length, 2); return concat(concat([replicate(q, c), s, replicate(q + r, c)])); };   // compose :: (b -> c) -> (a -> b) -> (a -> c) const compose = (f, g) => x => f(g(x));   // concat :: [[a]] -> [a] | [String] -> String const concat = xs => xs.length > 0 ? (() => { const unit = typeof xs[0] === 'string' ? '' : []; return unit.concat.apply(unit, xs); })() : [];   // cons :: a -> [a] -> [a] const cons = (x, xs) => [x].concat(xs);   // 2 or more arguments // curry :: Function -> Function const curry = (f, ...args) => { const go = xs => xs.length >= f.length ? (f.apply(null, xs)) : function () { return go(xs.concat(Array.from(arguments))); }; return go([].slice.call(args, 1)); };   // enumFromTo :: Int -> Int -> [Int] const enumFromTo = (m, n) => Array.from({ length: Math.floor(n - m) + 1 }, (_, i) => m + i);   // flip :: (a -> b -> c) -> b -> a -> c const flip = f => (a, b) => f.apply(null, [b, a]);   // foldl :: (b -> a -> b) -> b -> [a] -> b const foldl = (f, a, xs) => xs.reduce(f, a);   // gcd :: Integral a => a -> a -> a const gcd = (x, y) => { const _gcd = (a, b) => (b === 0 ? a : _gcd(b, a % b)), abs = Math.abs; return _gcd(abs(x), abs(y)); };   // head :: [a] -> a const head = xs => xs.length ? xs[0] : undefined;   // intercalate :: String -> [a] -> String const intercalate = (s, xs) => xs.join(s);   // justifyLeft :: Int -> Char -> Text -> Text const justifyLeft = (n, cFiller, strText) => n > strText.length ? ( (strText + cFiller.repeat(n)) .substr(0, n) ) : strText;   // justifyRight :: Int -> Char -> Text -> Text const justifyRight = (n, cFiller, strText) => n > strText.length ? ( (cFiller.repeat(n) + strText) .slice(-n) ) : strText;   // last :: [a] -> a const last = xs => xs.length ? xs.slice(-1)[0] : undefined;   // length :: [a] -> Int const length = xs => xs.length;   // lcm :: Integral a => a -> a -> a const lcm = (x, y) => (x === 0 || y === 0) ? 0 : Math.abs(Math.floor(x / gcd(x, y)) * y);   // lookup :: Eq a => a -> [(a, b)] -> Maybe b const lookup = (k, pairs) => { if (Array.isArray(pairs)) { let m = pairs.find(x => x[0] === k); return m ? m[1] : undefined; } else { return typeof pairs === 'object' ? ( pairs[k] ) : undefined; } };   // map :: (a -> b) -> [a] -> [b] const map = (f, xs) => xs.map(f);   // max :: Ord a => a -> a -> a const max = (a, b) => b > a ? b : a;   // min :: Ord a => a -> a -> a const min = (a, b) => b < a ? b : a;   // quotRem :: Integral a => a -> a -> (a, a) const quotRem = (m, n) => [Math.floor(m / n), m % n];   // raise :: Num -> Int -> Num const raise = (n, e) => Math.pow(n, e);   // replicate :: Int -> a -> [a] const replicate = (n, x) => Array.from({ length: n }, () => x);   // scanl :: (b -> a -> b) -> b -> [a] -> [b] const scanl = (f, startValue, xs) => xs.reduce((a, x) => { const v = f(a.acc, x); return { acc: v, scan: cons(a.scan, v) }; }, { acc: startValue, scan: [startValue] }) .scan;   // show :: a -> String const show = (...x) => JSON.stringify.apply( null, x.length > 1 ? [x[0], null, x[1]] : x );   // tail :: [a] -> [a] const tail = xs => xs.length ? xs.slice(1) : undefined;   // unlines :: [String] -> String const unlines = xs => xs.join('\n');     // TEST ------------------------------------------------------------------- const triangle = faulhaberTriangle(9), widths = ratioWidths(triangle);   return unlines( map(row => concat(map(cell => justifyRatio(widths, 8, ' ', cell), row)), triangle) ) + '\n\n' + unlines( [ 'faulhaber(17, 1000)', justifyRatio(widths, 0, ' ', faulhaber(17, 1000)), '\nfaulhaber(17, 8)', justifyRatio(widths, 0, ' ', faulhaber(17, 8)), '\nfaulhaber(4, 1000)', justifyRatio(widths, 0, ' ', faulhaber(4, 1000)), ] ); })();