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/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: Fn = Fn+2 - Fn+1, if n<0 support for negative     n     in the solution is optional. Related tasks   Fibonacci n-step number sequences‎   Leonardo numbers References   Wikipedia, Fibonacci number   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#ALGOL_68
ALGOL 68
PROC analytic fibonacci = (LONG INT n)LONG INT:( LONG REAL sqrt 5 = long sqrt(5); LONG REAL p = (1 + sqrt 5) / 2; LONG REAL q = 1/p; ROUND( (p**n + q**n) / sqrt 5 ) );   FOR i FROM 1 TO 30 WHILE print(whole(analytic fibonacci(i),0)); # WHILE # i /= 30 DO print(", ") OD; print(new line)
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
#Asymptote
Asymptote
int[] n = {11, 21, 32, 45, 67, 519};   for(var j : n) { write(j, suffix=none); write(" =>", suffix=none); for(int i = 1; i < (j/2); ++i) { if(j % i == 0) { write(" ", i, suffix=none); } } write(" ", j); }
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.
#Haskell
Haskell
import Data.Complex   -- Cooley-Tukey fft [] = [] fft [x] = [x] fft xs = zipWith (+) ys ts ++ zipWith (-) ys ts where n = length xs ys = fft evens zs = fft odds (evens, odds) = split xs split [] = ([], []) split [x] = ([x], []) split (x:y:xs) = (x:xt, y:yt) where (xt, yt) = split xs ts = zipWith (\z k -> exp' k n * z) zs [0..] exp' k n = cis $ -2 * pi * (fromIntegral k) / (fromIntegral n)   main = mapM_ print $ fft [1,1,1,1,0,0,0,0]
http://rosettacode.org/wiki/Factors_of_a_Mersenne_number
Factors of a Mersenne number
A Mersenne number is a number in the form of 2P-1. If P is prime, the Mersenne number may be a Mersenne prime (if P is not prime, the Mersenne number is also not prime). In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before starting a, potentially lengthy, Lucas-Lehmer test. There are very efficient algorithms for determining if a number divides 2P-1 (or equivalently, if 2P mod (the number) = 1). Some languages already have built-in implementations of this exponent-and-mod operation (called modPow or similar). The following is how to implement this modPow yourself: For example, let's compute 223 mod 47. Convert the exponent 23 to binary, you get 10111. Starting with square = 1, repeatedly square it. Remove the top bit of the exponent, and if it's 1 multiply square by the base of the exponentiation (2), then compute square modulo 47. Use the result of the modulo from the last step as the initial value of square in the next step: remove optional square top bit multiply by 2 mod 47 ──────────── ─────── ───────────── ────── 1*1 = 1 1 0111 1*2 = 2 2 2*2 = 4 0 111 no 4 4*4 = 16 1 11 16*2 = 32 32 32*32 = 1024 1 1 1024*2 = 2048 27 27*27 = 729 1 729*2 = 1458 1 Since 223 mod 47 = 1, 47 is a factor of 2P-1. (To see this, subtract 1 from both sides: 223-1 = 0 mod 47.) Since we've shown that 47 is a factor, 223-1 is not prime. Further properties of Mersenne numbers allow us to refine the process even more. Any factor q of 2P-1 must be of the form 2kP+1, k being a positive integer or zero. Furthermore, q must be 1 or 7 mod 8. Finally any potential factor q must be prime. As in other trial division algorithms, the algorithm stops when 2kP+1 > sqrt(N). These primality tests only work on Mersenne numbers where P is prime. For example, M4=15 yields no factors using these techniques, but factors into 3 and 5, neither of which fit 2kP+1. Task Using the above method find a factor of 2929-1 (aka M929) Related tasks   count in factors   prime decomposition   factors of an integer   Sieve of Eratosthenes   primality by trial division   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division See also   Computers in 1948: 2127 - 1       (Note:   This video is no longer available because the YouTube account associated with this video has been terminated.)
#Go
Go
package main   import ( "fmt" "math" )   // limit search to small primes. really this is higher than // you'd want it, but it's fun to factor M67. const qlimit = 2e8   func main() { mtest(31) mtest(67) mtest(929) }   func mtest(m int32) { // the function finds odd prime factors by // searching no farther than sqrt(N), where N = 2^m-1. // the first odd prime is 3, 3^2 = 9, so M3 = 7 is still too small. // M4 = 15 is first number for which test is meaningful. if m < 4 { fmt.Printf("%d < 4. M%d not tested.\n", m, m) return } flimit := math.Sqrt(math.Pow(2, float64(m)) - 1) var qlast int32 if flimit < qlimit { qlast = int32(flimit) } else { qlast = qlimit } composite := make([]bool, qlast+1) sq := int32(math.Sqrt(float64(qlast))) loop: for q := int32(3); ; { if q <= sq { for i := q * q; i <= qlast; i += q { composite[i] = true } } if q8 := q % 8; (q8 == 1 || q8 == 7) && modPow(2, m, q) == 1 { fmt.Printf("M%d has factor %d\n", m, q) return } for { q += 2 if q > qlast { break loop } if !composite[q] { break } } } fmt.Printf("No factors of M%d found.\n", m) }   // base b to power p, mod m func modPow(b, p, m int32) int32 { pow := int64(1) b64 := int64(b) m64 := int64(m) bit := uint(30) for 1<<bit&p == 0 { bit-- } for { pow *= pow if 1<<bit&p != 0 { pow *= b64 } pow %= m64 if bit == 0 { break } bit-- } return int32(pow) }
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
#Phix
Phix
with javascript_semantics function farey(integer n) integer a=0, b=1, c=1, d=n, items=1 if n<=11 then printf(1,"%d: %d/%d",{n,a,b}) end if while c<=n do integer k = floor((n+b)/d) {a,b,c,d} = {c,d,k*c-a,k*d-b} items += 1 if n<=11 then printf(1," %d/%d",{a,b}) end if end while return items end function printf(1,"Farey sequence for order 1 through 11:\n") for i=1 to 11 do {} = farey(i) printf(1,"\n") end for sequence nf = apply(tagset(1000,100,100),farey) printf(1,"Farey sequence fractions, 100 to 1000 by hundreds:\n%v\n",{nf})
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)
#Ruby
Ruby
class Frac attr_accessor:num attr_accessor:denom   def initialize(n,d) if d == 0 then raise ArgumentError.new('d cannot be zero') end   nn = n dd = d if nn == 0 then dd = 1 elsif dd < 0 then nn = -nn dd = -dd end   g = nn.abs.gcd(dd.abs) if g > 1 then nn = nn / g dd = dd / g end   @num = nn @denom = dd end   def to_s if self.denom == 1 then return self.num.to_s else return "%d/%d" % [self.num, self.denom] end end   def -@ return Frac.new(-self.num, self.denom) end   def +(rhs) return Frac.new(self.num * rhs.denom + self.denom * rhs.num, rhs.denom * self.denom) end def -(rhs) return Frac.new(self.num * rhs.denom - self.denom * rhs.num, rhs.denom * self.denom) end   def *(rhs) return Frac.new(self.num * rhs.num, rhs.denom * self.denom) end end   FRAC_ZERO = Frac.new(0, 1) FRAC_ONE = Frac.new(1, 1)   def bernoulli(n) if n < 0 then raise ArgumentError.new('n cannot be negative') end   a = Array.new(n + 1) a[0] = FRAC_ZERO   for m in 0 .. n do a[m] = Frac.new(1, m + 1) m.downto(1) do |j| a[j - 1] = (a[j - 1] - a[j]) * Frac.new(j, 1) end end   if n != 1 then return a[0] end return -a[0] end   def binomial(n, k) if n < 0 then raise ArgumentError.new('n cannot be negative') end if k < 0 then raise ArgumentError.new('k cannot be negative') end if n < k then raise ArgumentError.new('n cannot be less than k') end   if n == 0 or k == 0 then return 1 end   num = 1 for i in k + 1 .. n do num = num * i end   den = 1 for i in 2 .. n - k do den = den * i end   return num / den end   def faulhaberTriangle(p) coeffs = Array.new(p + 1) coeffs[0] = FRAC_ZERO q = Frac.new(1, p + 1) sign = -1 for j in 0 .. p do sign = -sign coeffs[p - j] = q * Frac.new(sign, 1) * Frac.new(binomial(p + 1, j), 1) * bernoulli(j) end return coeffs end   def main for i in 0 .. 9 do coeffs = faulhaberTriangle(i) coeffs.each do |coeff| print "%5s " % [coeff] end puts end end   main()
http://rosettacode.org/wiki/Faulhaber%27s_formula
Faulhaber's formula
In mathematics,   Faulhaber's formula,   named after Johann Faulhaber,   expresses the sum of the p-th powers of the first n positive integers as a (p + 1)th-degree polynomial function of n,   the coefficients involving Bernoulli numbers. Task Generate the first 10 closed-form expressions, starting with p = 0. Related tasks   Bernoulli numbers.   evaluate binomial coefficients. See also   The Wikipedia entry:   Faulhaber's formula.   The Wikipedia entry:   Bernoulli numbers.   The Wikipedia entry:   binomial coefficients.
#Scala
Scala
import scala.math.Ordering.Implicits.infixOrderingOps   abstract class Frac extends Comparable[Frac] { val num: BigInt val denom: BigInt   def unary_-(): Frac = { Frac(-num, denom) }   def +(rhs: Frac): Frac = { Frac( num * rhs.denom + rhs.num * denom, denom * rhs.denom ) }   def -(rhs: Frac): Frac = { Frac( num * rhs.denom - rhs.num * denom, denom * rhs.denom ) }   def *(rhs: Frac): Frac = { Frac(num * rhs.num, denom * rhs.denom) }   override def compareTo(rhs: Frac): Int = { val ln = num * rhs.denom val rn = rhs.num * denom ln.compare(rn) }   def canEqual(other: Any): Boolean = other.isInstanceOf[Frac]   override def equals(other: Any): Boolean = other match { case that: Frac => (that canEqual this) && num == that.num && denom == that.denom case _ => false }   override def hashCode(): Int = { val state = Seq(num, denom) state.map(_.hashCode()).foldLeft(0)((a, b) => 31 * a + b) }   override def toString: String = { if (denom == 1) { return s"$num" } s"$num/$denom" } }   object Frac { val ZERO: Frac = Frac(0) val ONE: Frac = Frac(1)   def apply(n: BigInt): Frac = new Frac { val num: BigInt = n val denom: BigInt = 1 }   def apply(n: BigInt, d: BigInt): Frac = { if (d == 0) { throw new IllegalArgumentException("Parameter d may not be zero.") }   var nn = n var dd = d   if (nn == 0) { dd = 1 } else if (dd < 0) { nn = -nn dd = -dd }   val g = nn.gcd(dd) if (g > 0) { nn /= g dd /= g }   new Frac { val num: BigInt = nn val denom: BigInt = dd } } }   object Faulhaber { def bernoulli(n: Int): Frac = { if (n < 0) { throw new IllegalArgumentException("n may not be negative or zero") }   val a = Array.fill(n + 1)(Frac.ZERO) for (m <- 0 to n) { a(m) = Frac(1, m + 1) for (j <- m to 1 by -1) { a(j - 1) = (a(j - 1) - a(j)) * Frac(j) } }   // returns 'first' Bernoulli number if (n != 1) { return a(0) } -a(0) }   def binomial(n: Int, k: Int): Int = { if (n < 0 || k < 0 || n < k) { throw new IllegalArgumentException() } if (n == 0 || k == 0) { return 1 } val num = (k + 1 to n).product val den = (2 to n - k).product num / den }   def faulhaber(p: Int): Unit = { print(s"$p : ") val q = Frac(1, p + 1) var sign = -1 for (j <- 0 to p) { sign *= -1 val coeff = q * Frac(sign) * Frac(binomial(p + 1, j)) * bernoulli(j) if (Frac.ZERO != coeff) { if (j == 0) { if (Frac.ONE != coeff) { if (-Frac.ONE == coeff) { print('-') } else { print(coeff) } } } else { if (Frac.ONE == coeff) { print(" + ") } else if (-Frac.ONE == coeff) { print(" - ") } else if (coeff > Frac.ZERO) { print(s" + ${coeff}") } else { print(s" - ${-coeff}") } } val pwr = p + 1 - j if (pwr > 1) { print(s"n^${pwr}") } else { print('n') } } } println() }   def main(args: Array[String]): Unit = { for (i <- 0 to 9) { faulhaber(i) } } }
http://rosettacode.org/wiki/Fibonacci_n-step_number_sequences
Fibonacci n-step number sequences
These number series are an expansion of the ordinary Fibonacci sequence where: For n = 2 {\displaystyle n=2} we have the Fibonacci sequence; with initial values [ 1 , 1 ] {\displaystyle [1,1]} and F k 2 = F k − 1 2 + F k − 2 2 {\displaystyle F_{k}^{2}=F_{k-1}^{2}+F_{k-2}^{2}} For n = 3 {\displaystyle n=3} we have the tribonacci sequence; with initial values [ 1 , 1 , 2 ] {\displaystyle [1,1,2]} and F k 3 = F k − 1 3 + F k − 2 3 + F k − 3 3 {\displaystyle F_{k}^{3}=F_{k-1}^{3}+F_{k-2}^{3}+F_{k-3}^{3}} For n = 4 {\displaystyle n=4} we have the tetranacci sequence; with initial values [ 1 , 1 , 2 , 4 ] {\displaystyle [1,1,2,4]} and F k 4 = F k − 1 4 + F k − 2 4 + F k − 3 4 + F k − 4 4 {\displaystyle F_{k}^{4}=F_{k-1}^{4}+F_{k-2}^{4}+F_{k-3}^{4}+F_{k-4}^{4}} ... For general n > 2 {\displaystyle n>2} we have the Fibonacci n {\displaystyle n} -step sequence - F k n {\displaystyle F_{k}^{n}} ; with initial values of the first n {\displaystyle n} values of the ( n − 1 ) {\displaystyle (n-1)} 'th Fibonacci n {\displaystyle n} -step sequence F k n − 1 {\displaystyle F_{k}^{n-1}} ; and k {\displaystyle k} 'th value of this n {\displaystyle n} 'th sequence being F k n = ∑ i = 1 ( n ) F k − i ( n ) {\displaystyle F_{k}^{n}=\sum _{i=1}^{(n)}{F_{k-i}^{(n)}}} For small values of n {\displaystyle n} , Greek numeric prefixes are sometimes used to individually name each series. Fibonacci n {\displaystyle n} -step sequences n {\displaystyle n} Series name Values 2 fibonacci 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ... 3 tribonacci 1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ... 4 tetranacci 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ... 5 pentanacci 1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ... 6 hexanacci 1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ... 7 heptanacci 1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ... 8 octonacci 1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ... 9 nonanacci 1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ... 10 decanacci 1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ... Allied sequences can be generated where the initial values are changed: The Lucas series sums the two preceding values like the fibonacci series for n = 2 {\displaystyle n=2} but uses [ 2 , 1 ] {\displaystyle [2,1]} as its initial values. Task Write a function to generate Fibonacci n {\displaystyle n} -step number sequences given its initial values and assuming the number of initial values determines how many previous values are summed to make the next number of the series. Use this to print and show here at least the first ten members of the Fibo/tribo/tetra-nacci and Lucas sequences. Related tasks   Fibonacci sequence   Wolfram Mathworld   Hofstadter Q sequence‎   Leonardo numbers Also see   Lucas Numbers - Numberphile (Video)   Tribonacci Numbers (and the Rauzy Fractal) - Numberphile (Video)   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   ' Deduces the step, n, from the length of the dynamic array passed in ' and fills it out to 'size' elements Sub fibN (a() As Integer, size As Integer) Dim lb As Integer = LBound(a) Dim ub As Integer = UBound(a) Dim length As Integer = ub - lb + 1 If length < 2 OrElse length >= size Then Return ub = lb + size - 1 Redim Preserve a(lb To ub) Dim sum As Integer For i As Integer = lb + length to ub sum = 0 For j As Integer = 1 To Length sum += a(i - j) Next j a(i) = sum Next i End Sub   Sub printSeries(a() As Integer, name_ As String) '' name is a keyword Print name_; " =>"; For i As Integer = LBound(a) To UBound(a) Print Using "####"; a(i); Print " "; Next Print End Sub   Const size As Integer = 13 '' say Redim a(1 To 2) As Integer a(1) = 1 : a(2) = 1 fibN(a(), size) printSeries(a(), "fibonacci ") Redim Preserve a(1 To 3) a(3) = 2 fibN(a(), size) printSeries(a(), "tribonacci") Redim Preserve a(1 To 4) a(4) = 4 fibN(a(), size) printSeries(a(), "tetranacci") erase a Redim a(1 To 2) a(1) = 2 : a(2) = 1 fibN(a(), size) printSeries(a(), "lucas ") Print Print "Press any key to quit" Sleep
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
#Visual_Basic
Visual Basic
Public Function CommonDirectoryPath(ParamArray Paths()) As String Dim v As Variant Dim Path() As String, s As String Dim i As Long, j As Long, k As Long Const PATH_SEPARATOR As String = "/"   For Each v In Paths ReDim Preserve Path(0 To i) Path(i) = v i = i + 1 Next v   k = 1   Do For i = 0 To UBound(Path) If i Then If InStr(k, Path(i), PATH_SEPARATOR) <> j Then Exit Do ElseIf Left$(Path(i), j) <> Left$(Path(0), j) Then Exit Do End If Else j = InStr(k, Path(i), PATH_SEPARATOR) If j = 0 Then Exit Do End If End If Next i s = Left$(Path(0), j + CLng(k <> 1)) k = j + 1 Loop CommonDirectoryPath = s   End Function   Sub Main()   ' testing the above function Debug.Assert CommonDirectoryPath( _ "/home/user1/tmp/coverage/test", _ "/home/user1/tmp/covert/operator", _ "/home/user1/tmp/coven/members") = _ "/home/user1/tmp"   Debug.Assert CommonDirectoryPath( _ "/home/user1/tmp/coverage/test", _ "/home/user1/tmp/covert/operator", _ "/home/user1/tmp/coven/members", _ "/home/user1/abc/coven/members") = _ "/home/user1"   Debug.Assert CommonDirectoryPath( _ "/home/user1/tmp/coverage/test", _ "/hope/user1/tmp/covert/operator", _ "/home/user1/tmp/coven/members") = _ "/"   End Sub
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.
#Futhark
Futhark
  fun main(as: []int): []int = filter (fn x => x%2 == 0) as  
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
#J
J
  classify =: +/@(1 2 * 0 = 3 5&|~) (":@]`('Fizz'"_)`('Buzz'"_)`('FizzBuzz'"_) @. classify "0) >:i.100  
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.
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   import java.nio.   parse arg infileName outfileName .   if infileName = '' | infileName.length = 0 then infileName = 'data/input.txt' if outfileName = '' | outfileName.length = 0 then outfileName = 'data/output.txt'   binaryCopy(infileName, outfileName)   return   method binaryCopy(infileName, outfileName) public static   do infile = Paths.get('.', [String infileName]) outfile = Paths.get('.', [String outfileName]) fileOctets = Files.readAllBytes(infile) Files.write(outfile, fileOctets, [StandardOpenOption.WRITE, StandardOpenOption.CREATE])   catch ioex = IOException ioex.printStackTrace() end   return  
http://rosettacode.org/wiki/File_input/output
File input/output
File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file into a variable   how to write a variable's contents into a file Oneliners that skip the intermediate variable are of secondary interest — operating systems have copy commands for that.
#Nim
Nim
import os copyfile("input.txt", "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
#Ring
Ring
  # Project : Fibonacci word   fw1 = "1" fw2 = "0"   see "N Length Entropy Word" + nl n = 1 see "" + n + " " + len(fw1) + " " + calcentropy(fw1,2) + " " + fw1 + nl n = 2 see "" + n + " " + len(fw2) + " " + calcentropy(fw2,2) + " " + fw2 + nl   for n = 1 to 55 fw3 = fw2 + fw1 temp = fw2 fw2 = fw3 fw1 = temp if len(fw3) < 55 see "" + (n+2) + " " + len(fw3) + " " + calcentropy(fw3,2) + " " + fw3 + nl ok next   func calcentropy(source,b) decimals(11) entropy = 0 countOfChar = list(255) charCount =len( source) usedChar ="" for i =1 to len( source) ch =substr(source, i, 1) if not(substr( usedChar, ch)) usedChar =usedChar +ch ok j =substr( usedChar, ch) countOfChar[j] =countOfChar[j] +1 next l =len(usedChar) for i =1 to l probability =countOfChar[i] /charCount entropy =entropy - (probability *logBase(probability, 2)) next return entropy   func swap(a, b) temp = a a = b b = temp return [a, b]   func logBase (x, b) logBase =log( x) /log( 2) return logBase  
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
#Ruby
Ruby
#encoding: ASCII-8BIT   def entropy(s) counts = Hash.new(0.0) s.each_char { |c| counts[c] += 1 } leng = s.length   counts.values.reduce(0) do |entropy, count| freq = count / leng entropy - freq * Math.log2(freq) end end   n_max = 37 words = ['1', '0']   for n in words.length ... n_max words << words[-1] + words[-2] end   puts '%3s %9s %15s  %s' % %w[N Length Entropy Fibword] words.each.with_index(1) do |word, i| puts '%3i %9i %15.12f  %s' % [i, word.length, entropy(word), word.length<60 ? word : '<too long>'] 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
#ALGOL_W
ALGOL W
begin  % return the nth Fibonacci number % integer procedure Fibonacci( integer value n ) ; begin integer fn, fn1, fn2; fn2 := 1; fn1 := 0; fn  := 0; for i := 1 until n do begin fn  := fn1 + fn2; fn2 := fn1; fn1 := fn end ; fn end Fibonacci ;   for i := 0 until 10 do writeon( i_w := 3, s_w := 0, Fibonacci( i ) )   end.
http://rosettacode.org/wiki/Factors_of_an_integer
Factors of an integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Compute the   factors   of a positive integer. These factors are the positive integers by which the number being factored can be divided to yield a positive integer result. (Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty;   this task does not require handling of either of these cases). Note that every prime number has two factors:   1   and itself. Related tasks   count in factors   prime decomposition   Sieve of Eratosthenes   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division   sequence: smallest number greater than previous term with exactly n divisors
#AutoHotkey
AutoHotkey
msgbox, % factors(45) "`n" factors(53) "`n" factors(64)   Factors(n) { Loop, % floor(sqrt(n)) { v := A_Index = 1 ? 1 "," n : mod(n,A_Index) ? v : v "," A_Index "," n//A_Index } Sort, v, N U D, Return, v }
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.
#Idris
Idris
module Main   import Data.Complex     concatPair : List (a, a) -> List (a) concatPair xs with (unzip xs) | (xs1, xs2) = xs1 ++ xs2   fft' : List (Complex Double) -> Nat -> Nat -> List (Complex Double) fft' (x::xs) (S Z) _ = [x] fft' xs n s = concatPair $ map (\(x1,x2,k) => let eTerm = ((cis (-2 * pi * ((cast k) - 1) / (cast n))) * x2) in (x1 + eTerm, x1 - eTerm)) $ zip3 left right [1..n `div` 2]   where left : List (Complex Double) right : List (Complex Double) left = fft' (xs) (n `div` 2) (2 * s) right = fft' (drop s xs) (n `div` 2) (2 * s)     -- Recursive Cooley-Tukey with radix-2 DIT case -- assumes no of points provided are a power of 2 fft : List (Complex Double) -> List (Complex Double) fft [] = [] fft xs = fft' xs (length xs) 1     main : IO() main = traverse_ printLn $ fft [1,1,1,1,0,0,0,0]
http://rosettacode.org/wiki/Factors_of_a_Mersenne_number
Factors of a Mersenne number
A Mersenne number is a number in the form of 2P-1. If P is prime, the Mersenne number may be a Mersenne prime (if P is not prime, the Mersenne number is also not prime). In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before starting a, potentially lengthy, Lucas-Lehmer test. There are very efficient algorithms for determining if a number divides 2P-1 (or equivalently, if 2P mod (the number) = 1). Some languages already have built-in implementations of this exponent-and-mod operation (called modPow or similar). The following is how to implement this modPow yourself: For example, let's compute 223 mod 47. Convert the exponent 23 to binary, you get 10111. Starting with square = 1, repeatedly square it. Remove the top bit of the exponent, and if it's 1 multiply square by the base of the exponentiation (2), then compute square modulo 47. Use the result of the modulo from the last step as the initial value of square in the next step: remove optional square top bit multiply by 2 mod 47 ──────────── ─────── ───────────── ────── 1*1 = 1 1 0111 1*2 = 2 2 2*2 = 4 0 111 no 4 4*4 = 16 1 11 16*2 = 32 32 32*32 = 1024 1 1 1024*2 = 2048 27 27*27 = 729 1 729*2 = 1458 1 Since 223 mod 47 = 1, 47 is a factor of 2P-1. (To see this, subtract 1 from both sides: 223-1 = 0 mod 47.) Since we've shown that 47 is a factor, 223-1 is not prime. Further properties of Mersenne numbers allow us to refine the process even more. Any factor q of 2P-1 must be of the form 2kP+1, k being a positive integer or zero. Furthermore, q must be 1 or 7 mod 8. Finally any potential factor q must be prime. As in other trial division algorithms, the algorithm stops when 2kP+1 > sqrt(N). These primality tests only work on Mersenne numbers where P is prime. For example, M4=15 yields no factors using these techniques, but factors into 3 and 5, neither of which fit 2kP+1. Task Using the above method find a factor of 2929-1 (aka M929) Related tasks   count in factors   prime decomposition   factors of an integer   Sieve of Eratosthenes   primality by trial division   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division See also   Computers in 1948: 2127 - 1       (Note:   This video is no longer available because the YouTube account associated with this video has been terminated.)
#Haskell
Haskell
import Data.List import HFM.Primes (isPrime) import Control.Monad import Control.Arrow   int2bin = reverse.unfoldr(\x -> if x==0 then Nothing else Just ((uncurry.flip$(,))$divMod x 2))   trialfac m = take 1. dropWhile ((/=1).(\q -> foldl (((`mod` q).).pm) 1 bs)) $ qs where qs = filter (liftM2 (&&) (liftM2 (||) (==1) (==7) .(`mod`8)) isPrime ). map (succ.(2*m*)). enumFromTo 1 $ m `div` 2 bs = int2bin m pm n b = 2^b*n*n
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
#Picat
Picat
go ?=> member(N,1..11), Farey = farey(N), println(N=Farey), fail, nl. go => true.   farey(N) = M => M1 = [0=$(0/1)] ++ [I2/J2=$(I2/J2) : I in 1..N, J in I..N, GCD=gcd(I,J),I2 =I//GCD,J2=J//GCD].sort_remove_dups(), M = [ E: _=E in M1]. % extract the rational representation    
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
#Prolog
Prolog
task(1) :- between(1, 11, I), farey(I, F), write(I), write(': '), rwrite(F), nl, fail; true.   task(2) :- between(1, 10, I), I100 is I*100, farey( I100, F), length(F,N), write('|F('), write(I100), write(')| = '), writeln(N), fail; true.   % farey(+Order, Sequence) farey(Order, Sequence) :- bagof( R, I^J^(between(1, Order, J), between(0, J, I), R is I rdiv J), S), predsort( rcompare, S, Sequence ).   rprint( rdiv(A,B) ) :- write(A), write(/), write(B), !. rprint( I ) :- integer(I), write(I), write(/), write(1), !.   rwrite([]). rwrite([R]) :- rprint(R). rwrite([R, T|Rs]) :- rprint(R), write(', '), rwrite([T|Rs]).   rcompare(<, A, B) :- A < B, !. rcompare(>, A, B) :- A > B, !. rcompare(=, A, B) :- A =< B.
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)
#Scala
Scala
import java.math.MathContext   import scala.collection.mutable   abstract class Frac extends Comparable[Frac] { val num: BigInt val denom: BigInt   def unary_-(): Frac = { Frac(-num, denom) }   def +(rhs: Frac): Frac = { Frac( num * rhs.denom + rhs.num * denom, denom * rhs.denom ) }   def -(rhs: Frac): Frac = { Frac( num * rhs.denom - rhs.num * denom, denom * rhs.denom ) }   def *(rhs: Frac): Frac = { Frac(num * rhs.num, denom * rhs.denom) }   override def compareTo(rhs: Frac): Int = { val ln = num * rhs.denom val rn = rhs.num * denom ln.compare(rn) }   def canEqual(other: Any): Boolean = other.isInstanceOf[Frac]   override def equals(other: Any): Boolean = other match { case that: Frac => (that canEqual this) && num == that.num && denom == that.denom case _ => false }   override def hashCode(): Int = { val state = Seq(num, denom) state.map(_.hashCode()).foldLeft(0)((a, b) => 31 * a + b) }   override def toString: String = { if (denom == 1) { return s"$num" } s"$num/$denom" } }   object Frac { val ZERO: Frac = Frac(0) val ONE: Frac = Frac(1)   def apply(n: BigInt): Frac = new Frac { val num: BigInt = n val denom: BigInt = 1 }   def apply(n: BigInt, d: BigInt): Frac = { if (d == 0) { throw new IllegalArgumentException("Parameter d may not be zero.") }   var nn = n var dd = d   if (nn == 0) { dd = 1 } else if (dd < 0) { nn = -nn dd = -dd }   val g = nn.gcd(dd) if (g > 0) { nn /= g dd /= g }   new Frac { val num: BigInt = nn val denom: BigInt = dd } } }   object Faulhaber { def bernoulli(n: Int): Frac = { if (n < 0) { throw new IllegalArgumentException("n may not be negative or zero") }   val a = Array.fill(n + 1)(Frac.ZERO) for (m <- 0 to n) { a(m) = Frac(1, m + 1) for (j <- m to 1 by -1) { a(j - 1) = (a(j - 1) - a(j)) * Frac(j) } }   // returns 'first' Bernoulli number if (n != 1) { return a(0) } -a(0) }   def binomial(n: Int, k: Int): Int = { if (n < 0 || k < 0 || n < k) { throw new IllegalArgumentException() } if (n == 0 || k == 0) { return 1 } val num = (k + 1 to n).product val den = (2 to n - k).product num / den }   def faulhaberTriangle(p: Int): List[Frac] = { val coeffs = mutable.MutableList.fill(p + 1)(Frac.ZERO)   val q = Frac(1, p + 1) var sign = -1 for (j <- 0 to p) { sign *= -1 coeffs(p - j) = q * Frac(sign) * Frac(binomial(p + 1, j)) * bernoulli(j) } coeffs.toList }   def main(args: Array[String]): Unit = { for (i <- 0 to 9) { val coeffs = faulhaberTriangle(i) for (coeff <- coeffs) { print("%5s ".format(coeff)) } println() } println() } }
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.
#Sidef
Sidef
const AnyNum = require('Math::AnyNum') const Poly = require('Math::Polynomial')   Poly.string_config(Hash( fold_sign => true, prefix => "", suffix => "", variable => "n" ))   func anynum(n) { AnyNum.new(n.as_rat) }   func faulhaber_formula(p) { (p+1).of { |j| Poly.monomial(p - j + 1)\ .mul_const(anynum(bernoulli(j)))\ .mul_const(anynum(binomial(p+1, j))) }.reduce(:add).div_const(p+1) }   for p in (^10) { printf("%2d: %s\n", p, faulhaber_formula(p)) }
http://rosettacode.org/wiki/Fibonacci_n-step_number_sequences
Fibonacci n-step number sequences
These number series are an expansion of the ordinary Fibonacci sequence where: For n = 2 {\displaystyle n=2} we have the Fibonacci sequence; with initial values [ 1 , 1 ] {\displaystyle [1,1]} and F k 2 = F k − 1 2 + F k − 2 2 {\displaystyle F_{k}^{2}=F_{k-1}^{2}+F_{k-2}^{2}} For n = 3 {\displaystyle n=3} we have the tribonacci sequence; with initial values [ 1 , 1 , 2 ] {\displaystyle [1,1,2]} and F k 3 = F k − 1 3 + F k − 2 3 + F k − 3 3 {\displaystyle F_{k}^{3}=F_{k-1}^{3}+F_{k-2}^{3}+F_{k-3}^{3}} For n = 4 {\displaystyle n=4} we have the tetranacci sequence; with initial values [ 1 , 1 , 2 , 4 ] {\displaystyle [1,1,2,4]} and F k 4 = F k − 1 4 + F k − 2 4 + F k − 3 4 + F k − 4 4 {\displaystyle F_{k}^{4}=F_{k-1}^{4}+F_{k-2}^{4}+F_{k-3}^{4}+F_{k-4}^{4}} ... For general n > 2 {\displaystyle n>2} we have the Fibonacci n {\displaystyle n} -step sequence - F k n {\displaystyle F_{k}^{n}} ; with initial values of the first n {\displaystyle n} values of the ( n − 1 ) {\displaystyle (n-1)} 'th Fibonacci n {\displaystyle n} -step sequence F k n − 1 {\displaystyle F_{k}^{n-1}} ; and k {\displaystyle k} 'th value of this n {\displaystyle n} 'th sequence being F k n = ∑ i = 1 ( n ) F k − i ( n ) {\displaystyle F_{k}^{n}=\sum _{i=1}^{(n)}{F_{k-i}^{(n)}}} For small values of n {\displaystyle n} , Greek numeric prefixes are sometimes used to individually name each series. Fibonacci n {\displaystyle n} -step sequences n {\displaystyle n} Series name Values 2 fibonacci 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ... 3 tribonacci 1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ... 4 tetranacci 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ... 5 pentanacci 1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ... 6 hexanacci 1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ... 7 heptanacci 1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ... 8 octonacci 1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ... 9 nonanacci 1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ... 10 decanacci 1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ... Allied sequences can be generated where the initial values are changed: The Lucas series sums the two preceding values like the fibonacci series for n = 2 {\displaystyle n=2} but uses [ 2 , 1 ] {\displaystyle [2,1]} as its initial values. Task Write a function to generate Fibonacci n {\displaystyle n} -step number sequences given its initial values and assuming the number of initial values determines how many previous values are summed to make the next number of the series. Use this to print and show here at least the first ten members of the Fibo/tribo/tetra-nacci and Lucas sequences. Related tasks   Fibonacci sequence   Wolfram Mathworld   Hofstadter Q sequence‎   Leonardo numbers Also see   Lucas Numbers - Numberphile (Video)   Tribonacci Numbers (and the Rauzy Fractal) - Numberphile (Video)   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#FunL
FunL
import util.TextTable native scala.collection.mutable.Queue   def fibLike( init ) = q = Queue()   for i <- init do q.enqueue( i )   def fib = q.enqueue( sum(q) ) q.dequeue() # fib()   0 # fib()   def fibN( n ) = fibLike( [1] + [2^i | i <- 0:n-1] )   val lucas = fibLike( [2, 1] )   t = TextTable() t.header( 'k', 'Fibonacci', 'Tribonacci', 'Tetranacci', 'Lucas' ) t.line()   for i <- 1..5 t.rightAlignment( i )   seqs = (fibN(2), fibN(3), fibN(4), lucas)   for k <- 1..10 t.row( ([k] + [seqs(i)(k) | i <- 0:4]).toIndexedSeq() )   print( t )
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
#Wren
Wren
var findCommonDir = Fn.new { |paths, sep| var count = paths.count if (count == 0) return "" if (count == 1) return paths[0] var splits = List.filled(count, null) for (i in 0...count) splits[i] = paths[i].split(sep) var minLen = splits[0].count for (i in 1...count) { var c = splits[i].count if (c < minLen) minLen = c } if (minLen < 2) return "" var common = "" for (i in 1...minLen) { var dir = splits[0][i] for (j in 1...count) { if (splits[j][i] != dir) return common } common = common + sep + dir } return common }   var paths = [ "/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members" ] System.write("The common directory path is: ") System.print(findCommonDir.call(paths, "/"))
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.
#Gambas
Gambas
sRandom As New String[] '______________________________________________________________________________________________________ Public Sub Main() Dim siCount As Short   For siCount = 0 To 19 sRandom.Add(Rand(1, 100)) Next   Print sRandom.join(",")   NewArray Destructive   End '______________________________________________________________________________________________________ Public Sub NewArray() 'Select certain elements from an array into a new array in a generic way Dim sEven As New String[] Dim siCount As Short   For siCount = 0 To sRandom.Max If Even(sRandom[siCount]) Then sEven.Add(sRandom[siCount]) Next   Print sEven.join(",")   End '______________________________________________________________________________________________________ Public Sub Destructive() 'Give a second solution which filters destructively Dim siIndex As New Short[] Dim siCount As Short   For siCount = 0 To sRandom.Max If Odd(sRandom[siCount]) Then siIndex.Add(siCount) Next   For siCount = siIndex.max DownTo 0 sRandom.Extract(siIndex[siCount], 1) Next   Print sRandom.join(",")   End
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
#Janet
Janet
  (loop [i :range [1 101]  :let [fizz (zero? (% i 3)) buzz (zero? (% i 5))]] (print (cond (and fizz buzz) "fizzbuzz" fizz "fizz" buzz "buzz" i)))  
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.
#Objeck
Objeck
use IO;   bundle Default { class Test { function : Main(args : String[]) ~ Nil { len := File->Size("input.txt"); buffer := Byte->New[len]; in := FileReader->New("input.txt"); if(in->IsOpen() <> Nil) { in->ReadBuffer(0, len, buffer); out := FileWriter->New("output.txt"); if(out->IsOpen() <> Nil) { out->WriteBuffer(0, len, buffer); out->Close(); }; in->Close(); }; } } }
http://rosettacode.org/wiki/Fibonacci_word
Fibonacci word
The   Fibonacci Word   may be created in a manner analogous to the   Fibonacci Sequence   as described here: Define   F_Word1   as   1 Define   F_Word2   as   0 Form     F_Word3   as   F_Word2     concatenated with   F_Word1   i.e.:   01 Form     F_Wordn   as   F_Wordn-1   concatenated with   F_wordn-2 Task Perform the above steps for     n = 37. You may display the first few but not the larger values of   n. {Doing so will get the task's author into trouble with them what be (again!).} Instead, create a table for   F_Words   1   to   37   which shows:   The number of characters in the word   The word's Entropy Related tasks   Fibonacci word/fractal   Entropy   Entropy/Narcissist
#Rust
Rust
struct Fib<T> { curr: T, next: T, }   impl<T> Fib<T> { fn new(curr: T, next: T) -> Self { Fib { curr: curr, next: next, } } }   impl Iterator for Fib<String> { type Item = String; fn next(&mut self) -> Option<Self::Item> { let ret = self.curr.clone(); self.curr = self.next.clone(); self.next = format!("{}{}", ret, self.next); Some(ret) } }   fn get_entropy(s: &[u8]) -> f64 { let mut entropy = 0.0; let mut histogram = [0.0; 256];   for i in 0..s.len() { histogram.get_mut(s[i] as usize).map(|v| *v += 1.0); }   for i in 0..256 { if histogram[i] > 0.0 { let ratio = histogram[i] / s.len() as f64; entropy -= ratio * ratio.log2(); } } entropy }   fn main() { let f = Fib::new("1".to_string(), "0".to_string()); println!("{:10} {:10} {:10} {:60}", "N", "Length", "Entropy", "Word"); for (i, s) in f.take(37).enumerate() { let word = if s.len() > 60 {"Too long"} else {&*s}; println!("{:10} {:10} {:.10} {:60}", i + 1, s.len(), get_entropy(&s.bytes().collect::<Vec<_>>()), word); } }
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
#Scala
Scala
  //word iterator def fibIt = Iterator.iterate(("1","0")){case (f1,f2) => (f2,f1+f2)}.map(_._1)   //entropy calculator def entropy(src: String): Double = { val xs = src.groupBy(identity).map(_._2.length) var result = 0.0 xs.foreach{c => val p = c.toDouble / src.length result -= p * (Math.log(p) / Math.log(2)) } result }   //printing (spaces inserted to get the tabs align properly) val it = fibIt.zipWithIndex.map(w => (w._2, w._1.length, entropy(w._1))) println(it.take(37).map{case (n,l,e) => s"$n).\t$l \t$e"}.mkString("\n"))  
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: Fn = Fn+2 - Fn+1, if n<0 support for negative     n     in the solution is optional. Related tasks   Fibonacci n-step number sequences‎   Leonardo numbers References   Wikipedia, Fibonacci number   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#ALGOL-M
ALGOL-M
INTEGER FUNCTION FIBONACCI( X ); INTEGER X; BEGIN INTEGER M, N, A, I; M := 0; N := 1; FOR I := 2 STEP 1 UNTIL X DO BEGIN A := N; N := M + N; M := A; END; FIBONACCI := N; END;
http://rosettacode.org/wiki/Factors_of_an_integer
Factors of an integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Compute the   factors   of a positive integer. These factors are the positive integers by which the number being factored can be divided to yield a positive integer result. (Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty;   this task does not require handling of either of these cases). Note that every prime number has two factors:   1   and itself. Related tasks   count in factors   prime decomposition   Sieve of Eratosthenes   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division   sequence: smallest number greater than previous term with exactly n divisors
#AutoIt
AutoIt
;AutoIt Version: 3.2.10.0 $num = 45 MsgBox (0,"Factors", "Factors of " & $num & " are: " & factors($num)) consolewrite ("Factors of " & $num & " are: " & factors($num)) Func factors($intg) $ls_factors="" For $i = 1 to $intg/2 if ($intg/$i - int($intg/$i))=0 Then $ls_factors=$ls_factors&$i &", " EndIf Next Return $ls_factors&$intg EndFunc
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.
#J
J
cube =: ($~ q:@#) :. , rou =: ^@j.@o.@(% #)@i.@-: NB. roots of unity floop =: 4 : 'for_r. i.#$x do. (y=.{."1 y) ] x=.(+/x) ,&,:"r (-/x)*y end.' fft =: ] floop&.cube rou@#
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.)
#Icon_and_Unicon
Icon and Unicon
procedure main(A) p := integer(A[1]) | 929 write("M",p," has a factor ",mfactor(p)) end   procedure mfactor(p) if isPrime(p) then { limit := sqrt(2^p)-1 k := 1 while 2*p*k-1 < limit do { q := 2*p*k+1 if isPrime(q) & (q%8 = (1|7)) & btest(p,q) then return q k +:= 1 } } end   procedure btest(p, q) return (2^p % q) = 1 end   procedure isPrime(n) if n%(i := 2|3) = 0 then return n = i; d := 5 while d*d <= n do { if n%d = 0 then fail d +:= 2 if n%d = 0 then fail d +:= 4 } return end
http://rosettacode.org/wiki/Farey_sequence
Farey sequence
The   Farey sequence   Fn   of order   n   is the sequence of completely reduced fractions between   0   and   1   which, when in lowest terms, have denominators less than or equal to   n,   arranged in order of increasing size. The   Farey sequence   is sometimes incorrectly called a   Farey series. Each Farey sequence:   starts with the value   0   (zero),   denoted by the fraction     0 1 {\displaystyle {\frac {0}{1}}}   ends with the value   1   (unity),   denoted by the fraction   1 1 {\displaystyle {\frac {1}{1}}} . The Farey sequences of orders   1   to   5   are: F 1 = 0 1 , 1 1 {\displaystyle {\bf {\it {F}}}_{1}={\frac {0}{1}},{\frac {1}{1}}} F 2 = 0 1 , 1 2 , 1 1 {\displaystyle {\bf {\it {F}}}_{2}={\frac {0}{1}},{\frac {1}{2}},{\frac {1}{1}}} F 3 = 0 1 , 1 3 , 1 2 , 2 3 , 1 1 {\displaystyle {\bf {\it {F}}}_{3}={\frac {0}{1}},{\frac {1}{3}},{\frac {1}{2}},{\frac {2}{3}},{\frac {1}{1}}} F 4 = 0 1 , 1 4 , 1 3 , 1 2 , 2 3 , 3 4 , 1 1 {\displaystyle {\bf {\it {F}}}_{4}={\frac {0}{1}},{\frac {1}{4}},{\frac {1}{3}},{\frac {1}{2}},{\frac {2}{3}},{\frac {3}{4}},{\frac {1}{1}}} F 5 = 0 1 , 1 5 , 1 4 , 1 3 , 2 5 , 1 2 , 3 5 , 2 3 , 3 4 , 4 5 , 1 1 {\displaystyle {\bf {\it {F}}}_{5}={\frac {0}{1}},{\frac {1}{5}},{\frac {1}{4}},{\frac {1}{3}},{\frac {2}{5}},{\frac {1}{2}},{\frac {3}{5}},{\frac {2}{3}},{\frac {3}{4}},{\frac {4}{5}},{\frac {1}{1}}} Task   Compute and show the Farey sequence for orders   1   through   11   (inclusive).   Compute and display the   number   of fractions in the Farey sequence for order   100   through   1,000   (inclusive)   by hundreds.   Show the fractions as   n/d   (using the solidus [or slash] to separate the numerator from the denominator). The length   (the number of fractions)   of a Farey sequence asymptotically approaches: 3 × n2   ÷   π {\displaystyle \pi } 2 See also   OEIS sequence   A006842 numerators of Farey series of order 1, 2, ···   OEIS sequence   A006843 denominators of Farey series of order 1, 2, ···   OEIS sequence   A005728 number of fractions in Farey series of order n   MathWorld entry   Farey sequence   Wikipedia   entry   Farey sequence
#PureBasic
PureBasic
EnableExplicit   Structure farey_struc complex.POINT quotient.d EndStructure   #MAXORDER=1000 Global NewList fareylist.farey_struc()   Define v_start.i, v_end.i, v_step.i, order.i, fractions.i, check.b, t$   Procedure farey(order) NewList sequence.farey_struc() Define quotient.d, divisor.i, dividend.i   For divisor=1 To order For dividend=0 To divisor quotient.d=dividend/divisor AddElement(sequence()) sequence()\complex\x=dividend sequence()\complex\y=divisor sequence()\quotient=quotient Next Next   SortStructuredList(sequence(),#PB_Sort_Ascending, OffsetOf(farey_struc\quotient), TypeOf(farey_struc\quotient))   FirstElement(sequence()) quotient=sequence()\quotient AddElement(fareylist()) fareylist()\complex\x=sequence()\complex\x fareylist()\complex\y=sequence()\complex\y fareylist()\quotient=sequence()\quotient   ForEach sequence() If quotient=sequence()\quotient : Continue : EndIf quotient=sequence()\quotient AddElement(fareylist()) fareylist()\complex\x=sequence()\complex\x fareylist()\complex\y=sequence()\complex\y fareylist()\quotient=sequence()\quotient Next FreeList(sequence()) EndProcedure   OpenConsole("Farey sequence [Input exit = program end]") Repeat Print("Input-> start end step [start>=1; end<=1000; step>=1; (start<end)] : ") t$=Input() : If Trim(LCase(t$))="exit" : End : EndIf v_start=Val(StringField(t$,1," ")) v_end=Val(StringField(t$,2," ")) v_step=Val(StringField(t$,3," ")) check=Bool(v_start>=1 And v_end<=#MAXORDER And v_step>=1 And v_start<v_end) Until check=#True PrintN(~"\n"+LSet("-",80,"-"))   order=v_start While order<=v_end FreeList(fareylist()) : NewList fareylist() farey(order) fractions=ListSize(fareylist()) PrintN("Farey sequence for order "+Str(order)+" has "+Str(fractions)+" fractions.") If fractions<100 ForEach fareylist() If ListIndex(fareylist()) % 7 = 0 : PrintN("") : EndIf Print(~"\t"+ RSet(Str(fareylist()\complex\x),2," ")+"/"+ RSet(Str(fareylist()\complex\y),2," ")) Next EndIf PrintN(~"\n"+LSet("=",80,"=")) order+v_step Wend Input()
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)
#Scheme
Scheme
; Return the first row-count rows of Faulhaber's Triangle as a vector of vectors. (define faulhabers-triangle (lambda (row-count) ; Calculate and store the value of the first column of a row. ; The value is one minus the sum of all the rest of the columns. (define calc-store-first! (lambda (row) (vector-set! row 0 (do ((col-inx 1 (1+ col-inx)) (col-sum 0 (+ col-sum (vector-ref row col-inx)))) ((>= col-inx (vector-length row)) (- 1 col-sum)))))) ; Generate the Faulhaber's Triangle one row at a time. ; The element at row i >= 0, column j >= 1 (both 0-based) is the product ; of the element at i - 1, j - 1 and the fraction ( i / ( j + 1 ) ). ; The element at column 0 is one minus the sum of all the rest of the columns. (let ((tri (make-vector row-count))) (do ((row-inx 0 (1+ row-inx))) ((>= row-inx row-count) tri) (let ((row (make-vector (1+ row-inx)))) (vector-set! tri row-inx row) (do ((col-inx 1 (1+ col-inx))) ((>= col-inx (vector-length row))) (vector-set! row col-inx (* (vector-ref (vector-ref tri (1- row-inx)) (1- col-inx)) (/ row-inx (1+ col-inx))))) (calc-store-first! row))))))   ; Convert elements of a vector to a string for display. (define vector->string (lambda (vec) (do ((inx 0 (1+ inx)) (str "" (string-append str (format "~7@a" (vector-ref vec inx))))) ((>= inx (vector-length vec)) str))))   ; Display a Faulhaber's Triangle. (define faulhabers-triangle-display (lambda (tri) (do ((inx 0 (1+ inx))) ((>= inx (vector-length tri))) (printf "~a~%" (vector->string (vector-ref tri inx))))))   ; Task.. (let ((row-count 10)) (printf "The first ~a rows of Faulhaber's Triangle..~%" row-count) (faulhabers-triangle-display (faulhabers-triangle row-count))) (newline) (let ((power 17) (sum-to 1000)) (printf "Sum over k=1..~a of k^~a using Faulhaber's Triangle..~%" sum-to power) (let* ((tri (faulhabers-triangle (1+ power))) (coefs (vector-ref tri power))) (printf "~a~%" (do ((inx 0 (1+ inx)) (term-expt sum-to (* term-expt sum-to)) (sum 0 (+ sum (* (vector-ref coefs inx) term-expt)))) ((>= inx (vector-length coefs)) sum)))))
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.
#Visual_Basic_.NET
Visual Basic .NET
Module Module1 Function Gcd(a As Long, b As Long) If b = 0 Then Return a End If Return Gcd(b, a Mod b) End Function   Class Frac ReadOnly num As Long ReadOnly denom As Long   Public Shared ReadOnly ZERO As New Frac(0, 1) Public Shared ReadOnly ONE As New Frac(1, 1)   Public Sub New(n As Long, d As Long) If d = 0 Then Throw New ArgumentException("d must not be zero") Dim nn = n Dim dd = d If nn = 0 Then dd = 1 ElseIf dd < 0 Then nn = -nn dd = -dd End If Dim g = Math.Abs(Gcd(nn, dd)) If g > 1 Then nn /= g dd /= g End If num = nn denom = dd End Sub   Public Shared Operator -(self As Frac) As Frac Return New Frac(-self.num, self.denom) End Operator   Public Shared Operator +(lhs As Frac, rhs As Frac) As Frac Return New Frac(lhs.num * rhs.denom + lhs.denom * rhs.num, rhs.denom * lhs.denom) End Operator   Public Shared Operator -(lhs As Frac, rhs As Frac) As Frac Return lhs + -rhs End Operator   Public Shared Operator *(lhs As Frac, rhs As Frac) As Frac Return New Frac(lhs.num * rhs.num, lhs.denom * rhs.denom) End Operator   Public Shared Operator <(lhs As Frac, rhs As Frac) As Boolean Dim x = lhs.num / lhs.denom Dim y = rhs.num / rhs.denom Return x < y End Operator   Public Shared Operator >(lhs As Frac, rhs As Frac) As Boolean Dim x = lhs.num / lhs.denom Dim y = rhs.num / rhs.denom Return x > y End Operator   Public Shared Operator =(lhs As Frac, rhs As Frac) As Boolean Return lhs.num = rhs.num AndAlso lhs.denom = rhs.denom End Operator   Public Shared Operator <>(lhs As Frac, rhs As Frac) As Boolean Return lhs.num <> rhs.num OrElse lhs.denom <> rhs.denom End Operator   Public Overloads Function Equals(obj As Object) As Boolean Dim frac = CType(obj, Frac) Return Not IsNothing(frac) AndAlso num = frac.num AndAlso denom = frac.denom End Function   Public Overloads Function GetHashCode() As Integer Dim hashCode = 1317992671 hashCode = hashCode * -1521134295 + num.GetHashCode() hashCode = hashCode * -1521134295 + denom.GetHashCode() Return hashCode End Function   Public Overloads Function ToString() As String If denom = 1 Then Return num.ToString() Return String.Format("{0}/{1}", num, denom) End Function End Class   Function Bernoulli(n As Integer) As Frac If n < 0 Then Throw New ArgumentException("n may not be negative or zero") Dim a(n + 1) As Frac For m = 0 To n a(m) = New Frac(1, m + 1) For j = m To 1 Step -1 a(j - 1) = (a(j - 1) - a(j)) * New Frac(j, 1) Next Next 'returns the first Bernoulli number If n <> 1 Then Return a(0) Return -a(0) End Function   Function Binomial(n As Integer, k As Integer) As Integer If n < 0 OrElse k < 0 OrElse n < k Then Throw New ArgumentException() End If If n = 0 OrElse k = 0 Then Return 1 End If Dim num = 1 For i = k + 1 To n num *= i Next Dim denom = 1 For i = 2 To n - k denom *= i Next Return num / denom End Function   Sub Faulhaber(p As Integer) Console.Write("{0} : ", p) Dim q As New Frac(1, p + 1) Dim sign = -1 For j = 0 To p sign *= -1 Dim coeff = q * New Frac(sign, 1) * New Frac(Binomial(p + 1, j), 1) * Bernoulli(j) If Frac.ZERO = coeff Then Continue For If j = 0 Then If Frac.ONE <> coeff Then If -Frac.ONE = coeff Then Console.Write("-") Else Console.Write(coeff.ToString()) End If End If Else If Frac.ONE = coeff Then Console.Write(" + ") ElseIf -Frac.ONE = coeff Then Console.Write(" - ") ElseIf Frac.ZERO < coeff Then Console.Write(" + {0}", coeff.ToString()) Else Console.Write(" - {0}", (-coeff).ToString()) End If End If Dim pwr = p + 1 - j If pwr > 1 Then Console.Write("n^{0}", pwr) Else Console.Write("n") End If Next Console.WriteLine() End Sub   Sub Main() For i = 0 To 9 Faulhaber(i) Next End Sub End Module
http://rosettacode.org/wiki/Fibonacci_n-step_number_sequences
Fibonacci n-step number sequences
These number series are an expansion of the ordinary Fibonacci sequence where: For n = 2 {\displaystyle n=2} we have the Fibonacci sequence; with initial values [ 1 , 1 ] {\displaystyle [1,1]} and F k 2 = F k − 1 2 + F k − 2 2 {\displaystyle F_{k}^{2}=F_{k-1}^{2}+F_{k-2}^{2}} For n = 3 {\displaystyle n=3} we have the tribonacci sequence; with initial values [ 1 , 1 , 2 ] {\displaystyle [1,1,2]} and F k 3 = F k − 1 3 + F k − 2 3 + F k − 3 3 {\displaystyle F_{k}^{3}=F_{k-1}^{3}+F_{k-2}^{3}+F_{k-3}^{3}} For n = 4 {\displaystyle n=4} we have the tetranacci sequence; with initial values [ 1 , 1 , 2 , 4 ] {\displaystyle [1,1,2,4]} and F k 4 = F k − 1 4 + F k − 2 4 + F k − 3 4 + F k − 4 4 {\displaystyle F_{k}^{4}=F_{k-1}^{4}+F_{k-2}^{4}+F_{k-3}^{4}+F_{k-4}^{4}} ... For general n > 2 {\displaystyle n>2} we have the Fibonacci n {\displaystyle n} -step sequence - F k n {\displaystyle F_{k}^{n}} ; with initial values of the first n {\displaystyle n} values of the ( n − 1 ) {\displaystyle (n-1)} 'th Fibonacci n {\displaystyle n} -step sequence F k n − 1 {\displaystyle F_{k}^{n-1}} ; and k {\displaystyle k} 'th value of this n {\displaystyle n} 'th sequence being F k n = ∑ i = 1 ( n ) F k − i ( n ) {\displaystyle F_{k}^{n}=\sum _{i=1}^{(n)}{F_{k-i}^{(n)}}} For small values of n {\displaystyle n} , Greek numeric prefixes are sometimes used to individually name each series. Fibonacci n {\displaystyle n} -step sequences n {\displaystyle n} Series name Values 2 fibonacci 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ... 3 tribonacci 1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ... 4 tetranacci 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ... 5 pentanacci 1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ... 6 hexanacci 1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ... 7 heptanacci 1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ... 8 octonacci 1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ... 9 nonanacci 1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ... 10 decanacci 1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ... Allied sequences can be generated where the initial values are changed: The Lucas series sums the two preceding values like the fibonacci series for n = 2 {\displaystyle n=2} but uses [ 2 , 1 ] {\displaystyle [2,1]} as its initial values. Task Write a function to generate Fibonacci n {\displaystyle n} -step number sequences given its initial values and assuming the number of initial values determines how many previous values are summed to make the next number of the series. Use this to print and show here at least the first ten members of the Fibo/tribo/tetra-nacci and Lucas sequences. Related tasks   Fibonacci sequence   Wolfram Mathworld   Hofstadter Q sequence‎   Leonardo numbers Also see   Lucas Numbers - Numberphile (Video)   Tribonacci Numbers (and the Rauzy Fractal) - Numberphile (Video)   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#F.C5.8Drmul.C3.A6
Fōrmulæ
package main   import "fmt"   func g(i []int, c chan<- int) { var sum int b := append([]int(nil), i...) // make a copy for _, t := range b { c <- t sum += t } for { for j, t := range b { c <- sum b[j], sum = sum, sum+sum-t } } }   func main() { for _, s := range [...]struct { seq string i []int }{ {"Fibonacci", []int{1, 1}}, {"Tribonacci", []int{1, 1, 2}}, {"Tetranacci", []int{1, 1, 2, 4}}, {"Lucas", []int{2, 1}}, } { fmt.Printf("%10s:", s.seq) c := make(chan int) // Note/warning: these goroutines are leaked. go g(s.i, c) for j := 0; j < 10; j++ { fmt.Print(" ", <-c) } fmt.Println() } }
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
#Yabasic
Yabasic
x$ = "/home/user1/tmp/coverage/test" y$ = "/home/user1/tmp/covert/operator" z$ = "/home/user1/tmp/coven/members"   a = len(x$) if a > len(y$) a = len(y$) if a > len(z$) a = len(z$) for i = 1 to a if mid$(x$, i, 1) <> mid$(y$, i, 1) break next i a = i - 1   for i = 1 to a if mid$(x$, i, 1) <> mid$(z$, i, 1) break next i a = i - 1   if mid$(x$, i, 1) <> "/" then for i = a to 1 step -1 if "/" = mid$(x$, i, 1) break next i fi   REM Task description says no trailing slash, so... a = i - 1 print "Common path is '", left$(x$, a), "'"
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
#zkl
zkl
dirs:=T("/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members"); n:=Utils.zipWith('==,dirs.xplode()).find(False); // character pos which differs n=dirs[0][0,n].rfind("/"); // find last "/" dirs[0][0,n];
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.
#GAP
GAP
# Built-in   Filtered([1 .. 100], IsPrime); # [ 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 ]   Filtered([1 .. 10], IsEvenInt); # [ 2, 4, 6, 8, 10 ]   Filtered([1 .. 10], IsOddInt); # [ 1, 3, 5, 7, 9 ]
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
#Java
Java
  public class FizzBuzz { public static void main(String[] args) { for (int number = 1; number <= 100; number++) { if (number % 15 == 0) { System.out.println("FizzBuzz"); } else if (number % 3 == 0) { System.out.println("Fizz"); } else if (number % 5 == 0) { System.out.println("Buzz"); } else { System.out.println(number); } } } }  
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.
#Object_Pascal
Object Pascal
uses classes; begin with TFileStream.Create('input.txt', fmOpenRead) do try SaveToFile('output.txt'); finally Free; end; end;
http://rosettacode.org/wiki/File_input/output
File input/output
File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file into a variable   how to write a variable's contents into a file Oneliners that skip the intermediate variable are of secondary interest — operating systems have copy commands for that.
#Objective-C
Objective-C
[[NSFileManager defaultManager] copyItemAtPath:@"input.txt" toPath:@"output.txt" error:NULL];
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
#Scheme
Scheme
  (import (scheme base) (scheme inexact) (scheme write))   (define *words* (make-vector 38 ""))   (define (create-words) (vector-set! *words* 1 "1") (vector-set! *words* 2 "0") (do ((i 3 (+ 1 i))) ((= i (vector-length *words*)) ) (vector-set! *words* i (string-append (vector-ref *words* (- i 1)) (vector-ref *words* (- i 2))))))   ;; in this context, word only contains 1 or 0 (define (entropy word) (let* ((N (string-length word)) (num-ones 0) (num-zeros 0)) (string-for-each (lambda (c) (if (char=? c #\1) (set! num-ones (+ 1 num-ones)) (set! num-zeros (+ 1 num-zeros)))) word) (if (or (zero? num-ones) (zero? num-zeros)) 0 (- 0 (* (/ num-ones N) (log (/ num-ones N) 2)) (* (/ num-zeros N) (log (/ num-zeros N) 2))))))   ;; display values (create-words) (do ((i 1 (+ 1 i))) ((= i (vector-length *words*)) ) (display (string-append (number->string i) " " (number->string (string-length (vector-ref *words* i))) " " (number->string (entropy (vector-ref *words* i))) "\n")))  
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
#Alore
Alore
def fib(n as Int) as Int if n < 2 return 1 end return fib(n-1) + fib(n-2) end
http://rosettacode.org/wiki/Factors_of_an_integer
Factors of an integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Compute the   factors   of a positive integer. These factors are the positive integers by which the number being factored can be divided to yield a positive integer result. (Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty;   this task does not require handling of either of these cases). Note that every prime number has two factors:   1   and itself. Related tasks   count in factors   prime decomposition   Sieve of Eratosthenes   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division   sequence: smallest number greater than previous term with exactly n divisors
#AWK
AWK
  # syntax: GAWK -f FACTORS_OF_AN_INTEGER.AWK BEGIN { print("enter a number or C/R to exit") } { if ($0 == "") { exit(0) } if ($0 !~ /^[0-9]+$/) { printf("invalid: %s\n",$0) next } n = $0 printf("factors of %s:",n) for (i=1; i<=n; i++) { if (n % i == 0) { printf(" %d",i) } } printf("\n") }  
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.
#Java
Java
import static java.lang.Math.*;   public class FastFourierTransform {   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)); }   static void fft(Complex[] buffer) {   int bits = (int) (log(buffer.length) / log(2)); for (int j = 1; j < buffer.length / 2; j++) {   int swapPos = bitReverse(j, bits); Complex temp = buffer[j]; buffer[j] = buffer[swapPos]; buffer[swapPos] = temp; }   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); Complex even = buffer[evenIndex]; Complex odd = buffer[oddIndex];   double term = (-2 * PI * k) / (double) N; Complex exp = (new Complex(cos(term), sin(term)).mult(odd));   buffer[evenIndex] = even.add(exp); buffer[oddIndex] = even.sub(exp); } } } }   public static void main(String[] args) { double[] input = {1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0};   Complex[] cinput = new Complex[input.length]; for (int i = 0; i < input.length; i++) cinput[i] = new Complex(input[i], 0.0);   fft(cinput);   System.out.println("Results:"); for (Complex c : cinput) { System.out.println(c); } } }   class Complex { public final double re; public final double im;   public Complex() { this(0, 0); }   public Complex(double r, double i) { re = r; im = i; }   public Complex add(Complex b) { return new Complex(this.re + b.re, this.im + b.im); }   public Complex sub(Complex b) { return new Complex(this.re - b.re, this.im - b.im); }   public Complex mult(Complex b) { return new Complex(this.re * b.re - this.im * b.im, this.re * b.im + this.im * b.re); }   @Override public String toString() { return String.format("(%f,%f)", re, im); } }
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.)
#J
J
trialfac=: 3 : 0 qs=. (#~8&(1=|+.7=|))(#~1&p:)1+(*(1x+i.@<:@<.)&.-:)y qs#~1=qs&|@(2&^@[**:@])/ 1,~ |.#: 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.)
#Java
Java
  import java.math.BigInteger;   class MersenneFactorCheck {   private final static BigInteger TWO = BigInteger.valueOf(2);   public static boolean isPrime(long n) { if (n == 2) return true; if ((n < 2) || ((n & 1) == 0)) return false; long maxFactor = (long)Math.sqrt((double)n); for (long possibleFactor = 3; possibleFactor <= maxFactor; possibleFactor += 2) if ((n % possibleFactor) == 0) return false; return true; }   public static BigInteger findFactorMersenneNumber(int primeP) { if (primeP <= 0) throw new IllegalArgumentException(); BigInteger bigP = BigInteger.valueOf(primeP); BigInteger m = BigInteger.ONE.shiftLeft(primeP).subtract(BigInteger.ONE); // There are more complicated ways of getting closer to sqrt(), but not that important here, so go with simple BigInteger maxFactor = BigInteger.ONE.shiftLeft((primeP + 1) >>> 1); BigInteger twoP = BigInteger.valueOf(primeP << 1); BigInteger possibleFactor = BigInteger.ONE; int possibleFactorBits12 = 0; int twoPBits12 = primeP & 3;   while ((possibleFactor = possibleFactor.add(twoP)).compareTo(maxFactor) <= 0) { possibleFactorBits12 = (possibleFactorBits12 + twoPBits12) & 3; // "Furthermore, q must be 1 or 7 mod 8". We know it's odd due to the +1 done above, so bit 0 is set. Therefore, we only care about bits 1 and 2 equaling 00 or 11 if ((possibleFactorBits12 == 0) || (possibleFactorBits12 == 3)) if (TWO.modPow(bigP, possibleFactor).equals(BigInteger.ONE)) return possibleFactor; } return null; }   public static void checkMersenneNumber(int p) { if (!isPrime(p)) { System.out.println("M" + p + " is not prime"); return; } BigInteger factor = findFactorMersenneNumber(p); if (factor == null) System.out.println("M" + p + " is prime"); else System.out.println("M" + p + " is not prime, has factor " + factor); return; }   public static void main(String[] args) { for (int p = 1; p <= 50; p++) checkMersenneNumber(p); checkMersenneNumber(929); return; }   }  
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
#Python
Python
from fractions import Fraction     class Fr(Fraction): def __repr__(self): return '(%s/%s)' % (self.numerator, self.denominator)     def farey(n, length=False): if not length: return [Fr(0, 1)] + sorted({Fr(m, k) for k in range(1, n+1) for m in range(1, k+1)}) else: #return 1 + len({Fr(m, k) for k in range(1, n+1) for m in range(1, k+1)}) return (n*(n+3))//2 - sum(farey(n//k, True) for k in range(2, n+1))   if __name__ == '__main__': print('Farey sequence for order 1 through 11 (inclusive):') for n in range(1, 12): print(farey(n)) print('Number of fractions in the Farey sequence for order 100 through 1,000 (inclusive) by hundreds:') print([farey(i, length=True) for i in range(100, 1001, 100)])
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)
#Sidef
Sidef
func faulhaber_triangle(p) { { binomial(p, _) * bernoulli(_) / p }.map(p ^.. 0) }   { |p| say faulhaber_triangle(p).map{ '%6s' % .as_rat }.join } << 1..10   const p = 17 const n = 1000   say '' say faulhaber_triangle(p+1).map_kv {|k,v| v * n**(k+1) }.sum
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.
#Wren
Wren
import "/math" for Int import "/rat" for Rat   var bernoulli = Fn.new { |n| if (n < 0) Fiber.abort("Argument must be non-negative") var a = List.filled(n+1, null) for (m in 0..n) { a[m] = Rat.new(1, m+1) var j = m while (j >= 1) { a[j-1] = (a[j-1] - a[j]) * Rat.new(j, 1) j = j - 1 } } return (n != 1) ? a[0] : -a[0] // 'first' Bernoulli number }   var binomial = Fn.new { |n, k| if (n < 0 || k < 0) Fiber.abort("Arguments must be non-negative integers") if (n < k) Fiber.abort("The second argument cannot be more than the first.") if (n == k) return 1 var prod = 1 var i = n - k + 1 while (i <= n) { prod = prod * i i = i + 1 } return prod / Int.factorial(k) }   var faulhaber = Fn.new { |p| System.write("%(p) : ") var q = Rat.new(1, p+1) var sign = -1 for (j in 0..p) { sign = sign * -1 var b = Rat.new(binomial.call(p+1, j), 1) var coeff = q * Rat.new(sign, 1) * b * bernoulli.call(j) if (coeff != Rat.zero) { if (j == 0) { System.write((coeff == Rat.one) ? "" : (coeff == Rat.minusOne) ? "-" : "%(coeff)") } else { System.write((coeff == Rat.one) ? " + " : (coeff == Rat.minusOne) ? " - " : (coeff > Rat.zero) ? " + %(coeff)" : " - %(-coeff)") } var pwr = p + 1 - j System.write((pwr > 1) ? "n^%(pwr)" : "n") } } System.print() }   for (i in 0..9) faulhaber.call(i)
http://rosettacode.org/wiki/Fibonacci_n-step_number_sequences
Fibonacci n-step number sequences
These number series are an expansion of the ordinary Fibonacci sequence where: For n = 2 {\displaystyle n=2} we have the Fibonacci sequence; with initial values [ 1 , 1 ] {\displaystyle [1,1]} and F k 2 = F k − 1 2 + F k − 2 2 {\displaystyle F_{k}^{2}=F_{k-1}^{2}+F_{k-2}^{2}} For n = 3 {\displaystyle n=3} we have the tribonacci sequence; with initial values [ 1 , 1 , 2 ] {\displaystyle [1,1,2]} and F k 3 = F k − 1 3 + F k − 2 3 + F k − 3 3 {\displaystyle F_{k}^{3}=F_{k-1}^{3}+F_{k-2}^{3}+F_{k-3}^{3}} For n = 4 {\displaystyle n=4} we have the tetranacci sequence; with initial values [ 1 , 1 , 2 , 4 ] {\displaystyle [1,1,2,4]} and F k 4 = F k − 1 4 + F k − 2 4 + F k − 3 4 + F k − 4 4 {\displaystyle F_{k}^{4}=F_{k-1}^{4}+F_{k-2}^{4}+F_{k-3}^{4}+F_{k-4}^{4}} ... For general n > 2 {\displaystyle n>2} we have the Fibonacci n {\displaystyle n} -step sequence - F k n {\displaystyle F_{k}^{n}} ; with initial values of the first n {\displaystyle n} values of the ( n − 1 ) {\displaystyle (n-1)} 'th Fibonacci n {\displaystyle n} -step sequence F k n − 1 {\displaystyle F_{k}^{n-1}} ; and k {\displaystyle k} 'th value of this n {\displaystyle n} 'th sequence being F k n = ∑ i = 1 ( n ) F k − i ( n ) {\displaystyle F_{k}^{n}=\sum _{i=1}^{(n)}{F_{k-i}^{(n)}}} For small values of n {\displaystyle n} , Greek numeric prefixes are sometimes used to individually name each series. Fibonacci n {\displaystyle n} -step sequences n {\displaystyle n} Series name Values 2 fibonacci 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ... 3 tribonacci 1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ... 4 tetranacci 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ... 5 pentanacci 1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ... 6 hexanacci 1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ... 7 heptanacci 1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ... 8 octonacci 1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ... 9 nonanacci 1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ... 10 decanacci 1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ... Allied sequences can be generated where the initial values are changed: The Lucas series sums the two preceding values like the fibonacci series for n = 2 {\displaystyle n=2} but uses [ 2 , 1 ] {\displaystyle [2,1]} as its initial values. Task Write a function to generate Fibonacci n {\displaystyle n} -step number sequences given its initial values and assuming the number of initial values determines how many previous values are summed to make the next number of the series. Use this to print and show here at least the first ten members of the Fibo/tribo/tetra-nacci and Lucas sequences. Related tasks   Fibonacci sequence   Wolfram Mathworld   Hofstadter Q sequence‎   Leonardo numbers Also see   Lucas Numbers - Numberphile (Video)   Tribonacci Numbers (and the Rauzy Fractal) - Numberphile (Video)   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#Go
Go
package main   import "fmt"   func g(i []int, c chan<- int) { var sum int b := append([]int(nil), i...) // make a copy for _, t := range b { c <- t sum += t } for { for j, t := range b { c <- sum b[j], sum = sum, sum+sum-t } } }   func main() { for _, s := range [...]struct { seq string i []int }{ {"Fibonacci", []int{1, 1}}, {"Tribonacci", []int{1, 1, 2}}, {"Tetranacci", []int{1, 1, 2, 4}}, {"Lucas", []int{2, 1}}, } { fmt.Printf("%10s:", s.seq) c := make(chan int) // Note/warning: these goroutines are leaked. go g(s.i, c) for j := 0; j < 10; j++ { fmt.Print(" ", <-c) } fmt.Println() } }
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.
#Go
Go
package main   import ( "fmt" "math/rand" )   func main() { a := rand.Perm(20) fmt.Println(a) // show array to filter fmt.Println(even(a)) // show result of non-destructive filter fmt.Println(a) // show that original array is unchanged reduceToEven(&a) // destructive filter fmt.Println(a) // show that a is now changed // a is not only changed, it is changed in place. length and capacity // show that it still has its original allocated capacity but has now // been reduced in length. fmt.Println("a len:", len(a), "cap:", cap(a)) }   func even(a []int) (r []int) { for _, e := range a { if e%2 == 0 { r = append(r, e) } } return }   func reduceToEven(pa *[]int) { a := *pa var last int for _, e := range a { if e%2 == 0 { a[last] = e last++ } } *pa = a[:last] }
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
#JavaScript
JavaScript
var fizzBuzz = function () { var i, output; for (i = 1; i < 101; i += 1) { output = ''; if (!(i % 3)) { output += 'Fizz'; } if (!(i % 5)) { output += 'Buzz'; } console.log(output || i);//empty string is false, so we short-circuit } };
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.
#OCaml
OCaml
let () = let ic = open_in "input.txt" in let oc = open_out "output.txt" in try while true do let s = input_line ic in output_string oc s; output_char oc '\n'; done with End_of_file -> close_in ic; close_out oc; ;;
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.
#Octave
Octave
  in = fopen("input.txt", "r", "native"); out = fopen("output.txt", "w","native"); if (in == -1) disp("Error opening input.txt for reading."); else if (out == -1) disp("Error opening output.txt for writing."); else while (1) [val,count]=fread(in,1,"uchar",0,"native"); if (count > 0) count=fwrite(out,val,"uchar",0,"native"); if (count == 0) disp("Error writing to output.txt."); end else break; end endwhile end end if (in != -1) fclose(in); end if (out != -1) fclose(out); end  
http://rosettacode.org/wiki/Fibonacci_word
Fibonacci word
The   Fibonacci Word   may be created in a manner analogous to the   Fibonacci Sequence   as described here: Define   F_Word1   as   1 Define   F_Word2   as   0 Form     F_Word3   as   F_Word2     concatenated with   F_Word1   i.e.:   01 Form     F_Wordn   as   F_Wordn-1   concatenated with   F_wordn-2 Task Perform the above steps for     n = 37. You may display the first few but not the larger values of   n. {Doing so will get the task's author into trouble with them what be (again!).} Instead, create a table for   F_Words   1   to   37   which shows:   The number of characters in the word   The word's Entropy Related tasks   Fibonacci word/fractal   Entropy   Entropy/Narcissist
#Scilab
Scilab
exec('.\entropy.sci',0);   function word=fiboword(n) word_1 = '1'; word_2 = '0'; select n case 1 word = word_1 case 2 word = word_2; case 3 word = strcat([word_2 word_1]); else word = strcat([fiboword(n-1) fiboword(n-2)]) end endfunction   final_length = 37;   N=[1:final_length]'; char_length = zeros(N); entropies = zeros(N); tic(); for i=1:final_length word = fiboword(i); char_length(i) = length(word); entropies(i) = entropy(word); end time = toc();   disp('EXECUTION TIME: '+string(time)+'s.'); disp(['N', 'LENGTH', 'ENTROPY'; string([N char_length entropies])]);
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
#Seed7
Seed7
$ include "seed7_05.s7i"; include "float.s7i"; include "math.s7i";   const func float: entropy (in string: stri) is func result var float: entropy is 0.0; local var hash [char] integer: count is (hash [char] integer).value; var char: ch is ' '; var float: p is 0.0; begin for ch range stri do if ch in count then incr(count[ch]); else count @:= [ch] 1; end if; end for; for key ch range count do p := flt(count[ch]) / flt(length(stri)); entropy -:= p * log(p) / log(2.0); end for; end func ;   const func string: fibWord (in integer: number) is func result var string: fibWord is "1"; local var integer: i is 0; var string: a is "1"; var string: c is ""; begin if number >= 2 then fibWord := "0"; for i range 3 to number do c := a; a := fibWord; fibWord &:= c; end for; end if; end func;   const proc: main is func local var integer: index is 0; var string: fibWord is ""; begin for index range 1 to 37 do fibWord := fibWord(index); writeln(index lpad 2 <& length(fibWord) lpad 10 <& " " <& entropy(fibWord) digits 15); end for; end func;
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
#Amazing_Hopper
Amazing Hopper
  #include <hbasic.h>   #define TERM1 1.61803398874989 #define TERM2 -0.61803398874989   #context get Fibonacci number with analitic mode GetArgs(n) get Inv of (M_SQRT5), Mul by( Pow (TERM 1, n), Minus( Pow(TERM 2, n) ) ); then Return\\   #proto fibonacci_recursive(__X__) #synon _fibonacci_recursive getFibonaccinumberwithrecursivemodeof   #proto fibonacci_iterative(__X__) #synon _fibonacci_iterative getFibonaccinumberwithiterativemodeof   Begin Option Stack 1024   get Arg Number(2, n), and Take( n ); then, get Fibonacci number with analitic mode, and Print It with a Newl. secondly, get Fibonacci number with recursive mode of(n), and Print It with a Newl. finally, get Fibonacci number with iterative mode of (n), and Print It with a Newl. End   Subrutines   fibonacci_recursive(n) Iif ( var(n) Is Le? (2), 1 , \ get Fibonacci number with recursive mode of( var(n) Minus (1));\ get Fibonacci number with recursive mode of( var(n) Minus (2)); and Add It ) Return   fibonacci_iterative(n) A=0 B=1 For Up( I:=2, n, 1 ) C=B Let ( B: = var(A) Plus (B) ) A=C Next Return(B)  
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
#BASIC
BASIC
DECLARE SUB factor (what AS INTEGER)   REDIM SHARED factors(0) AS INTEGER   DIM i AS INTEGER, L AS INTEGER   INPUT "Gimme a number"; i   factor i   PRINT factors(0); FOR L = 1 TO UBOUND(factors) PRINT ","; factors(L); NEXT PRINT   SUB factor (what AS INTEGER) DIM tmpint1 AS INTEGER DIM L0 AS INTEGER, L1 AS INTEGER   REDIM tmp(0) AS INTEGER REDIM factors(0) AS INTEGER factors(0) = 1   FOR L0 = 2 TO what IF (0 = (what MOD L0)) THEN 'all this REDIMing and copying can be replaced with: 'REDIM PRESERVE factors(UBOUND(factors)+1) 'in languages that support the PRESERVE keyword REDIM tmp(UBOUND(factors)) AS INTEGER FOR L1 = 0 TO UBOUND(factors) tmp(L1) = factors(L1) NEXT REDIM factors(UBOUND(factors) + 1) FOR L1 = 0 TO UBOUND(factors) - 1 factors(L1) = tmp(L1) NEXT factors(UBOUND(factors)) = L0 END IF NEXT END SUB
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.
#JavaScript
JavaScript
/* complex fast fourier transform and inverse from http://rosettacode.org/wiki/Fast_Fourier_transform#C.2B.2B */ function icfft(amplitudes) { var N = amplitudes.length; var iN = 1 / N;   //conjugate if imaginary part is not 0 for(var i = 0 ; i < N; ++i) if(amplitudes[i] instanceof Complex) amplitudes[i].im = -amplitudes[i].im;   //apply fourier transform amplitudes = cfft(amplitudes)   for(var i = 0 ; i < N; ++i) { //conjugate again amplitudes[i].im = -amplitudes[i].im; //scale amplitudes[i].re *= iN; amplitudes[i].im *= iN; } return amplitudes; }   function cfft(amplitudes) { var N = amplitudes.length; if( N <= 1 ) return amplitudes;   var hN = N / 2; var even = []; var odd = []; even.length = hN; odd.length = hN; for(var i = 0; i < hN; ++i) { even[i] = amplitudes[i*2]; odd[i] = amplitudes[i*2+1]; } even = cfft(even); odd = cfft(odd);   var a = -2*Math.PI; for(var k = 0; k < hN; ++k) { if(!(even[k] instanceof Complex)) even[k] = new Complex(even[k], 0); if(!(odd[k] instanceof Complex)) odd[k] = new Complex(odd[k], 0); var p = k/N; var t = new Complex(0, a * p); t.cexp(t).mul(odd[k], t); amplitudes[k] = even[k].add(t, odd[k]); amplitudes[k + hN] = even[k].sub(t, even[k]); } return amplitudes; }   //test code //console.log( cfft([1,1,1,1,0,0,0,0]) ); //console.log( icfft(cfft([1,1,1,1,0,0,0,0])) );
http://rosettacode.org/wiki/Factors_of_a_Mersenne_number
Factors of a Mersenne number
A Mersenne number is a number in the form of 2P-1. If P is prime, the Mersenne number may be a Mersenne prime (if P is not prime, the Mersenne number is also not prime). In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before starting a, potentially lengthy, Lucas-Lehmer test. There are very efficient algorithms for determining if a number divides 2P-1 (or equivalently, if 2P mod (the number) = 1). Some languages already have built-in implementations of this exponent-and-mod operation (called modPow or similar). The following is how to implement this modPow yourself: For example, let's compute 223 mod 47. Convert the exponent 23 to binary, you get 10111. Starting with square = 1, repeatedly square it. Remove the top bit of the exponent, and if it's 1 multiply square by the base of the exponentiation (2), then compute square modulo 47. Use the result of the modulo from the last step as the initial value of square in the next step: remove optional square top bit multiply by 2 mod 47 ──────────── ─────── ───────────── ────── 1*1 = 1 1 0111 1*2 = 2 2 2*2 = 4 0 111 no 4 4*4 = 16 1 11 16*2 = 32 32 32*32 = 1024 1 1 1024*2 = 2048 27 27*27 = 729 1 729*2 = 1458 1 Since 223 mod 47 = 1, 47 is a factor of 2P-1. (To see this, subtract 1 from both sides: 223-1 = 0 mod 47.) Since we've shown that 47 is a factor, 223-1 is not prime. Further properties of Mersenne numbers allow us to refine the process even more. Any factor q of 2P-1 must be of the form 2kP+1, k being a positive integer or zero. Furthermore, q must be 1 or 7 mod 8. Finally any potential factor q must be prime. As in other trial division algorithms, the algorithm stops when 2kP+1 > sqrt(N). These primality tests only work on Mersenne numbers where P is prime. For example, M4=15 yields no factors using these techniques, but factors into 3 and 5, neither of which fit 2kP+1. Task Using the above method find a factor of 2929-1 (aka M929) Related tasks   count in factors   prime decomposition   factors of an integer   Sieve of Eratosthenes   primality by trial division   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division See also   Computers in 1948: 2127 - 1       (Note:   This video is no longer available because the YouTube account associated with this video has been terminated.)
#JavaScript
JavaScript
function mersenne_factor(p){ var limit, k, q limit = Math.sqrt(Math.pow(2,p) - 1) k = 1 while ((2*k*p - 1) < limit){ q = 2*k*p + 1 if (isPrime(q) && (q % 8 == 1 || q % 8 == 7) && trial_factor(2,p,q)){ return q // q is a factor of 2**p-1 } k++ } return null }   function isPrime(value){ for (var i=2; i < value; i++){ if (value % i == 0){ return false } if (value % i != 0){ return true; } } }   function trial_factor(base, exp, mod){ var square, bits square = 1 bits = exp.toString(2).split('') for (var i=0,ln=bits.length; i<ln; i++){ square = Math.pow(square, 2) * (bits[i] == 1 ? base : 1) % mod } return (square == 1) }   function check_mersenne(p){ var f, result console.log("M"+p+" = 2^"+p+"-1 is ") f = mersenne_factor(p) console.log(f == null ? "prime" : "composite with factor "+f) }
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
#Quackery
Quackery
[ $ "bigrat.qky" loadfile ] now!   [ rot + dip + reduce ] is mediant ( n/d n/d --> n/d )   [ 1+ temp put [] swap dup size 1 - times [ dup i^ peek rot over nested join unrot over i^ 1+ peek join do mediant dup temp share < iff [ join nested rot swap join swap ] else 2drop ] drop ' [ [ 1 1 ] ] join temp release ] is nextfarey ( fy n --> fy )   [ witheach [ unpack vulgar$ echo$ sp ] ] is echofarey ( fy --> )   [ 0 swap dup times [ i over gcd 1 = rot + swap ] drop ] is totient ( n --> n )   [ 0 swap times [ i 1+ totient + ] ] is totientsum ( n --> n )   [ totientsum 1+ ] is fareylength ( n --> n )   say "First eleven Farey series:" cr ' [ [ 0 1 ] [ 1 1 ] ] 10 times [ dup echofarey cr i^ 2 + nextfarey ] echofarey cr cr say "Length of Farey series 100, 200 ... 1000: " [] 10 times [ i^ 1+ 100 * fareylength join ] echo
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
#R
R
  farey <- function(n, length_only = FALSE) { a <- 0 b <- 1 c <- 1 d <- n if (!length_only) cat(a, "/", b, sep = "") count <- 1 while (c <= n) { count <- count + 1 k <- ((n + b) %/% d) next_c <- k * c - a next_d <- k * d - b a <- c b <- d c <- next_c d <- next_d if (!length_only) cat(" ", a, "/", b, sep = "") } if (length_only) cat(count, "items") cat("\n") }     for (i in 1:11) { cat(i, ": ", sep = "") farey(i) }   for (i in 100 * 1:10) { cat(i, ": ", sep = "") farey(i, length_only = TRUE) }  
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)
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Class Frac Private ReadOnly num As Long Private ReadOnly denom As Long   Public Shared ReadOnly ZERO = New Frac(0, 1) Public Shared ReadOnly ONE = New Frac(1, 1)   Public Sub New(n As Long, d As Long) If d = 0 Then Throw New ArgumentException("d must not be zero") End If Dim nn = n Dim dd = d If nn = 0 Then dd = 1 ElseIf dd < 0 Then nn = -nn dd = -dd End If Dim g = Math.Abs(Gcd(nn, dd)) If g > 1 Then nn /= g dd /= g End If num = nn denom = dd End Sub   Private Shared Function Gcd(a As Long, b As Long) As Long If b = 0 Then Return a Else Return Gcd(b, a Mod b) End If End Function   Public Shared Operator -(self As Frac) As Frac Return New Frac(-self.num, self.denom) End Operator   Public Shared Operator +(lhs As Frac, rhs As Frac) As Frac Return New Frac(lhs.num * rhs.denom + lhs.denom * rhs.num, rhs.denom * lhs.denom) End Operator   Public Shared Operator -(lhs As Frac, rhs As Frac) As Frac Return lhs + -rhs End Operator   Public Shared Operator *(lhs As Frac, rhs As Frac) As Frac Return New Frac(lhs.num * rhs.num, lhs.denom * rhs.denom) End Operator   Public Shared Operator <(lhs As Frac, rhs As Frac) As Boolean Dim x = lhs.num / lhs.denom Dim y = rhs.num / rhs.denom Return x < y End Operator   Public Shared Operator >(lhs As Frac, rhs As Frac) As Boolean Dim x = lhs.num / lhs.denom Dim y = rhs.num / rhs.denom Return x > y End Operator   Public Shared Operator =(lhs As Frac, rhs As Frac) As Boolean Return lhs.num = rhs.num AndAlso lhs.denom = rhs.denom End Operator   Public Shared Operator <>(lhs As Frac, rhs As Frac) As Boolean Return lhs.num <> rhs.num OrElse lhs.denom <> rhs.denom End Operator   Public Overrides Function ToString() As String If denom = 1 Then Return num.ToString Else Return String.Format("{0}/{1}", num, denom) End If End Function   Public Overrides Function Equals(obj As Object) As Boolean Dim frac = CType(obj, Frac) Return Not IsNothing(frac) AndAlso num = frac.num AndAlso denom = frac.denom End Function End Class   Function Bernoulli(n As Integer) As Frac If n < 0 Then Throw New ArgumentException("n may not be negative or zero") End If Dim a(n + 1) As Frac For m = 0 To n a(m) = New Frac(1, m + 1) For j = m To 1 Step -1 a(j - 1) = (a(j - 1) - a(j)) * New Frac(j, 1) Next Next ' returns 'first' Bernoulli number If n <> 1 Then Return a(0) Else Return -a(0) End If End Function   Function Binomial(n As Integer, k As Integer) As Integer If n < 0 OrElse k < 0 OrElse n < k Then Throw New ArgumentException() End If If n = 0 OrElse k = 0 Then Return 1 End If Dim num = 1 For i = k + 1 To n num *= i Next Dim denom = 1 For i = 2 To n - k denom *= i Next Return num \ denom End Function   Function FaulhaberTriangle(p As Integer) As Frac() Dim coeffs(p + 1) As Frac For i = 1 To p + 1 coeffs(i - 1) = Frac.ZERO Next Dim q As New Frac(1, p + 1) Dim sign = -1 For j = 0 To p sign *= -1 coeffs(p - j) = q * New Frac(sign, 1) * New Frac(Binomial(p + 1, j), 1) * Bernoulli(j) Next Return coeffs End Function   Sub Main() For i = 1 To 10 Dim coeffs = FaulhaberTriangle(i - 1) For Each coeff In coeffs Console.Write("{0,5} ", coeff) Next Console.WriteLine() Next End Sub   End Module
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.
#zkl
zkl
var [const] BN=Import("zklBigNum"); // libGMP (GNU MP Bignum Library)   fcn faulhaberFormula(p){ //-->(Rational,Rational...) [p..0,-1].pump(List(),'wrap(k){ B(k)*BN(p+1).binomial(k) }) .apply('*(Rational(1,p+1))) }
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
#Groovy
Groovy
def fib = { List seed, int k=10 -> assert seed : "The seed list must be non-null and non-empty" assert seed.every { it instanceof Number } : "Every member of the seed must be a number" def n = seed.size() assert n > 1 : "The seed must contain at least two elements" List result = [] + seed if (k < n) { result[0..k] } else { (n..k).inject(result) { res, kk -> res << res[-n..-1].sum() } } }
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.
#Groovy
Groovy
def evens = [1, 2, 3, 4, 5].findAll{it % 2 == 0}
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) The   FizzBuzz   problem was presented as the lowest level of comprehension required to illustrate adequacy. Also see   (a blog)   dont-overthink-fizzbuzz   (a blog)   fizzbuzz-the-programmers-stairway-to-heaven
#Joy
Joy
DEFINE one == [[[dup 15 rem 0 =] "FizzBuzz"] [[dup 3 rem 0 =] "Fizz"] [[dup 5 rem 0 =] "Buzz"] [dup]] cond. 1 [100 <=] [dup one put succ] while.
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.
#Oforth
Oforth
: fcopy(in, out) | f g | File newMode(in, File.BINARY) dup open(File.READ) ->f File newMode(out, File.BINARY) dup open(File.WRITE) ->g   while(f >> dup notNull) [ g addChar ] drop f close g close ;
http://rosettacode.org/wiki/File_input/output
File input/output
File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file into a variable   how to write a variable's contents into a file Oneliners that skip the intermediate variable are of secondary interest — operating systems have copy commands for that.
#OpenEdge.2FProgress
OpenEdge/Progress
COPY-LOB FROM FILE "input.txt" TO FILE "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
#Sidef
Sidef
func entropy(s) { [0] + (s.chars.freq.values »/» s.len) -> reduce { |a,b| a - b*b.log2 } }   var n_max = 37 var words = ['1', '0']   { words.append(words[-1] + words[-2]) } * (n_max - words.len)   say ('%3s %10s %15s  %s' % <N Length Entropy Fibword>...)   for i in ^words { var word = words[i] say ('%3i %10i %15.12f  %s' % (i+1, word.len, entropy(word), word.len<30 ? word : '<too long>')) }
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
#Swift
Swift
import Foundation   struct Fib: Sequence, IteratorProtocol { private var cur: String private var nex: String   init(cur: String, nex: String) { self.cur = cur self.nex = nex }   mutating func next() -> String? { let ret = cur   cur = nex nex = "\(ret)\(nex)"   return ret } }   func getEntropy(_ s: [Int]) -> Double { var entropy = 0.0 var hist = Array(repeating: 0.0, count: 256)   for i in 0..<s.count { hist[s[i]] += 1 }   for i in 0..<256 where hist[i] > 0 { let rat = hist[i] / Double(s.count) entropy -= rat * log2(rat) }   return entropy }   for (i, str) in Fib(cur: "1", nex: "0").prefix(37).enumerated() { let ent = getEntropy(str.map({ Int($0.asciiValue!) }))   print("i: \(i) len: \(str.count) entropy: \(ent)") }
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
#AntLang
AntLang
/Sequence fib:{<0;1> {x,<x[-1]+x[-2]>}/ range[x]} /nth fibn:{fib[x][x]}
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
#Batch_File
Batch File
@echo off set res=Factors of %1: for /L %%i in (1,1,%1) do call :fac %1 %%i echo %res% goto :eof   :fac set /a test = %1 %% %2 if %test% equ 0 set res=%res% %2
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.
#jq
jq
  # multiplication of real or complex numbers def cmult(x; y): if (x|type) == "number" then if (y|type) == "number" then [ x*y, 0 ] else [x * y[0], x * y[1]] end elif (y|type) == "number" then cmult(y;x) else [ x[0] * y[0] - x[1] * y[1], x[0] * y[1] + x[1] * y[0]] end;   def cplus(x; y): if (x|type) == "number" then if (y|type) == "number" then [ x+y, 0 ] else [ x + y[0], y[1]] end elif (y|type) == "number" then cplus(y;x) else [ x[0] + y[0], x[1] + y[1] ] end;   def cminus(x; y): cplus(x; cmult(-1; y));   # e(ix) = cos(x) + i sin(x) def expi(x): [ (x|cos), (x|sin) ];
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.)
#Julia
Julia
# v0.6   using Primes   function mersennefactor(p::Int)::Int q = 2p + 1 while true if log2(q) > p / 2 return -1 elseif q % 8 in (1, 7) && Primes.isprime(q) && powermod(2, p, q) == 1 return q end q += 2p end end   for i in filter(Primes.isprime, push!(collect(1:20), 929)) mf = mersennefactor(i) if mf != -1 println("M$i = ", mf, " × ", (big(2) ^ i - 1) ÷ mf) else println("M$i is prime") end end
http://rosettacode.org/wiki/Factors_of_a_Mersenne_number
Factors of a Mersenne number
A Mersenne number is a number in the form of 2P-1. If P is prime, the Mersenne number may be a Mersenne prime (if P is not prime, the Mersenne number is also not prime). In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before starting a, potentially lengthy, Lucas-Lehmer test. There are very efficient algorithms for determining if a number divides 2P-1 (or equivalently, if 2P mod (the number) = 1). Some languages already have built-in implementations of this exponent-and-mod operation (called modPow or similar). The following is how to implement this modPow yourself: For example, let's compute 223 mod 47. Convert the exponent 23 to binary, you get 10111. Starting with square = 1, repeatedly square it. Remove the top bit of the exponent, and if it's 1 multiply square by the base of the exponentiation (2), then compute square modulo 47. Use the result of the modulo from the last step as the initial value of square in the next step: remove optional square top bit multiply by 2 mod 47 ──────────── ─────── ───────────── ────── 1*1 = 1 1 0111 1*2 = 2 2 2*2 = 4 0 111 no 4 4*4 = 16 1 11 16*2 = 32 32 32*32 = 1024 1 1 1024*2 = 2048 27 27*27 = 729 1 729*2 = 1458 1 Since 223 mod 47 = 1, 47 is a factor of 2P-1. (To see this, subtract 1 from both sides: 223-1 = 0 mod 47.) Since we've shown that 47 is a factor, 223-1 is not prime. Further properties of Mersenne numbers allow us to refine the process even more. Any factor q of 2P-1 must be of the form 2kP+1, k being a positive integer or zero. Furthermore, q must be 1 or 7 mod 8. Finally any potential factor q must be prime. As in other trial division algorithms, the algorithm stops when 2kP+1 > sqrt(N). These primality tests only work on Mersenne numbers where P is prime. For example, M4=15 yields no factors using these techniques, but factors into 3 and 5, neither of which fit 2kP+1. Task Using the above method find a factor of 2929-1 (aka M929) Related tasks   count in factors   prime decomposition   factors of an integer   Sieve of Eratosthenes   primality by trial division   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division See also   Computers in 1948: 2127 - 1       (Note:   This video is no longer available because the YouTube account associated with this video has been terminated.)
#Kotlin
Kotlin
// version 1.0.6   fun isPrime(n: Int): Boolean { if (n < 2) return false if (n % 2 == 0) return n == 2 if (n % 3 == 0) return n == 3 var d = 5 while (d * d <= n) { if (n % d == 0) return false d += 2 if (n % d == 0) return false d += 4 } return true }   fun main(args: Array<String>) { // test 929 plus all prime numbers below 100 which are known not to be Mersenne primes val q = intArrayOf(11, 23, 29, 37, 41, 43, 47, 53, 59, 67, 71, 73, 79, 83, 97, 929) for (k in 0 until q.size) { if (isPrime(q[k])) { var i: Long var d: Int var p: Int var r: Int = q[k] while (r > 0) r = r shl 1 d = 2 * q[k] + 1 while (true) { i = 1L p = r while (p != 0) { i = (i * i) % d if (p < 0) i *= 2 if (i > d) i -= d p = p shl 1 } if (i != 1L) d += 2 * q[k] else break } println("2^${"%3d".format(q[k])} - 1 = 0 (mod $d)") } else { println("${q[k]} is not prime") } } }
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
#Racket
Racket
#lang racket (require math/number-theory) (define (display-farey-sequence order show-fractions?) (define f-s (farey-sequence order)) (printf "-- Farey Sequence for order ~a has ~a fractions~%" order (length f-s))  ;; racket will simplify 0/1 and 1/1 to 0 and 1 respectively, so deconstruct into numerator and  ;; denomimator (and take the opportunity to insert commas (when show-fractions? (displayln (string-join (for/list ((f f-s)) (format "~a/~a" (numerator f) (denominator f))) ", "))))   ; compute and show the Farey sequence for order: ; 1 through 11 (inclusive). (for ((order (in-range 1 (add1 11)))) (display-farey-sequence order #t)) ; compute and display the number of fractions in the Farey sequence for order: ; 100 through 1,000 (inclusive) by hundreds. (for ((order (in-range 100 (add1 1000) 100))) (display-farey-sequence order #f))
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
#Raku
Raku
sub farey ($order) { my @l = 0/1, 1/1; (2..$order).map: { push @l, |(1..$^d).map: { $_/$d } } unique @l }   say "Farey sequence order "; .say for (1..11).hyper(:1batch).map: { "$_: ", .&farey.sort.map: *.nude.join('/') }; .say for (100, 200 ... 1000).race(:1batch).map: { "Farey sequence order $_ has " ~ [.&farey].elems ~ ' elements.' }
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)
#Vlang
Vlang
import math.fractions import math.big   fn bernoulli(n int) fractions.Fraction { mut a := []fractions.Fraction{len: n+1} for m,_ in a { a[m] = fractions.fraction(1, i64(m+1)) for j := m; j >= 1; j-- { mut d := a[j-1] d = fractions.fraction(i64(j),i64(1)) * (d-a[j]) a[j-1]=d } } // return the 'first' Bernoulli number if n != 1 { return a[0] } a[0] = a[0].negate() return a[0] }   fn binomial(n int, k int) i64 { if n <= 0 || k <= 0 || n < k { return 1 } mut num, mut den := i64(1), i64(1) for i := k + 1; i <= n; i++ { num *= i64(i) } for i := 2; i <= n-k; i++ { den *= i64(i) } return num / den }   fn faulhaber_triangle(p int) []fractions.Fraction { mut coeffs := []fractions.Fraction{len: p+1} q := fractions.fraction(1, i64(p)+1) mut t := fractions.fraction(1,1) mut u := fractions.fraction(1,1) mut sign := -1 for j,_ in coeffs { sign *= -1 mut d := coeffs[p-j] t=fractions.fraction(i64(sign),1) u = fractions.fraction(binomial(p+1, j),1) d=q*t d*=u d*=bernoulli(j) coeffs[p-j]=d } return coeffs }   fn main() { for i in 0..10 { coeffs := faulhaber_triangle(i) for coeff in coeffs { print("${coeff:5} ") } println('') } println('') }
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)
#Wren
Wren
import "/fmt" for Fmt import "/math" for Int import "/big" for BigRat   var bernoulli = Fn.new { |n| if (n < 0) Fiber.abort("Argument must be non-negative") var a = List.filled(n+1, null) for (m in 0..n) { a[m] = BigRat.new(1, m+1) var j = m while (j >= 1) { a[j-1] = (a[j-1] - a[j]) * BigRat.new(j, 1) j = j - 1 } } return (n != 1) ? a[0] : -a[0] // 'first' Bernoulli number }   var binomial = Fn.new { |n, k| if (n < 0 || k < 0) Fiber.abort("Arguments must be non-negative integers") if (n < k) Fiber.abort("The second argument cannot be more than the first.") if (n == k) return 1 var prod = 1 var i = n - k + 1 while (i <= n) { prod = prod * i i = i + 1 } return prod / Int.factorial(k) }   var faulhaberTriangle = Fn.new { |p| var coeffs = List.filled(p+1, null) var q = BigRat.new(1, p+1) var sign = -1 for (j in 0..p) { sign = sign * -1 var b = BigRat.new(binomial.call(p+1, j), 1) coeffs[p-j] = q * BigRat.new(sign, 1) * b * bernoulli.call(j) } return coeffs }   BigRat.showAsInt = true for (i in 0..9) { var coeffs = faulhaberTriangle.call(i) for (coeff in coeffs) Fmt.write("$5s ", coeff) System.print() } System.print() // get coeffs for (k + 1)th row var k = 17 var cc = faulhaberTriangle.call(k) var n = BigRat.new(1000, 1) var np = BigRat.one var sum = BigRat.zero for (c in cc) { np = np * n sum = sum + np*c } System.print(sum)
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
#Haskell
Haskell
import Data.List (tails) import Control.Monad (zipWithM_)   fiblike :: [Integer] -> [Integer] fiblike st = xs where xs = st ++ map (sum . take n) (tails xs) n = length st   nstep :: Int -> [Integer] nstep n = fiblike $ take n $ 1 : iterate (2*) 1   main :: IO () main = do print $ take 10 $ fiblike [1,1] print $ take 10 $ fiblike [2,1] zipWithM_ (\n name -> do putStr (name ++ "nacci -> ") print $ take 15 $ nstep n) [2..] (words "fibo tribo tetra penta hexa hepta octo nona deca")
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.
#Haskell
Haskell
ary = [1..10] evens = [x | x <- ary, even x]
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
#jq
jq
range(1;101) | if . % 15 == 0 then "FizzBuzz" elif . % 5 == 0 then "Buzz" elif . % 3 == 0 then "Fizz" else . end
http://rosettacode.org/wiki/File_input/output
File input/output
File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file into a variable   how to write a variable's contents into a file Oneliners that skip the intermediate variable are of secondary interest — operating systems have copy commands for that.
#Oz
Oz
declare class TextFile from Open.file Open.text end   In = {New TextFile init(name:"input.txt")} Out = {New TextFile init(name:"output.txt" flags:[write text create truncate])}   proc {CopyAll In Out} case {In getS($)} of false then skip [] Line then {Out putS(Line)} {CopyAll In Out} end end in {CopyAll In Out} {Out close} {In close}
http://rosettacode.org/wiki/File_input/output
File input/output
File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file into a variable   how to write a variable's contents into a file Oneliners that skip the intermediate variable are of secondary interest — operating systems have copy commands for that.
#PARI.2FGP
PARI/GP
f=read("filename.in"); write("filename.out", f);
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
#Tcl
Tcl
proc fibwords {n} { set fw {1 0} while {[llength $fw] < $n} { lappend fw [lindex $fw end][lindex $fw end-1] } return $fw }   proc fibwordinfo {num word} { # Entropy calculator from Tcl solution of that task set log2 [expr log(2)] set len [string length $word] foreach char [split $word ""] {dict incr counts $char} set entropy 0.0 foreach count [dict values $counts] { set freq [expr {$count / double($len)}] set entropy [expr {$entropy - $freq * log($freq)/$log2}] } # Output formatting from Clojure solution puts [format "%2d %10d %.15f %s" $num $len $entropy \ [if {$len < 35} {set word} {subst "<too long>"}]] }   # Output formatting from Clojure solution puts [format "%2s %10s %17s %s" N Length Entropy Fibword] foreach word [fibwords 37] { fibwordinfo [incr i] $word }
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
#Apex
Apex
  /* author: snugsfbay date: March 3, 2016 description: Create a list of x numbers in the Fibonacci sequence. - user may specify the length of the list - enforces a minimum of 2 numbers in the sequence because any fewer is not a sequence - enforces a maximum of 47 because further values are too large for integer data type - Fibonacci sequence always starts with 0 and 1 by definition */ public class FibNumbers{   final static Integer MIN = 2; //minimum length of sequence final static Integer MAX = 47; //maximum length of sequence   /* description: method to create a list of numbers in the Fibonacci sequence param: user specified integer representing length of sequence should be 2-47, inclusive. - Sequence starts with 0 and 1 by definition so the minimum length could be as low as 2. - For 48th number in sequence or greater, code would require a Long data type rather than an Integer. return: list of integers in sequence. */ public static List<Integer> makeSeq(Integer len){   List<Integer> fib = new List<Integer>{0,1}; // initialize list with first two values Integer i;   if(len<MIN || len==null || len>MAX) { if (len>MAX){ len=MAX; //set length to maximum if user entered too high a value }else{ len=MIN; //set length to minimum if user entered too low a value or none } } //This could be refactored using teneray operator, but we want code coverage to be reflected for each condition   //start with initial list size to find previous two values in the sequence, continue incrementing until list reaches user defined length for(i=fib.size(); i<len; i++){ fib.add(fib[i-1]+fib[i-2]); //create new number based on previous numbers and add that to the list }   return fib; }   }  
http://rosettacode.org/wiki/Factors_of_an_integer
Factors of an integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Compute the   factors   of a positive integer. These factors are the positive integers by which the number being factored can be divided to yield a positive integer result. (Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty;   this task does not require handling of either of these cases). Note that every prime number has two factors:   1   and itself. Related tasks   count in factors   prime decomposition   Sieve of Eratosthenes   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division   sequence: smallest number greater than previous term with exactly n divisors
#BBC_BASIC
BBC BASIC
INSTALL @lib$+"SORTLIB" sort% = FN_sortinit(0, 0)   PRINT "The factors of 45 are " FNfactorlist(45) PRINT "The factors of 12345 are " FNfactorlist(12345) END   DEF FNfactorlist(N%) LOCAL C%, I%, L%(), L$ DIM L%(32) FOR I% = 1 TO SQR(N%) IF (N% MOD I% = 0) THEN L%(C%) = I% C% += 1 IF (N% <> I%^2) THEN L%(C%) = (N% DIV I%) C% += 1 ENDIF ENDIF NEXT I% CALL sort%, L%(0) FOR I% = 0 TO C%-1 L$ += STR$(L%(I%)) + ", " NEXT = LEFT$(LEFT$(L$))
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.
#Julia
Julia
using FFTW # or using DSP   fft([1,1,1,1,0,0,0,0])
http://rosettacode.org/wiki/Factors_of_a_Mersenne_number
Factors of a Mersenne number
A Mersenne number is a number in the form of 2P-1. If P is prime, the Mersenne number may be a Mersenne prime (if P is not prime, the Mersenne number is also not prime). In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before starting a, potentially lengthy, Lucas-Lehmer test. There are very efficient algorithms for determining if a number divides 2P-1 (or equivalently, if 2P mod (the number) = 1). Some languages already have built-in implementations of this exponent-and-mod operation (called modPow or similar). The following is how to implement this modPow yourself: For example, let's compute 223 mod 47. Convert the exponent 23 to binary, you get 10111. Starting with square = 1, repeatedly square it. Remove the top bit of the exponent, and if it's 1 multiply square by the base of the exponentiation (2), then compute square modulo 47. Use the result of the modulo from the last step as the initial value of square in the next step: remove optional square top bit multiply by 2 mod 47 ──────────── ─────── ───────────── ────── 1*1 = 1 1 0111 1*2 = 2 2 2*2 = 4 0 111 no 4 4*4 = 16 1 11 16*2 = 32 32 32*32 = 1024 1 1 1024*2 = 2048 27 27*27 = 729 1 729*2 = 1458 1 Since 223 mod 47 = 1, 47 is a factor of 2P-1. (To see this, subtract 1 from both sides: 223-1 = 0 mod 47.) Since we've shown that 47 is a factor, 223-1 is not prime. Further properties of Mersenne numbers allow us to refine the process even more. Any factor q of 2P-1 must be of the form 2kP+1, k being a positive integer or zero. Furthermore, q must be 1 or 7 mod 8. Finally any potential factor q must be prime. As in other trial division algorithms, the algorithm stops when 2kP+1 > sqrt(N). These primality tests only work on Mersenne numbers where P is prime. For example, M4=15 yields no factors using these techniques, but factors into 3 and 5, neither of which fit 2kP+1. Task Using the above method find a factor of 2929-1 (aka M929) Related tasks   count in factors   prime decomposition   factors of an integer   Sieve of Eratosthenes   primality by trial division   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division See also   Computers in 1948: 2127 - 1       (Note:   This video is no longer available because the YouTube account associated with this video has been terminated.)
#Lingo
Lingo
on modPow (b, e, m) bits = getBits(e) sq = 1 repeat while TRUE tb = bits[1] bits.deleteAt(1) sq = sq*sq if tb then sq=sq*b sq = sq mod m if bits.count=0 then return sq end repeat end   on getBits (n) bits = [] f = 1 repeat while TRUE bits.addAt(1, bitAnd(f, n)>0) f = f * 2 if f>n then exit repeat end repeat return bits end
http://rosettacode.org/wiki/Factors_of_a_Mersenne_number
Factors of a Mersenne number
A Mersenne number is a number in the form of 2P-1. If P is prime, the Mersenne number may be a Mersenne prime (if P is not prime, the Mersenne number is also not prime). In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before starting a, potentially lengthy, Lucas-Lehmer test. There are very efficient algorithms for determining if a number divides 2P-1 (or equivalently, if 2P mod (the number) = 1). Some languages already have built-in implementations of this exponent-and-mod operation (called modPow or similar). The following is how to implement this modPow yourself: For example, let's compute 223 mod 47. Convert the exponent 23 to binary, you get 10111. Starting with square = 1, repeatedly square it. Remove the top bit of the exponent, and if it's 1 multiply square by the base of the exponentiation (2), then compute square modulo 47. Use the result of the modulo from the last step as the initial value of square in the next step: remove optional square top bit multiply by 2 mod 47 ──────────── ─────── ───────────── ────── 1*1 = 1 1 0111 1*2 = 2 2 2*2 = 4 0 111 no 4 4*4 = 16 1 11 16*2 = 32 32 32*32 = 1024 1 1 1024*2 = 2048 27 27*27 = 729 1 729*2 = 1458 1 Since 223 mod 47 = 1, 47 is a factor of 2P-1. (To see this, subtract 1 from both sides: 223-1 = 0 mod 47.) Since we've shown that 47 is a factor, 223-1 is not prime. Further properties of Mersenne numbers allow us to refine the process even more. Any factor q of 2P-1 must be of the form 2kP+1, k being a positive integer or zero. Furthermore, q must be 1 or 7 mod 8. Finally any potential factor q must be prime. As in other trial division algorithms, the algorithm stops when 2kP+1 > sqrt(N). These primality tests only work on Mersenne numbers where P is prime. For example, M4=15 yields no factors using these techniques, but factors into 3 and 5, neither of which fit 2kP+1. Task Using the above method find a factor of 2929-1 (aka M929) Related tasks   count in factors   prime decomposition   factors of an integer   Sieve of Eratosthenes   primality by trial division   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division See also   Computers in 1948: 2127 - 1       (Note:   This video is no longer available because the YouTube account associated with this video has been terminated.)
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
For[i = 2, i < Prime[1000000], i = NextPrime[i], If[Mod[2^44497, i] == 1, Print["divisible by "<>i]]]; Print["prime test passed; call Lucas and Lehmer"]
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
#REXX
REXX
/*REXX program computes and displays a Farey sequence (or the number of fractions). */ parse arg LO HI INC . /*obtain optional arguments from the CL*/ if LO=='' | LO=="," then LO= 1 /*Not specified? Then use the default.*/ if HI=='' | HI=="," then HI= LO /* " " " " " " */ if INC=='' | INC=="," then INC= 1 /* " " " " " " */ sw= linesize() - 1 /*obtain the linesize of the terminal. */ oLO= LO /*save original value of the the orders*/ do j=abs(LO) to abs(HI) by INC /*process each of the specified numbers*/ #= fareyF(j) /*go ye forth & compute Farey sequence.*/ say center('Farey sequence for order ' j " has " # ' fractions.', sw, "═") if oLO>=0 then call show /*display the Farey fractions. */ end /*j*/ exit # /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ fareyF: procedure expose n. d.; parse arg x n.1= 0; d.1= 1; n.2= 1; d.2= x /*some kit parts for the fraction list.*/ do k=1 until n.z>x /*construct from thirds and on "up".*/ y= k+1; z= k+2 /*calculate the next K and the next Z. */ _= d.k + x /*calculation used as a shortcut. */ n.z= _ % d.y*n.y - n.k /* " the fraction numerator. */ d.z= _ % d.y*d.y - d.k /* " " " denominator. */ if n.z>x then leave /*Should the construction be stopped ? */ end /*k*/ return z - 1 /*return the count of Farey fractions. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ show: $= '0/1' /*construct the start of the Farey seq.*/ do k=2 for #-1; _= n.k'/'d.k /*build a fraction: numer. / denom. */ if length($ _)>sw then do; say $; $= _; end /*Is new line too wide? Show it*/ else $= $ _ /*No? Keep it & keep building.*/ end /*k*/ if $\=='' then say $; return /*display any residual fractions. */
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)
#zkl
zkl
foreach p in (10){ faulhaberFormula(p).apply("%7s".fmt).concat().println(); }   // each term of faulhaberFormula is BigInt/BigInt [1..].zipWith(fcn(n,rat){ rat*BN(1000).pow(n) }, faulhaberFormula(17)) .walk() // -->(0, -3617/60 * 1000^2, 0, 595/3 * 1000^4 ...) .reduce('+) // rat + rat + ... .println();
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
#Icon_and_Unicon
Icon and Unicon
procedure main(A) every writes("F2:\t"|right((fnsGen(1,1))\14,5) | "\n") every writes("F3:\t"|right((fnsGen(1,1,2))\14,5) | "\n") every writes("F4:\t"|right((fnsGen(1,1,2,4))\14,5) | "\n") every writes("Lucas:\t"|right((fnsGen(2,1))\14,5) | "\n") every writes("F?:\t"|right((fnsGen!A)\14,5) | "\n") end   procedure fnsGen(cache[]) n := *cache every i := seq() do { if i > *cache then every (put(cache,0),cache[i] +:= cache[i-n to i-1]) suspend cache[i] } end
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.
#Icon_and_Unicon
Icon and Unicon
procedure main()   every put(A := [],1 to 10) # make a list of 1..10 every put(B := [],iseven(!A)) # make a second list and filter out odd numbers every writes(!B," ") | write() # show end   procedure iseven(x) #: return x if x is even or fail if x % 2 = 0 then return x end
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
#Julia
Julia
for i in 1:100 if i % 15 == 0 println("FizzBuzz") elseif i % 3 == 0 println("Fizz") elseif i % 5 == 0 println("Buzz") else println(i) end end