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/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Simula
Simula
BEGIN END
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Slate
Slate
 
http://rosettacode.org/wiki/Earliest_difference_between_prime_gaps
Earliest difference between prime gaps
When calculating prime numbers > 2, the difference between adjacent primes is always an even number. This difference, also referred to as the gap, varies in an random pattern; at least, no pattern has ever been discovered, and it is strongly conjectured that no pattern exists. However, it is also conjectured that between some two adjacent primes will be a gap corresponding to every positive even integer. gap minimal starting prime ending prime 2 3 5 4 7 11 6 23 29 8 89 97 10 139 149 12 199 211 14 113 127 16 1831 1847 18 523 541 20 887 907 22 1129 1151 24 1669 1693 26 2477 2503 28 2971 2999 30 4297 4327 This task involves locating the minimal primes corresponding to those gaps. Though every gap value exists, they don't seem to come in any particular order. For example, this table shows the gaps and minimum starting value primes for 2 through 30: For the purposes of this task, considering only primes greater than 2, consider prime gaps that differ by exactly two to be adjacent. Task For each order of magnitude m from 10¹ through 10⁶: Find the first two sets of adjacent minimum prime gaps where the absolute value of the difference between the prime gap start values is greater than m. E.G. For an m of 10¹; The start value of gap 2 is 3, the start value of gap 4 is 7, the difference is 7 - 3 or 4. 4 < 10¹ so keep going. The start value of gap 4 is 7, the start value of gap 6 is 23, the difference is 23 - 7, or 16. 16 > 10¹ so this the earliest adjacent gap difference > 10¹. Stretch goal Do the same for 10⁷ and 10⁸ (and higher?) orders of magnitude Note: the earliest value found for each order of magnitude may not be unique, in fact, is not unique; also, with the gaps in ascending order, the minimal starting values are not strictly ascending.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
primes = Prime[Range[10^7]]; gaps = {Differences[primes], Most[primes]} // Transpose; tmp = GatherBy[gaps, First][[All, 1]]; tmp = SortBy[tmp, First]; starts = Association[Rule @@@ tmp]; set = {Most[tmp[[All, 1]]], Abs@Differences[tmp[[All, 2]]]} // Transpose; data = Table[{n, k} = SelectFirst[set, Last/*GreaterThan[10^i]]; {10^i, n, starts[n], n + 2, starts[n + 2], k}, {i, 1, 7}]; StringTemplate["Earliest difference > `` between adjacent prime gap starting primes: Gap `` starts at ``, gap `` starts at ``, difference is ``."]/*Print @@@ data;
http://rosettacode.org/wiki/Earliest_difference_between_prime_gaps
Earliest difference between prime gaps
When calculating prime numbers > 2, the difference between adjacent primes is always an even number. This difference, also referred to as the gap, varies in an random pattern; at least, no pattern has ever been discovered, and it is strongly conjectured that no pattern exists. However, it is also conjectured that between some two adjacent primes will be a gap corresponding to every positive even integer. gap minimal starting prime ending prime 2 3 5 4 7 11 6 23 29 8 89 97 10 139 149 12 199 211 14 113 127 16 1831 1847 18 523 541 20 887 907 22 1129 1151 24 1669 1693 26 2477 2503 28 2971 2999 30 4297 4327 This task involves locating the minimal primes corresponding to those gaps. Though every gap value exists, they don't seem to come in any particular order. For example, this table shows the gaps and minimum starting value primes for 2 through 30: For the purposes of this task, considering only primes greater than 2, consider prime gaps that differ by exactly two to be adjacent. Task For each order of magnitude m from 10¹ through 10⁶: Find the first two sets of adjacent minimum prime gaps where the absolute value of the difference between the prime gap start values is greater than m. E.G. For an m of 10¹; The start value of gap 2 is 3, the start value of gap 4 is 7, the difference is 7 - 3 or 4. 4 < 10¹ so keep going. The start value of gap 4 is 7, the start value of gap 6 is 23, the difference is 23 - 7, or 16. 16 > 10¹ so this the earliest adjacent gap difference > 10¹. Stretch goal Do the same for 10⁷ and 10⁸ (and higher?) orders of magnitude Note: the earliest value found for each order of magnitude may not be unique, in fact, is not unique; also, with the gaps in ascending order, the minimal starting values are not strictly ascending.
#Pascal
Pascal
program primesieve; // sieving small ranges of 65536 //{$O+,R+} {$IFDEF FPC} {$MODE DELPHI}{$OPTIMIZATION ON,ALL}{$CODEALIGN proc=32} uses sysutils; {$ENDIF} {$IFDEF WINDOWS} {$APPTYPE CONSOLE} {$ENDIF}   const smlPrimes :array [0..10] of Byte = (2,3,5,7,11,13,17,19,23,29,31); maxPreSievePrime = 17; sieveSize = 1 shl 15;//32768*2 ->max count of FoundPrimes = 6542 type tSievePrim = record svdeltaPrime:word;//diff between actual and new prime svSivOfs:word;//-> sieveSize< 1 shl 16 svSivNum:LongWord;// 1 shl (16+32) = 2.8e14 end; var {$Align 16} //primes up to 1E6-> sieving to 1E12 sievePrimes : array[0..78497] of tSievePrim; {$Align 16} preSieve :array[0..3*5*7*11*13*17-1] of Byte; {$Align 16} Sieve :array[0..sieveSize-1] of Byte; {$Align 16} FoundPrimes : array[0..6542] of LongWord; {$Align 16} Gaps : array[0..255] Of Uint64; {$Align 16} Limit,OffSet : Uint64;   SieveMaxIdx, preSieveOffset, SieveNum, FoundPrimesCnt, PrimPos, LastInsertedSievePrime :NativeUInt;   procedure CopyPreSieveInSieve;forward; procedure CollectPrimes;forward; procedure sieveOneSieve;forward;   procedure preSieveInit; var i,pr,j,umf : NativeInt; Begin fillchar(preSieve[0],SizeOf(preSieve),#1); i := 1;// starts with pr = 3 umf := 1; repeat IF preSieve[i] <> 0 then Begin pr := 2*i+1; j := i; repeat preSieve[j] := 0; inc(j,pr); until j> High(preSieve); umf := umf*pr; end; inc(i); until umf>High(preSieve); preSieveOffset := 0; end;   procedure CalcSievePrimOfs(lmt:NativeUint); var i,pr : NativeUInt; sq : Uint64; begin pr := 0; i := 0; repeat with sievePrimes[i] do Begin pr := pr+svdeltaPrime; IF sqr(pr) < (SieveSize*2) then Begin svSivNum := 0; svSivOfs := (pr*pr-1) DIV 2; end else Begin SieveMaxIdx := i; pr := pr-svdeltaPrime; BREAK; end; end; inc(i); until i > lmt;   for i := i to lmt do begin with sievePrimes[i] do Begin pr := pr+svdeltaPrime; sq := sqr(pr); svSivNum := sq DIV (2*SieveSize); svSivOfs := ( (sq - Uint64(svSivNum)*(2*SieveSize))-1)DIV 2; end; end; end;   procedure InitSieve; begin preSieveOffset := 0; SieveNum :=0; CalcSievePrimOfs(PrimPos-1); end;   procedure InsertSievePrimes; var j :NativeUINt; i,pr : NativeUInt; begin i := 0; //ignore first primes already sieved with if SieveNum = 0 then repeat inc(i); until FoundPrimes[i] > maxPreSievePrime;   pr :=0; j := Uint64(SieveNum)*SieveSize*2-LastInsertedSievePrime; with sievePrimes[PrimPos] do Begin pr := FoundPrimes[i]; svdeltaPrime := pr+j; j := pr; end; inc(PrimPos); for i := i+1 to FoundPrimesCnt-1 do Begin IF PrimPos > High(sievePrimes) then BREAK; with sievePrimes[PrimPos] do Begin pr := FoundPrimes[i]; svdeltaPrime := (pr-j); j := pr; end; inc(PrimPos); end; LastInsertedSievePrime :=Uint64(SieveNum)*(SieveSize*2)+pr; end;   procedure sievePrimesInit; var i,j,pr:NativeInt; Begin LastInsertedSievePrime := 0;   PrimPos := 0; preSieveOffset := 0; SieveNum :=0; CopyPreSieveInSieve; i := 1; // start with 3 repeat while Sieve[i] = 0 do inc(i); pr := 2*i+1; inc(i); j := ((pr*pr)-1) DIV 2; if j > High(Sieve) then BREAK; repeat Sieve[j] := 0; inc(j,pr); until j > High(Sieve); until false;   CollectPrimes; InsertSievePrimes; IF PrimPos < High(sievePrimes) then Begin InitSieve; //Erste Sieb nochmals, aber ohne Eintrag CopyPreSieveInSieve; sieveOneSieve; repeat inc(SieveNum); CopyPreSieveInSieve; sieveOneSieve; CollectPrimes; InsertSievePrimes; until PrimPos > High(sievePrimes); end; end;   procedure OutGaps(g1,g2,delta:NativeUint); begin if g2= 0 then writeln(2*g1:4,2*g1+2:4,delta:13,Gaps[g1]:13,Gaps[g1+1]:13) else writeln(2*g2-1:4,2*g1:4,delta:13,Gaps[g1-1]:13,Gaps[g1]:13); end; function GetDiffval(val1,val2: NativeInt): NativeInt; begin if val1*val2 = 0 then EXIT(0); dec(val1,val2); if val1<0 then val1 :=-val1; GetDiffval := val1; end;   procedure CheckGaps; var val1,val2,val3,i,DekaLimit : NativeInt; Begin writeln('Gap1 Gap2 difference first second prime'); dekaLimit := 10; i := 1; repeat val1 := Gaps[i]; if val1 <> 0 then Begin val2 := GetDiffval(val1,Gaps[i-1]); val3 := GetDiffval(val1,Gaps[i+1]); while (val2>DekaLimit) or (val3>DekaLimit) do begin writeln(DekaLimit:21,'<'); if val2 = 0 then begin if val3 > 0 then OutGaps(i,0,val3); end else begin if val3 = 0 then OutGaps(i,1,val2) else Begin if val3 > val2 then OutGaps(i,0,val3) else OutGaps(i,1,val2); end; end; DekaLimit := 10*DekaLimit; end; end; inc(i); until i>=254; end;   procedure CopyPreSieveInSieve; var lmt : NativeInt; Begin lmt := preSieveOffset+sieveSize; lmt := lmt-(High(preSieve)+1); IF lmt<= 0 then begin Move(preSieve[preSieveOffset],Sieve[0],sieveSize); if lmt <> 0 then inc(preSieveOffset,sieveSize) else preSieveOffset := 0; end else begin Move(preSieve[preSieveOffset],Sieve[0],sieveSize-lmt); Move(preSieve[0],Sieve[sieveSize-lmt],lmt); preSieveOffset := lmt end; end;   procedure CollectPrimes; var pSieve : pbyte; pFound : pLongWord; i,idx : NativeInt; Begin pFound := @FoundPrimes[0]; idx := 0; i := 0; IF SieveNum = 0 then Begin repeat pFound[idx] := smlPrimes[idx]; inc(idx); until smlPrimes[idx]>maxPreSievePrime; i := (smlPrimes[idx] -1) DIV 2; end;   pSieve := @Sieve[0]; repeat pFound[idx]:= 2*i+1; inc(idx,pSieve[i]); inc(i); until i>High(Sieve); FoundPrimesCnt:= idx; end;   procedure sieveOneSieve; var i,j,pr,dSievNum :NativeUint; Begin pr := 0; For i := 0 to SieveMaxIdx do with sievePrimes[i] do begin pr := pr+svdeltaPrime; IF svSivNum = sieveNum then Begin j := svSivOfs; repeat Sieve[j] := 0; inc(j,pr); until j > High(Sieve);   dSievNum := j DIV SieveSize; svSivOfs := j-dSievNum*SieveSize; inc(svSivNum,dSievNum); end; end;   i := SieveMaxIdx+1; repeat if i > High(SievePrimes) then BREAK; with sievePrimes[i] do begin if svSivNum > sieveNum then Begin SieveMaxIdx := I-1; Break; end; pr := pr+svdeltaPrime; j := svSivOfs; repeat Sieve[j] := 0; inc(j,pr); until j > High(Sieve); dSievNum := j DIV SieveSize; svSivOfs := j-dSievNum*SieveSize; inc(svSivNum,dSievNum); inc(i); end; until false; end;   var T1,T0,CNT,ActPrime,LastPrime,delta : Int64; i: Int32;   begin T0 := GetTickCount64; Limit := 10*1000*1000*1000;//158*1000*1000*1000; preSieveInit; sievePrimesInit;   InitSieve; offset := 0; Cnt := 1;//==2 LastPrime := 2;     repeat CopyPreSieveInSieve;sieveOneSieve;CollectPrimes; inc(Cnt,FoundPrimesCnt); //collect first occurrence of gap i := 0; repeat ActPrime := Offset+FoundPrimes[i]; delta := (ActPrime - LastPrime) shr 1; If Gaps[delta] = 0 then Gaps[delta] := LastPrime; LastPrime := ActPrime; inc(i); until (i >= FoundPrimesCnt);   inc(SieveNum); inc(offset,2*SieveSize); until SieveNum > (Limit DIV (2*SieveSize)); CheckGaps; T1 := GetTickCount64; OffSet := Uint64(SieveNum-1)*(2*SieveSize);     i := FoundPrimesCnt; repeat dec(i); dec(cnt); until (i = 0) OR (OffSet+FoundPrimes[i]<Limit); writeln; writeln(cnt,' in ',Limit,' takes ',T1-T0,' ms'); {$IFDEF WINDOWS} writeln('Press <Enter>');readln; {$ENDIF} end.
http://rosettacode.org/wiki/Element-wise_operations
Element-wise operations
This task is similar to:   Matrix multiplication   Matrix transposition Task Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks. Implement:   addition   subtraction   multiplication   division   exponentiation Extend the task if necessary to include additional basic operations, which should not require their own specialised task.
#C.23
C#
using System; using System.Collections.Generic; using System.Linq;   public static class ElementWiseOperations { private static readonly Dictionary<string, Func<double, double, double>> operations = new Dictionary<string, Func<double, double, double>> { { "add", (a, b) => a + b }, { "sub", (a, b) => a - b }, { "mul", (a, b) => a * b }, { "div", (a, b) => a / b }, { "pow", (a, b) => Math.Pow(a, b) } };   private static readonly Func<double, double, double> nothing = (a, b) => a;   public static double[,] DoOperation(this double[,] m, string name, double[,] other) => DoOperation(m, operations.TryGetValue(name, out var operation) ? operation : nothing, other);   public static double[,] DoOperation(this double[,] m, Func<double, double, double> operation, double[,] other) { if (m == null || other == null) throw new ArgumentNullException(); int rows = m.GetLength(0), columns = m.GetLength(1); if (rows != other.GetLength(0) || columns != other.GetLength(1)) { throw new ArgumentException("Matrices have different dimensions."); }   double[,] result = new double[rows, columns]; for (int r = 0; r < rows; r++) { for (int c = 0; c < columns; c++) { result[r, c] = operation(m[r, c], other[r, c]); } } return result; }   public static double[,] DoOperation(this double[,] m, string name, double number) => DoOperation(m, operations.TryGetValue(name, out var operation) ? operation : nothing, number);   public static double[,] DoOperation(this double[,] m, Func<double, double, double> operation, double number) { if (m == null) throw new ArgumentNullException(); int rows = m.GetLength(0), columns = m.GetLength(1); double[,] result = new double[rows, columns]; for (int r = 0; r < rows; r++) { for (int c = 0; c < columns; c++) { result[r, c] = operation(m[r, c], number); } } return result; }   public static void Print(this double[,] m) { if (m == null) throw new ArgumentNullException(); int rows = m.GetLength(0), columns = m.GetLength(1); for (int r = 0; r < rows; r++) { Console.WriteLine("[ " + string.Join(", ", Enumerable.Range(0, columns).Select(c => m[r, c])) + " ]"); } }   }   public class Program { public static void Main() { double[,] matrix = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } };   double[,] tens = { { 10, 10, 10, 10 }, { 20, 20, 20, 20 }, { 30, 30, 30, 30 } };   matrix.Print(); WriteLine();   (matrix = matrix.DoOperation("add", tens)).Print(); WriteLine();   matrix.DoOperation((a, b) => b - a, 100).Print(); } }
http://rosettacode.org/wiki/Egyptian_division
Egyptian division
Egyptian division is a method of dividing integers using addition and doubling that is similar to the algorithm of Ethiopian multiplication Algorithm: Given two numbers where the dividend is to be divided by the divisor: Start the construction of a table of two columns: powers_of_2, and doublings; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column. Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order. Continue with successive i’th rows of 2^i and 2^i * divisor. Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend. We now assemble two separate sums that both start as zero, called here answer and accumulator Consider each row of the table, in the reverse order of its construction. If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer. When the first row has been considered as above, then the integer division of dividend by divisor is given by answer. (And the remainder is given by the absolute value of accumulator - dividend). Example: 580 / 34 Table creation: powers_of_2 doublings 1 34 2 68 4 136 8 272 16 544 Initialization of sums: powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 0 0 Considering table rows, bottom-up: When a row is considered it is shown crossed out if it is not accumulated, or bold if the row causes summations. powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 4 136 16 544 8 272 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 16 544 4 136 8 272 16 544 powers_of_2 doublings answer accumulator 1 34 17 578 2 68 4 136 8 272 16 544 Answer So 580 divided by 34 using the Egyptian method is 17 remainder (578 - 580) or 2. Task The task is to create a function that does Egyptian division. The function should closely follow the description above in using a list/array of powers of two, and another of doublings. Functions should be clear interpretations of the algorithm. Use the function to divide 580 by 34 and show the answer here, on this page. Related tasks   Egyptian fractions References   Egyptian Number System
#AutoHotkey
AutoHotkey
divident := 580 divisor := 34   answer := accumulator := 0 obj := [] , div := divisor   while (div < divident) { obj[2**(A_Index-1)] := div ; obj[powers_of_2] := doublings div *= 2 ; double up }   while obj.MaxIndex() ; iterate rows "in the reverse order" { if (accumulator + obj[obj.MaxIndex()] <= divident) ; If (accumulator + current doubling) <= dividend { accumulator += obj[obj.MaxIndex()] ; add current doubling to the accumulator answer += obj.MaxIndex() ; add the powers_of_2 value to the answer. } obj.pop() ; remove current row } MsgBox % divident "/" divisor " = " answer ( divident-accumulator > 0 ? " r" divident-accumulator : "")
http://rosettacode.org/wiki/Egyptian_fractions
Egyptian fractions
An   Egyptian fraction   is the sum of distinct unit fractions such as: 1 2 + 1 3 + 1 16 ( = 43 48 ) {\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})} Each fraction in the expression has a numerator equal to   1   (unity)   and a denominator that is a positive integer,   and all the denominators are distinct   (i.e., no repetitions). Fibonacci's   Greedy algorithm for Egyptian fractions   expands the fraction   x y {\displaystyle {\tfrac {x}{y}}}   to be represented by repeatedly performing the replacement x y = 1 ⌈ y / x ⌉ + ( − y ) mod x y ⌈ y / x ⌉ {\displaystyle {\frac {x}{y}}={\frac {1}{\lceil y/x\rceil }}+{\frac {(-y)\!\!\!\!\mod x}{y\lceil y/x\rceil }}} (simplifying the 2nd term in this replacement as necessary, and where   ⌈ x ⌉ {\displaystyle \lceil x\rceil }   is the   ceiling   function). For this task,   Proper and improper fractions   must be able to be expressed. Proper  fractions   are of the form   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive integers, such that   a < b {\displaystyle a<b} ,     and improper fractions are of the form   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive integers, such that   a ≥ b. (See the REXX programming example to view one method of expressing the whole number part of an improper fraction.) For improper fractions, the integer part of any improper fraction should be first isolated and shown preceding the Egyptian unit fractions, and be surrounded by square brackets [n]. Task requirements   show the Egyptian fractions for: 43 48 {\displaystyle {\tfrac {43}{48}}} and 5 121 {\displaystyle {\tfrac {5}{121}}} and 2014 59 {\displaystyle {\tfrac {2014}{59}}}   for all proper fractions,   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive one-or two-digit (decimal) integers, find and show an Egyptian fraction that has:   the largest number of terms,   the largest denominator.   for all one-, two-, and three-digit integers,   find and show (as above).     {extra credit} Also see   Wolfram MathWorld™ entry: Egyptian fraction
#C.23
C#
using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using System.Text; using System.Threading.Tasks;   namespace EgyptianFractions { class Program { class Rational : IComparable<Rational>, IComparable<int> { public BigInteger Num { get; } public BigInteger Den { get; }   public Rational(BigInteger n, BigInteger d) { var c = Gcd(n, d); Num = n / c; Den = d / c; if (Den < 0) { Num = -Num; Den = -Den; } }   public Rational(BigInteger n) { Num = n; Den = 1; }   public override string ToString() { if (Den == 1) { return Num.ToString(); } else { return string.Format("{0}/{1}", Num, Den); } }   public Rational Add(Rational rhs) { return new Rational(Num * rhs.Den + rhs.Num * Den, Den * rhs.Den); }   public Rational Sub(Rational rhs) { return new Rational(Num * rhs.Den - rhs.Num * Den, Den * rhs.Den); }   public int CompareTo(Rational rhs) { var ad = Num * rhs.Den; var bc = Den * rhs.Num; return ad.CompareTo(bc); }   public int CompareTo(int rhs) { var ad = Num * rhs; var bc = Den * rhs; return ad.CompareTo(bc); } }   static BigInteger Gcd(BigInteger a, BigInteger b) { if (b == 0) { if (a < 0) { return -a; } else { return a; } } else { return Gcd(b, a % b); } }   static List<Rational> Egyptian(Rational r) { List<Rational> result = new List<Rational>();   if (r.CompareTo(1) >= 0) { if (r.Den == 1) { result.Add(r); result.Add(new Rational(0)); return result; } result.Add(new Rational(r.Num / r.Den)); r = r.Sub(result[0]); }   BigInteger modFunc(BigInteger m, BigInteger n) { return ((m % n) + n) % n; }   while (r.Num != 1) { var q = (r.Den + r.Num - 1) / r.Num; result.Add(new Rational(1, q)); r = new Rational(modFunc(-r.Den, r.Num), r.Den * q); }   result.Add(r); return result; }   static string FormatList<T>(IEnumerable<T> col) { StringBuilder sb = new StringBuilder(); var iter = col.GetEnumerator();   sb.Append('['); if (iter.MoveNext()) { sb.Append(iter.Current); } while (iter.MoveNext()) { sb.AppendFormat(", {0}", iter.Current); } sb.Append(']');   return sb.ToString(); }   static void Main() { List<Rational> rs = new List<Rational> { new Rational(43, 48), new Rational(5, 121), new Rational(2014, 59) }; foreach (var r in rs) { Console.WriteLine("{0} => {1}", r, FormatList(Egyptian(r))); }   var lenMax = Tuple.Create(0UL, new Rational(0)); var denomMax = Tuple.Create(BigInteger.Zero, new Rational(0));   var query = (from i in Enumerable.Range(1, 100) from j in Enumerable.Range(1, 100) select new Rational(i, j)) .Distinct() .ToList(); foreach (var r in query) { var e = Egyptian(r); ulong eLen = (ulong) e.Count; var eDenom = e.Last().Den; if (eLen > lenMax.Item1) { lenMax = Tuple.Create(eLen, r); } if (eDenom > denomMax.Item1) { denomMax = Tuple.Create(eDenom, r); } }   Console.WriteLine("Term max is {0} with {1} terms", lenMax.Item2, lenMax.Item1); var dStr = denomMax.Item1.ToString(); Console.WriteLine("Denominator max is {0} with {1} digits {2}...{3}", denomMax.Item2, dStr.Length, dStr.Substring(0, 5), dStr.Substring(dStr.Length - 5, 5)); } } }
http://rosettacode.org/wiki/Eertree
Eertree
An eertree is a data structure designed for efficient processing of certain palindrome tasks, for instance counting the number of sub-palindromes in an input string. The data structure has commonalities to both tries and suffix trees.   See links below. Task Construct an eertree for the string "eertree", then output all sub-palindromes by traversing the tree. See also   Wikipedia entry:   trie.   Wikipedia entry:   suffix tree   Cornell University Library, Computer Science, Data Structures and Algorithms ───► EERTREE: An Efficient Data Structure for Processing Palindromes in Strings.
#Perl
Perl
$str = "eertree";   for $n (1 .. length($str)) { for $m (1 .. length($str)) { $strrev = ""; $strpal = substr($str, $n-1, $m); if ($strpal ne "") { for $p (reverse 1 .. length($strpal)) { $strrev .= substr($strpal, $p-1, 1); } ($strpal eq $strrev) and push @pal, $strpal; } } }   print join ' ', grep {not $seen{$_}++} @pal, "\n";
http://rosettacode.org/wiki/Ethiopian_multiplication
Ethiopian multiplication
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last in the same column, until you write a value of 1. In the right-hand column repeatedly double the last number and write the result below. stop when you add a result in the same row as where the left hand column shows 1. Examine the table produced and discard any row where the value in the left column is even. Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together For example:   17 × 34 17 34 Halving the first column: 17 34 8 4 2 1 Doubling the second column: 17 34 8 68 4 136 2 272 1 544 Strike-out rows whose first cell is even: 17 34 8 68 4 136 2 272 1 544 Sum the remaining numbers in the right-hand column: 17 34 8 -- 4 --- 2 --- 1 544 ==== 578 So 17 multiplied by 34, by the Ethiopian method is 578. Task The task is to define three named functions/methods/procedures/subroutines: one to halve an integer, one to double an integer, and one to state if an integer is even. Use these functions to create a function that does Ethiopian multiplication. References Ethiopian multiplication explained (BBC Video clip) A Night Of Numbers - Go Forth And Multiply (Video) Russian Peasant Multiplication Programming Praxis: Russian Peasant Multiplication
#Quackery
Quackery
[ 1 & not ] is even ( n --> b )   [ 1 << ] is double ( n --> n )   [ 1 >> ] is halve ( n --> n )   [ dup 0 < unrot abs [ dup 0 = iff nip done over double over halve recurse swap even iff nip else + ] swap if negate ] is e* ( n n --> n )
http://rosettacode.org/wiki/Elementary_cellular_automaton
Elementary cellular automaton
An elementary cellular automaton is a one-dimensional cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three bits. The rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101. Task Create a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice. The space state should wrap: this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally. This task is basically a generalization of one-dimensional cellular automata. See also Cellular automata (natureofcode.com)
#EchoLisp
EchoLisp
  (lib 'types) ;; int32 vectors (lib 'plot)   (define-constant BIT0 0) (define-constant BIT1 (rgb 0.8 0.9 0.7)) ;; colored bit 1   ;; integer to pattern (define ( n->pat n) (for/vector ((i 8)) #:when (bitwise-bit-set? n i) (for/vector ((j (in-range 2 -1 -1))) (if (bitwise-bit-set? i j) BIT1 BIT0 ))))   ;; test if three pixels match a pattern (define (pmatch a b c pat) (for/or ((v pat)) (and (= a (vector-ref v 0)) (= b (vector-ref v 1)) (= c (vector-ref v 2)) )))   ;; next generation = next row (define (generate x0 width PAT PIX (x)) (for ((dx (in-range 0 width))) (set! x (+ x0 dx)) (vector-set! PIX (+ x width) ;; next row (if (pmatch (vector-ref PIX (if (zero? dx) (+ x0 width) (1- x))) ;; let's wrap (vector-ref PIX x) (vector-ref PIX (if (= dx (1- width)) x0 (1+ x))) PAT) BIT1 BIT0))))   ;; n is the pattern, starters in the number of set pixels at generation 0 (define (task n (starters 1)) (define width (first (plot-size))) (define height (rest (plot-size))) (define PAT (n->pat n)) (plot-clear)   (define PIX (pixels->int32-vector)) (init-pix starters width height PIX)   (for ((y (1- height))) (generate (* y width) width PAT into: PIX)) (vector->pixels PIX))   ;; put n starters on first row (define (init-pix starters width height PIX) (define dw (floor (/ width (1+ starters)))) (for ((x (in-range dw width (1+ dw)))) (vector-set! PIX x BIT1)))   ;; usage (task 99 3) → 672400 ;; ESC to see it (task 22) → 672400   ;; check pattern generator (n->pat 13) → #( #( 0 0 0) #( 0 -5052980 0) #( 0 -5052980 -5052980))    
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#Tcl
Tcl
proc ifact n { for {set i $n; set sum 1} {$i >= 2} {incr i -1} { set sum [expr {$sum * $i}] } return $sum }
http://rosettacode.org/wiki/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd. Use modular congruences: i ≡ 0 (mod 2) iff i is even. i ≡ 1 (mod 2) iff i is odd.
#.E0.AE.89.E0.AE.AF.E0.AE.BF.E0.AE.B0.E0.AF.8D.2FUyir
உயிர்/Uyir
முதன்மை என்பதின் வகை எண் பணி {{ எ இன் வகை எண்{$5} = 0; படை வகை சரம்;   "எண்ணைக் கொடுங்கள்? ") ஐ திரை.இடு;   எ = எண்{$5} ஐ விசை.எடு;   ஒருக்கால் (எ.இருமம்(0) == 1) ஆகில் { படை = "ஒற்றை"; } இல்லையேல் { படை = "இரட்டை "; }   {எ, " ஒரு ", படை, "ப்படை எண் ஆகும்"} என்பதை திரை.இடு;   முதன்மை = 0; }};
http://rosettacode.org/wiki/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd. Use modular congruences: i ≡ 0 (mod 2) iff i is even. i ≡ 1 (mod 2) iff i is odd.
#VBA
VBA
4 ways = 4 Functions : IsEven ==> Use the even and odd predicates IsEven2 ==> Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even IsEven3 ==> Divide i by 2. The remainder equals 0 if i is even. IsEven4 ==> Use modular congruences
http://rosettacode.org/wiki/Echo_server
Echo server
Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary to support connections from localhost (127.0.0.1 or perhaps ::1). Logging of connection information to standard output is recommended. The implementation must be able to handle simultaneous connections from multiple clients. A multi-threaded or multi-process solution may be used. Each connection must be able to echo more than a single line. The implementation must not stop responding to other clients if one client sends a partial line or stops reading responses.
#Factor
Factor
USING: accessors io io.encodings.utf8 io.servers io.sockets threads ; IN: rosetta.echo   CONSTANT: echo-port 12321   : handle-client ( -- ) [ print flush ] each-line ;   : <echo-server> ( -- threaded-server ) utf8 <threaded-server> "echo server" >>name echo-port >>insecure [ handle-client ] >>handler ;   : start-echo-server ( -- ) <echo-server> [ start-server ] in-thread start-server drop ;  
http://rosettacode.org/wiki/Empty_string
Empty string
Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. 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
#XPL0
XPL0
code Text=12; string 0; \use zero-terminated convention, instead of MSb set char S; [S:= ""; \assign an empty string if S(0) = 0 then Text(0, "empty "); S:= "Hello"; if S(0) # 0 then Text(0, "not empty "); ]
http://rosettacode.org/wiki/Empty_string
Empty string
Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. 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
#Z80_Assembly
Z80 Assembly
EmptyString: byte 0
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Smalltalk
Smalltalk
[]
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#SNOBOL4
SNOBOL4
end
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#SNUSP
SNUSP
$#
http://rosettacode.org/wiki/Earliest_difference_between_prime_gaps
Earliest difference between prime gaps
When calculating prime numbers > 2, the difference between adjacent primes is always an even number. This difference, also referred to as the gap, varies in an random pattern; at least, no pattern has ever been discovered, and it is strongly conjectured that no pattern exists. However, it is also conjectured that between some two adjacent primes will be a gap corresponding to every positive even integer. gap minimal starting prime ending prime 2 3 5 4 7 11 6 23 29 8 89 97 10 139 149 12 199 211 14 113 127 16 1831 1847 18 523 541 20 887 907 22 1129 1151 24 1669 1693 26 2477 2503 28 2971 2999 30 4297 4327 This task involves locating the minimal primes corresponding to those gaps. Though every gap value exists, they don't seem to come in any particular order. For example, this table shows the gaps and minimum starting value primes for 2 through 30: For the purposes of this task, considering only primes greater than 2, consider prime gaps that differ by exactly two to be adjacent. Task For each order of magnitude m from 10¹ through 10⁶: Find the first two sets of adjacent minimum prime gaps where the absolute value of the difference between the prime gap start values is greater than m. E.G. For an m of 10¹; The start value of gap 2 is 3, the start value of gap 4 is 7, the difference is 7 - 3 or 4. 4 < 10¹ so keep going. The start value of gap 4 is 7, the start value of gap 6 is 23, the difference is 23 - 7, or 16. 16 > 10¹ so this the earliest adjacent gap difference > 10¹. Stretch goal Do the same for 10⁷ and 10⁸ (and higher?) orders of magnitude Note: the earliest value found for each order of magnitude may not be unique, in fact, is not unique; also, with the gaps in ascending order, the minimal starting values are not strictly ascending.
#Perl
Perl
#!/usr/bin/perl   use strict; # https://rosettacode.org/wiki/Earliest_difference_between_prime_gaps use warnings; use ntheory qw( primes );   my @gaps; my $primeref = primes( 1e9 ); for my $i ( 2 .. $#$primeref ) { my $diff = $primeref->[$i] - $primeref->[$i - 1]; $gaps[ $diff >> 1 ] //= $primeref->[$i - 1]; } my %first; for my $i ( 1 .. $#gaps ) { defined $gaps[$i] && defined $gaps[$i-1] or next; my $diff = abs $gaps[$i] - $gaps[$i-1]; for my $m ( map 10 ** $_, 1 .. 10 ) { $diff > $m and !$first{$m}++ and print "above $m gap @{[$i * 2 - 2 ]} abs( $gaps[$i-1] - $gaps[$i] )\n"; } }
http://rosettacode.org/wiki/Earliest_difference_between_prime_gaps
Earliest difference between prime gaps
When calculating prime numbers > 2, the difference between adjacent primes is always an even number. This difference, also referred to as the gap, varies in an random pattern; at least, no pattern has ever been discovered, and it is strongly conjectured that no pattern exists. However, it is also conjectured that between some two adjacent primes will be a gap corresponding to every positive even integer. gap minimal starting prime ending prime 2 3 5 4 7 11 6 23 29 8 89 97 10 139 149 12 199 211 14 113 127 16 1831 1847 18 523 541 20 887 907 22 1129 1151 24 1669 1693 26 2477 2503 28 2971 2999 30 4297 4327 This task involves locating the minimal primes corresponding to those gaps. Though every gap value exists, they don't seem to come in any particular order. For example, this table shows the gaps and minimum starting value primes for 2 through 30: For the purposes of this task, considering only primes greater than 2, consider prime gaps that differ by exactly two to be adjacent. Task For each order of magnitude m from 10¹ through 10⁶: Find the first two sets of adjacent minimum prime gaps where the absolute value of the difference between the prime gap start values is greater than m. E.G. For an m of 10¹; The start value of gap 2 is 3, the start value of gap 4 is 7, the difference is 7 - 3 or 4. 4 < 10¹ so keep going. The start value of gap 4 is 7, the start value of gap 6 is 23, the difference is 23 - 7, or 16. 16 > 10¹ so this the earliest adjacent gap difference > 10¹. Stretch goal Do the same for 10⁷ and 10⁸ (and higher?) orders of magnitude Note: the earliest value found for each order of magnitude may not be unique, in fact, is not unique; also, with the gaps in ascending order, the minimal starting values are not strictly ascending.
#Phix
Phix
with javascript_semantics constant limit = iff(platform()=JS?1e7:1e8), gslim = 250 sequence primes = get_primes_le(limit*4), gapstarts = repeat(0,gslim) for i=2 to length(primes) do integer gap = primes[i]-primes[i-1] if gapstarts[gap]=0 then gapstarts[gap] = primes[i-1] end if end for integer pm = 10, gap1 = 2 while true do while gapstarts[gap1]=0 do gap1 += 2 end while integer start1 = gapstarts[gap1], gap2 = gap1 + 2 if gapstarts[gap2]=0 then gap1 = gap2 + 2 else integer start2 = gapstarts[gap2], diff = abs(start2 - start1) if diff>pm then printf(1,"Earliest difference >%,d between adjacent prime gap starting primes:\n",{pm}) printf(1,"Gap %d starts at %,d, gap %d starts at %,d, difference is %,d.\n\n", {gap1, start1, gap2, start2, diff}) if pm=limit then exit end if pm *= 10 else gap1 = gap2 end if end if end while
http://rosettacode.org/wiki/Element-wise_operations
Element-wise operations
This task is similar to:   Matrix multiplication   Matrix transposition Task Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks. Implement:   addition   subtraction   multiplication   division   exponentiation Extend the task if necessary to include additional basic operations, which should not require their own specialised task.
#C.2B.2B
C++
#include <cassert> #include <cmath> #include <iostream> #include <valarray>   template <typename scalar_type> class matrix { public: matrix(size_t rows, size_t columns) : rows_(rows), columns_(columns) { elements_.resize(rows * columns); } matrix(size_t rows, size_t columns, scalar_type value) : rows_(rows), columns_(columns), elements_(value, rows * columns) {}   size_t rows() const { return rows_; } size_t columns() const { return columns_; }   const scalar_type& at(size_t row, size_t column) const { assert(row < rows_); assert(column < columns_); return elements_[index(row, column)]; } scalar_type& at(size_t row, size_t column) { assert(row < rows_); assert(column < columns_); return elements_[index(row, column)]; }   matrix& operator+=(scalar_type e) { elements_ += e; return *this; } matrix& operator-=(scalar_type e) { elements_ -= e; return *this; } matrix& operator*=(scalar_type e) { elements_ *= e; return *this; } matrix& operator/=(scalar_type e) { elements_ /= e; return *this; }   matrix& operator+=(const matrix& other) { assert(rows_ == other.rows_); assert(columns_ == other.columns_); elements_ += other.elements_; return *this; } matrix& operator-=(const matrix& other) { assert(rows_ == other.rows_); assert(columns_ == other.columns_); elements_ -= other.elements_; return *this; } matrix& operator*=(const matrix& other) { assert(rows_ == other.rows_); assert(columns_ == other.columns_); elements_ *= other.elements_; return *this; } matrix& operator/=(const matrix& other) { assert(rows_ == other.rows_); assert(columns_ == other.columns_); elements_ /= other.elements_; return *this; }   matrix& negate() { for (scalar_type& element : elements_) element = -element; return *this; } matrix& invert() { for (scalar_type& element : elements_) element = 1 / element; return *this; }   friend matrix pow(const matrix& a, scalar_type b) { return matrix(a.rows_, a.columns_, std::pow(a.elements_, b)); } friend matrix pow(const matrix& a, const matrix& b) { assert(a.rows_ == b.rows_); assert(a.columns_ == b.columns_); return matrix(a.rows_, a.columns_, std::pow(a.elements_, b.elements_)); } private: matrix(size_t rows, size_t columns, std::valarray<scalar_type>&& values) : rows_(rows), columns_(columns), elements_(std::move(values)) {}   size_t index(size_t row, size_t column) const { return row * columns_ + column; } size_t rows_; size_t columns_; std::valarray<scalar_type> elements_; };   template <typename scalar_type> matrix<scalar_type> operator+(const matrix<scalar_type>& a, scalar_type b) { matrix<scalar_type> c(a); c += b; return c; }   template <typename scalar_type> matrix<scalar_type> operator-(const matrix<scalar_type>& a, scalar_type b) { matrix<scalar_type> c(a); c -= b; return c; }   template <typename scalar_type> matrix<scalar_type> operator*(const matrix<scalar_type>& a, scalar_type b) { matrix<scalar_type> c(a); c *= b; return c; }   template <typename scalar_type> matrix<scalar_type> operator/(const matrix<scalar_type>& a, scalar_type b) { matrix<scalar_type> c(a); c /= b; return c; }   template <typename scalar_type> matrix<scalar_type> operator+(scalar_type a, const matrix<scalar_type>& b) { matrix<scalar_type> c(b); c += a; return c; }   template <typename scalar_type> matrix<scalar_type> operator-(scalar_type a, const matrix<scalar_type>& b) { matrix<scalar_type> c(b); c.negate() += a; return c; }   template <typename scalar_type> matrix<scalar_type> operator*(scalar_type a, const matrix<scalar_type>& b) { matrix<scalar_type> c(b); c *= a; return c; }   template <typename scalar_type> matrix<scalar_type> operator/(scalar_type a, const matrix<scalar_type>& b) { matrix<scalar_type> c(b); c.invert() *= a; return c; }   template <typename scalar_type> matrix<scalar_type> operator+(const matrix<scalar_type>& a, const matrix<scalar_type>& b) { matrix<scalar_type> c(a); c += b; return c; }   template <typename scalar_type> matrix<scalar_type> operator-(const matrix<scalar_type>& a, const matrix<scalar_type>& b) { matrix<scalar_type> c(a); c -= b; return c; }   template <typename scalar_type> matrix<scalar_type> operator*(const matrix<scalar_type>& a, const matrix<scalar_type>& b) { matrix<scalar_type> c(a); c *= b; return c; }   template <typename scalar_type> matrix<scalar_type> operator/(const matrix<scalar_type>& a, const matrix<scalar_type>& b) { matrix<scalar_type> c(a); c /= b; return c; }   template <typename scalar_type> void print(std::ostream& out, const matrix<scalar_type>& matrix) { out << '['; size_t rows = matrix.rows(), columns = matrix.columns(); for (size_t row = 0; row < rows; ++row) { if (row > 0) out << ", "; out << '['; for (size_t column = 0; column < columns; ++column) { if (column > 0) out << ", "; out << matrix.at(row, column); } out << ']'; } out << "]\n"; }   void test_matrix_matrix() { const size_t rows = 3, columns = 2; matrix<double> a(rows, columns); for (size_t i = 0; i < rows; ++i) { for (size_t j = 0; j < columns; ++j) a.at(i, j) = double(columns * i + j + 1); } matrix<double> b(a);   std::cout << "a + b:\n"; print(std::cout, a + b);   std::cout << "\na - b:\n"; print(std::cout, a - b);   std::cout << "\na * b:\n"; print(std::cout, a * b);   std::cout << "\na / b:\n"; print(std::cout, a / b);   std::cout << "\npow(a, b):\n"; print(std::cout, pow(a, b)); }   void test_matrix_scalar() { const size_t rows = 3, columns = 4; matrix<double> a(rows, columns); for (size_t i = 0; i < rows; ++i) { for (size_t j = 0; j < columns; ++j) a.at(i, j) = double(columns * i + j + 1); }   std::cout << "a + 10:\n"; print(std::cout, a + 10.0);   std::cout << "\na - 10:\n"; print(std::cout, a - 10.0);   std::cout << "\n10 - a:\n"; print(std::cout, 10.0 - a);   std::cout << "\na * 10:\n"; print(std::cout, a * 10.0);   std::cout << "\na / 10:\n"; print(std::cout, a / 10.0);   std::cout << "\npow(a, 0.5):\n"; print(std::cout, pow(a, 0.5)); }   int main() { test_matrix_matrix(); std::cout << '\n'; test_matrix_scalar(); return 0; }
http://rosettacode.org/wiki/Dynamic_variable_names
Dynamic variable names
Task Create a variable with a user-defined name. The variable name should not be written in the program text, but should be taken from the user dynamically. See also   Eval in environment is a similar task.
#APL
APL
  is←{ t←⍵ ⋄ ⎕this⍎⍺,'←t' } ⍝⍝ the 'Slick Willie' function ;) 'test' is ⍳2 3 test 1 1 1 2 1 3 2 1 2 2 2 3  
http://rosettacode.org/wiki/Egyptian_division
Egyptian division
Egyptian division is a method of dividing integers using addition and doubling that is similar to the algorithm of Ethiopian multiplication Algorithm: Given two numbers where the dividend is to be divided by the divisor: Start the construction of a table of two columns: powers_of_2, and doublings; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column. Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order. Continue with successive i’th rows of 2^i and 2^i * divisor. Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend. We now assemble two separate sums that both start as zero, called here answer and accumulator Consider each row of the table, in the reverse order of its construction. If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer. When the first row has been considered as above, then the integer division of dividend by divisor is given by answer. (And the remainder is given by the absolute value of accumulator - dividend). Example: 580 / 34 Table creation: powers_of_2 doublings 1 34 2 68 4 136 8 272 16 544 Initialization of sums: powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 0 0 Considering table rows, bottom-up: When a row is considered it is shown crossed out if it is not accumulated, or bold if the row causes summations. powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 4 136 16 544 8 272 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 16 544 4 136 8 272 16 544 powers_of_2 doublings answer accumulator 1 34 17 578 2 68 4 136 8 272 16 544 Answer So 580 divided by 34 using the Egyptian method is 17 remainder (578 - 580) or 2. Task The task is to create a function that does Egyptian division. The function should closely follow the description above in using a list/array of powers of two, and another of doublings. Functions should be clear interpretations of the algorithm. Use the function to divide 580 by 34 and show the answer here, on this page. Related tasks   Egyptian fractions References   Egyptian Number System
#BaCon
BaCon
    '---Ported from the c code example to BaCon by bigbass   '================================================================================== FUNCTION EGYPTIAN_DIVISION(long dividend, long divisor, long remainder) TYPE long '================================================================================== '--- remainder is the third parameter, pass 0 if you do not need the remainder   DECLARE powers[64] TYPE long DECLARE doublings[64] TYPE long   LOCAL i TYPE long   FOR i = 0 TO 63 STEP 1 powers[i] = 1 << i doublings[i] = divisor << i IF (doublings[i] > dividend) THEN BREAK ENDIF NEXT   LOCAL answer TYPE long LOCAL accumulator TYPE long answer = 0 accumulator = 0   WHILE i >= 0 '--- If the current value of the accumulator added to the '--- doublings cell would be less than or equal to the '--- dividend then add it to the accumulator IF (accumulator + doublings[i] <= dividend) THEN accumulator = accumulator + doublings[i] answer = answer + powers[i] ENDIF DECR i WEND   IF remainder THEN remainder = dividend - accumulator PRINT dividend ," / ", divisor, " = " , answer ," remainder " , remainder   PRINT "Decoded the answer to a standard fraction" PRINT (remainder + 0.0 )/ (divisor + 0.0) + answer PRINT   ELSE PRINT dividend ," / ", divisor , " = " , answer ENDIF   RETURN answer   ENDFUNCTION     '--- the large number divided by the smaller number '--- the third argument is 1 if you want to have a remainder '--- and 0 if you dont want to have a remainder   EGYPTIAN_DIVISION(580,34,1) EGYPTIAN_DIVISION(580,34,0)   EGYPTIAN_DIVISION(580,34,1)        
http://rosettacode.org/wiki/Egyptian_fractions
Egyptian fractions
An   Egyptian fraction   is the sum of distinct unit fractions such as: 1 2 + 1 3 + 1 16 ( = 43 48 ) {\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})} Each fraction in the expression has a numerator equal to   1   (unity)   and a denominator that is a positive integer,   and all the denominators are distinct   (i.e., no repetitions). Fibonacci's   Greedy algorithm for Egyptian fractions   expands the fraction   x y {\displaystyle {\tfrac {x}{y}}}   to be represented by repeatedly performing the replacement x y = 1 ⌈ y / x ⌉ + ( − y ) mod x y ⌈ y / x ⌉ {\displaystyle {\frac {x}{y}}={\frac {1}{\lceil y/x\rceil }}+{\frac {(-y)\!\!\!\!\mod x}{y\lceil y/x\rceil }}} (simplifying the 2nd term in this replacement as necessary, and where   ⌈ x ⌉ {\displaystyle \lceil x\rceil }   is the   ceiling   function). For this task,   Proper and improper fractions   must be able to be expressed. Proper  fractions   are of the form   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive integers, such that   a < b {\displaystyle a<b} ,     and improper fractions are of the form   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive integers, such that   a ≥ b. (See the REXX programming example to view one method of expressing the whole number part of an improper fraction.) For improper fractions, the integer part of any improper fraction should be first isolated and shown preceding the Egyptian unit fractions, and be surrounded by square brackets [n]. Task requirements   show the Egyptian fractions for: 43 48 {\displaystyle {\tfrac {43}{48}}} and 5 121 {\displaystyle {\tfrac {5}{121}}} and 2014 59 {\displaystyle {\tfrac {2014}{59}}}   for all proper fractions,   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive one-or two-digit (decimal) integers, find and show an Egyptian fraction that has:   the largest number of terms,   the largest denominator.   for all one-, two-, and three-digit integers,   find and show (as above).     {extra credit} Also see   Wolfram MathWorld™ entry: Egyptian fraction
#C.2B.2B
C++
#include <iostream> #include <optional> #include <vector> #include <string> #include <sstream> #include <boost/multiprecision/cpp_int.hpp>   typedef boost::multiprecision::cpp_int integer;   struct fraction { fraction(const integer& n, const integer& d) : numerator(n), denominator(d) {} integer numerator; integer denominator; };   integer mod(const integer& x, const integer& y) { return ((x % y) + y) % y; }   size_t count_digits(const integer& i) { std::ostringstream os; os << i; return os.str().length(); }   std::string to_string(const integer& i) { const int max_digits = 20; std::ostringstream os; os << i; std::string s = os.str(); if (s.length() > max_digits) { s = s.substr(0, max_digits/2) + "..." + s.substr(s.length()-max_digits/2); } return s; }   std::ostream& operator<<(std::ostream& out, const fraction& f) { return out << to_string(f.numerator) << '/' << to_string(f.denominator); }   void egyptian(const fraction& f, std::vector<fraction>& result) { result.clear(); integer x = f.numerator, y = f.denominator; while (x > 0) { integer z = (y + x - 1)/x; result.emplace_back(1, z); x = mod(-y, x); y = y * z; } }   void print_egyptian(const std::vector<fraction>& result) { if (result.empty()) return; auto i = result.begin(); std::cout << *i++; for (; i != result.end(); ++i) std::cout << " + " << *i; std::cout << '\n'; }   void print_egyptian(const fraction& f) { std::cout << "Egyptian fraction for " << f << ": "; integer x = f.numerator, y = f.denominator; if (x > y) { std::cout << "[" << x/y << "] "; x = x % y; } std::vector<fraction> result; egyptian(fraction(x, y), result); print_egyptian(result); std::cout << '\n'; }   void show_max_terms_and_max_denominator(const integer& limit) { size_t max_terms = 0; std::optional<fraction> max_terms_fraction, max_denominator_fraction; std::vector<fraction> max_terms_result; integer max_denominator = 0; std::vector<fraction> max_denominator_result; std::vector<fraction> result; for (integer b = 2; b < limit; ++b) { for (integer a = 1; a < b; ++a) { fraction f(a, b); egyptian(f, result); if (result.size() > max_terms) { max_terms = result.size(); max_terms_result = result; max_terms_fraction = f; } const integer& denominator = result.back().denominator; if (denominator > max_denominator) { max_denominator = denominator; max_denominator_result = result; max_denominator_fraction = f; } } } std::cout << "Proper fractions with most terms and largest denominator, limit = " << limit << ":\n\n"; std::cout << "Most terms (" << max_terms << "): " << max_terms_fraction.value() << " = "; print_egyptian(max_terms_result); std::cout << "\nLargest denominator (" << count_digits(max_denominator_result.back().denominator) << " digits): " << max_denominator_fraction.value() << " = "; print_egyptian(max_denominator_result); }   int main() { print_egyptian(fraction(43, 48)); print_egyptian(fraction(5, 121)); print_egyptian(fraction(2014, 59)); show_max_terms_and_max_denominator(100); show_max_terms_and_max_denominator(1000); return 0; }
http://rosettacode.org/wiki/Eertree
Eertree
An eertree is a data structure designed for efficient processing of certain palindrome tasks, for instance counting the number of sub-palindromes in an input string. The data structure has commonalities to both tries and suffix trees.   See links below. Task Construct an eertree for the string "eertree", then output all sub-palindromes by traversing the tree. See also   Wikipedia entry:   trie.   Wikipedia entry:   suffix tree   Cornell University Library, Computer Science, Data Structures and Algorithms ───► EERTREE: An Efficient Data Structure for Processing Palindromes in Strings.
#Phix
Phix
with javascript_semantics enum LEN,SUFF,CHARS,NEXT function node(integer len, suffix=1, string chars="", sequence next={}) return {len,suffix,chars,next} -- must match above enum! end function function eertree(string s) sequence tree = {node(-1), -- odd lengths node(0)} -- even lengths integer suff = 2 -- max suffix palindrome for i=1 to length(s) do integer cur = suff, curlen, ch = s[i], k while (true) do curlen = tree[cur][LEN] k = i-1-curlen if k>=1 and s[k]==ch then exit end if cur = tree[cur][SUFF] end while k = find(ch,tree[cur][CHARS]) if k then suff = tree[cur][NEXT][k] else tree = append(tree,node(curlen+2)) suff = length(tree) tree[cur][CHARS] &= ch tree[cur][NEXT] = deep_copy(tree[cur][NEXT])&suff if tree[suff][LEN]==1 then tree[suff][SUFF] = 2 else while (true) do cur = tree[cur][SUFF] curlen = tree[cur][LEN] k = i-1-curlen if k>=0 and s[k]==ch then k = find(ch,tree[cur][CHARS]) if k then tree[suff][SUFF] = tree[cur][NEXT][k] end if exit end if end while end if end if end for return tree end function function children(sequence s, tree, integer n, string root="") for i=1 to length(tree[n][CHARS]) do integer c = tree[n][CHARS][i], nxt = tree[n][NEXT][i] string p = iff(n=1 ? c&"" : c&root&c) s = append(s, p) s = children(s, tree, nxt, p) end for return s end function procedure main() sequence tree = eertree("eertree") puts(1,"tree:\n") for i=1 to length(tree) do sequence ti = deep_copy(tree[i]) ti[NEXT] = sprint(ti[NEXT]) ti = i&ti printf(1,"[%d]: len:%2d suffix:%d chars:%-5s next:%s\n",ti) end for puts(1,"\n") -- odd then even lengths: ?children(children({},tree,1), tree, 2) end procedure main()
http://rosettacode.org/wiki/Ethiopian_multiplication
Ethiopian multiplication
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last in the same column, until you write a value of 1. In the right-hand column repeatedly double the last number and write the result below. stop when you add a result in the same row as where the left hand column shows 1. Examine the table produced and discard any row where the value in the left column is even. Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together For example:   17 × 34 17 34 Halving the first column: 17 34 8 4 2 1 Doubling the second column: 17 34 8 68 4 136 2 272 1 544 Strike-out rows whose first cell is even: 17 34 8 68 4 136 2 272 1 544 Sum the remaining numbers in the right-hand column: 17 34 8 -- 4 --- 2 --- 1 544 ==== 578 So 17 multiplied by 34, by the Ethiopian method is 578. Task The task is to define three named functions/methods/procedures/subroutines: one to halve an integer, one to double an integer, and one to state if an integer is even. Use these functions to create a function that does Ethiopian multiplication. References Ethiopian multiplication explained (BBC Video clip) A Night Of Numbers - Go Forth And Multiply (Video) Russian Peasant Multiplication Programming Praxis: Russian Peasant Multiplication
#R
R
halve <- function(a) floor(a/2) double <- function(a) a*2 iseven <- function(a) (a%%2)==0   ethiopicmult <- function(plier, plicand, tutor=FALSE) { if (tutor) { cat("ethiopic multiplication of", plier, "and", plicand, "\n") } result <- 0 while(plier >= 1) { if (!iseven(plier)) { result <- result + plicand } if (tutor) { cat(plier, ", ", plicand, " ", ifelse(iseven(plier), "struck", "kept"), "\n", sep="") } plier <- halve(plier) plicand <- double(plicand) } result }   print(ethiopicmult(17, 34, TRUE))
http://rosettacode.org/wiki/Elementary_cellular_automaton
Elementary cellular automaton
An elementary cellular automaton is a one-dimensional cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three bits. The rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101. Task Create a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice. The space state should wrap: this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally. This task is basically a generalization of one-dimensional cellular automata. See also Cellular automata (natureofcode.com)
#Elixir
Elixir
defmodule Elementary_cellular_automaton do def run(start_str, rule, times) do IO.puts "rule : #{rule}" each(start_str, rule_pattern(rule), times) end   defp rule_pattern(rule) do list = Integer.to_string(rule, 2) |> String.pad_leading(8, "0") |> String.codepoints |> Enum.reverse Enum.map(0..7, fn i -> Integer.to_string(i, 2) |> String.pad_leading(3, "0") end) |> Enum.zip(list) |> Map.new end   defp each(_, _, 0), do: :ok defp each(str, patterns, times) do IO.puts String.replace(str, "0", ".") |> String.replace("1", "#") str2 = String.last(str) <> str <> String.first(str) next_str = Enum.map_join(0..String.length(str)-1, fn i -> Map.get(patterns, String.slice(str2, i, 3)) end) each(next_str, patterns, times-1) end end   pad = String.duplicate("0", 14) str = pad <> "1" <> pad Elementary_cellular_automaton.run(str, 18, 25)
http://rosettacode.org/wiki/Elementary_cellular_automaton
Elementary cellular automaton
An elementary cellular automaton is a one-dimensional cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three bits. The rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101. Task Create a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice. The space state should wrap: this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally. This task is basically a generalization of one-dimensional cellular automata. See also Cellular automata (natureofcode.com)
#F.23
F#
  // Elementary Cellular Automaton . Nigel Galloway: July 31st., 2019 let eca N= let N=Array.init 8 (fun n->(N>>>n)%2) Seq.unfold(fun G->Some(G,[|yield Array.last G; yield! G; yield Array.head G|]|>Array.windowed 3|>Array.map(fun n->N.[n.[2]+2*n.[1]+4*n.[0]])))  
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#TI-83_BASIC
TI-83 BASIC
10→N N! ---> 362880 prod(seq(I,I,1,N)) ---> 362880
http://rosettacode.org/wiki/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd. Use modular congruences: i ≡ 0 (mod 2) iff i is even. i ≡ 1 (mod 2) iff i is odd.
#VBScript
VBScript
  Function odd_or_even(n) If n Mod 2 = 0 Then odd_or_even = "Even" Else odd_or_even = "Odd" End If End Function   WScript.StdOut.Write "Please enter a number: " n = WScript.StdIn.ReadLine WScript.StdOut.Write n & " is " & odd_or_even(CInt(n)) WScript.StdOut.WriteLine  
http://rosettacode.org/wiki/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd. Use modular congruences: i ≡ 0 (mod 2) iff i is even. i ≡ 1 (mod 2) iff i is odd.
#Verilog
Verilog
module main; integer i;   initial begin for (i = 1; i <= 10; i = i+1) begin if (i % 2 == 0) $display(i, " is even"); else $display(i, " is odd"); end $finish ; end endmodule
http://rosettacode.org/wiki/Echo_server
Echo server
Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary to support connections from localhost (127.0.0.1 or perhaps ::1). Logging of connection information to standard output is recommended. The implementation must be able to handle simultaneous connections from multiple clients. A multi-threaded or multi-process solution may be used. Each connection must be able to echo more than a single line. The implementation must not stop responding to other clients if one client sends a partial line or stops reading responses.
#Forth
Forth
include unix/socket.fs   128 constant size   : (echo) ( sock buf -- sock buf ) begin cr ." waiting..." 2dup 2dup size read-socket nip dup 0> while ." got: " 2dup type rot write-socket repeat drop drop drop ;   create buf size allot   : echo-server ( port -- ) cr ." Listening on " dup . create-server dup 4 listen begin dup accept-socket cr ." Connection!" buf ['] (echo) catch cr ." Disconnected (" . ." )" drop close-socket again ;   12321 echo-server
http://rosettacode.org/wiki/Empty_string
Empty string
Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. 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
s:=""; // or s:=String, String is the object "" s.toBool() //-->False if (s) println("not empty")
http://rosettacode.org/wiki/Empty_string
Empty string
Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. 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
#Zoomscript
Zoomscript
var string string = "" if eq string "" print "The string is empty." else print "The string is not empty." endif
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Sparkling
Sparkling
 
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#SQL_PL
SQL PL
  SELECT 1 FROM sysibm.sysdummy1;  
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#SSEM
SSEM
00000000000000000000000000000000 0. 0 to CI jump to store(0) + 1 00000000000000000000000000000000 1. 0 to CI jump to store(0) + 1
http://rosettacode.org/wiki/Earliest_difference_between_prime_gaps
Earliest difference between prime gaps
When calculating prime numbers > 2, the difference between adjacent primes is always an even number. This difference, also referred to as the gap, varies in an random pattern; at least, no pattern has ever been discovered, and it is strongly conjectured that no pattern exists. However, it is also conjectured that between some two adjacent primes will be a gap corresponding to every positive even integer. gap minimal starting prime ending prime 2 3 5 4 7 11 6 23 29 8 89 97 10 139 149 12 199 211 14 113 127 16 1831 1847 18 523 541 20 887 907 22 1129 1151 24 1669 1693 26 2477 2503 28 2971 2999 30 4297 4327 This task involves locating the minimal primes corresponding to those gaps. Though every gap value exists, they don't seem to come in any particular order. For example, this table shows the gaps and minimum starting value primes for 2 through 30: For the purposes of this task, considering only primes greater than 2, consider prime gaps that differ by exactly two to be adjacent. Task For each order of magnitude m from 10¹ through 10⁶: Find the first two sets of adjacent minimum prime gaps where the absolute value of the difference between the prime gap start values is greater than m. E.G. For an m of 10¹; The start value of gap 2 is 3, the start value of gap 4 is 7, the difference is 7 - 3 or 4. 4 < 10¹ so keep going. The start value of gap 4 is 7, the start value of gap 6 is 23, the difference is 23 - 7, or 16. 16 > 10¹ so this the earliest adjacent gap difference > 10¹. Stretch goal Do the same for 10⁷ and 10⁸ (and higher?) orders of magnitude Note: the earliest value found for each order of magnitude may not be unique, in fact, is not unique; also, with the gaps in ascending order, the minimal starting values are not strictly ascending.
#Python
Python
""" https://rosettacode.org/wiki/Earliest_difference_between_prime_gaps """   from primesieve import primes   LIMIT = 10**9 pri = primes(LIMIT * 5) gapstarts = {} for i in range(1, len(pri)): if pri[i] - pri[i - 1] not in gapstarts: gapstarts[pri[i] - pri[i - 1]] = pri[i - 1]   PM, GAP1, = 10, 2 while True: while GAP1 not in gapstarts: GAP1 += 2 start1 = gapstarts[GAP1] GAP2 = GAP1 + 2 if GAP2 not in gapstarts: GAP1 = GAP2 + 2 continue start2 = gapstarts[GAP2] diff = abs(start2 - start1) if diff > PM: print(f"Earliest difference >{PM: ,} between adjacent prime gap starting primes:") print(f"Gap {GAP1} starts at{start1: ,}, gap {GAP2} starts at{start2: ,}, difference is{diff: ,}.\n") if PM == LIMIT: break PM *= 10 else: GAP1 = GAP2  
http://rosettacode.org/wiki/Earliest_difference_between_prime_gaps
Earliest difference between prime gaps
When calculating prime numbers > 2, the difference between adjacent primes is always an even number. This difference, also referred to as the gap, varies in an random pattern; at least, no pattern has ever been discovered, and it is strongly conjectured that no pattern exists. However, it is also conjectured that between some two adjacent primes will be a gap corresponding to every positive even integer. gap minimal starting prime ending prime 2 3 5 4 7 11 6 23 29 8 89 97 10 139 149 12 199 211 14 113 127 16 1831 1847 18 523 541 20 887 907 22 1129 1151 24 1669 1693 26 2477 2503 28 2971 2999 30 4297 4327 This task involves locating the minimal primes corresponding to those gaps. Though every gap value exists, they don't seem to come in any particular order. For example, this table shows the gaps and minimum starting value primes for 2 through 30: For the purposes of this task, considering only primes greater than 2, consider prime gaps that differ by exactly two to be adjacent. Task For each order of magnitude m from 10¹ through 10⁶: Find the first two sets of adjacent minimum prime gaps where the absolute value of the difference between the prime gap start values is greater than m. E.G. For an m of 10¹; The start value of gap 2 is 3, the start value of gap 4 is 7, the difference is 7 - 3 or 4. 4 < 10¹ so keep going. The start value of gap 4 is 7, the start value of gap 6 is 23, the difference is 23 - 7, or 16. 16 > 10¹ so this the earliest adjacent gap difference > 10¹. Stretch goal Do the same for 10⁷ and 10⁸ (and higher?) orders of magnitude Note: the earliest value found for each order of magnitude may not be unique, in fact, is not unique; also, with the gaps in ascending order, the minimal starting values are not strictly ascending.
#Raku
Raku
use Math::Primesieve; use Lingua::EN::Numbers;   my $iterator = Math::Primesieve::iterator.new; my @gaps; my $last = 2;   for 1..9 { my $m = exp $_, 10; my $this; loop { $this = (my $p = $iterator.next) - $last; if !@gaps[$this].defined { @gaps[$this]= $last; check-gap($m, $this, @gaps) && last if $this > 2 and @gaps[$this - 2].defined and (abs($last - @gaps[$this - 2]) > $m); } $last = $p; } }   sub check-gap ($n, $this, @p) { my %upto = @p[^$this].pairs.grep: *.value; my @upto = (1..$this).map: { last unless %upto{$_ * 2}; %upto{$_ * 2} } my $key = @upto.rotor(2=>-1).first( {.sink; abs(.[0] - .[1]) > $n}, :k ); return False unless $key; say "Earliest difference > {comma $n} between adjacent prime gap starting primes:"; printf "Gap %s starts at %s, gap %s starts at %s, difference is %s\n\n", |(2 * $key + 2, @upto[$key], 2 * $key + 4, @upto[$key+1], abs(@upto[$key] - @upto[$key+1]))».&comma; True }
http://rosettacode.org/wiki/Eban_numbers
Eban numbers
Definition An   eban   number is a number that has no letter   e   in it when the number is spelled in English. Or more literally,   spelled numbers that contain the letter   e   are banned. The American version of spelling numbers will be used here   (as opposed to the British). 2,000,000,000   is two billion,   not   two milliard. Only numbers less than   one sextillion   (1021)   will be considered in/for this task. This will allow optimizations to be used. Task   show all eban numbers   ≤   1,000   (in a horizontal format),   and a count   show all eban numbers between   1,000   and   4,000   (inclusive),   and a count   show a count of all eban numbers up and including           10,000   show a count of all eban numbers up and including         100,000   show a count of all eban numbers up and including      1,000,000   show a count of all eban numbers up and including    10,000,000   show all output here. See also   The MathWorld entry:   eban numbers.   The OEIS entry:   A6933, eban numbers.
#11l
11l
F iseban(n) I n == 0 R 0B V (b, r) = divmod(n, 1'000'000'000) (V m, r) = divmod(r, 1'000'000) (V t, r) = divmod(r, 1'000) m = I m C 30..66 {m % 10} E m t = I t C 30..66 {t % 10} E t r = I r C 30..66 {r % 10} E r R Set([b, m, t, r]) <= Set([0, 2, 4, 6])   print(‘eban numbers up to and including 1000:’) L(i) 0..100 I iseban(i) print(i, end' ‘ ’)   print("\n\neban numbers between 1000 and 4000 (inclusive):") L(i) 1000..4000 I iseban(i) print(i, end' ‘ ’)   print() L(maxn) (10'000, 100'000, 1'000'000, 10'000'000) V count = 0 L(i) 0..maxn I iseban(i) count++ print("\nNumber of eban numbers up to and including #8: #4".format(maxn, count))
http://rosettacode.org/wiki/Duffinian_numbers
Duffinian numbers
A Duffinian number is a composite number k that is relatively prime to its sigma sum σ. The sigma sum of k is the sum of the divisors of k. E.G. 161 is a Duffinian number. It is composite. (7 × 23) The sigma sum 192 (1 + 7 + 23 + 161) is relatively prime to 161. Duffinian numbers are very common. It is not uncommon for two consecutive integers to be Duffinian (a Duffinian twin) (8, 9), (35, 36), (49, 50), etc. Less common are Duffinian triplets; three consecutive Duffinian numbers. (63, 64, 65), (323, 324, 325), etc. Much, much less common are Duffinian quadruplets and quintuplets. The first Duffinian quintuplet is (202605639573839041, 202605639573839042, 202605639573839043, 202605639573839044, 202605639573839045). It is not possible to have six consecutive Duffinian numbers Task Find and show the first 50 Duffinian numbers. Find and show at least the first 15 Duffinian triplets. See also Numbers Aplenty - Duffinian numbers OEIS:A003624 - Duffinian numbers: composite numbers k relatively prime to sigma(k)
#ALGOL_68
ALGOL 68
BEGIN # find Duffinian numbers: non-primes relatively prime to their divisor count # INT max number := 500 000; # largest number we will consider # # iterative Greatest Common Divisor routine, returns the gcd of m and n # PROC gcd = ( INT m, n )INT: BEGIN INT a := ABS m, b := ABS n; WHILE b /= 0 DO INT new a = b; b := a MOD b; a := new a OD; a END # gcd # ; # construct a table of the divisor counts # [ 1 : max number ]INT ds; FOR i TO UPB ds DO ds[ i ] := 1 OD; FOR i FROM 2 TO UPB ds DO FOR j FROM i BY i TO UPB ds DO ds[ j ] +:= i OD OD; # set the divisor counts of non-Duffinian numbers to 0 # ds[ 1 ] := 0; # 1 is not Duffinian # FOR n FROM 2 TO UPB ds DO IF INT nds = ds[ n ]; IF nds = n + 1 THEN TRUE ELSE gcd( n, nds ) /= 1 FI THEN # n is prime or is not relatively prime to its divisor sum # ds[ n ] := 0 FI OD; # show the first 50 Duffinian numbers # print( ( "The first 50 Duffinian numbers:", newline ) ); INT dcount := 0; FOR n WHILE dcount < 50 DO IF ds[ n ] /= 0 THEN # found a Duffinian number # print( ( " ", whole( n, -3) ) ); IF ( dcount +:= 1 ) MOD 25 = 0 THEN print( ( newline ) ) FI FI OD; print( ( newline ) ); # show the duffinian triplets below UPB ds # print( ( "The Duffinian triplets up to ", whole( UPB ds, 0 ), ":", newline ) ); dcount := 0; FOR n FROM 3 TO UPB ds DO IF ds[ n - 2 ] /= 0 AND ds[ n - 1 ] /= 0 AND ds[ n ] /= 0 THEN # found a Duffinian triplet # print( ( " (", whole( n - 2, -7 ), " ", whole( n - 1, -7 ), " ", whole( n, -7 ), ")" ) ); IF ( dcount +:= 1 ) MOD 4 = 0 THEN print( ( newline ) ) FI FI OD END
http://rosettacode.org/wiki/Element-wise_operations
Element-wise operations
This task is similar to:   Matrix multiplication   Matrix transposition Task Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks. Implement:   addition   subtraction   multiplication   division   exponentiation Extend the task if necessary to include additional basic operations, which should not require their own specialised task.
#Clojure
Clojure
(defn initial-mtx [i1 i2 value] (vec (repeat i1 (vec (repeat i2 value)))))   (defn operation [f mtx1 mtx2] (if (vector? mtx1) (vec (map #(vec (map f %1 %2)) mtx1 mtx2))) (recur f (initial-mtx (count mtx2) (count (first mtx2)) mtx1) mtx2) ))
http://rosettacode.org/wiki/Dynamic_variable_names
Dynamic variable names
Task Create a variable with a user-defined name. The variable name should not be written in the program text, but should be taken from the user dynamically. See also   Eval in environment is a similar task.
#Arturo
Arturo
name: strip input "enter a variable name: " value: strip input "enter a variable value: "   let name value   print ["the value of variable" name "is:" var name]
http://rosettacode.org/wiki/Dynamic_variable_names
Dynamic variable names
Task Create a variable with a user-defined name. The variable name should not be written in the program text, but should be taken from the user dynamically. See also   Eval in environment is a similar task.
#AutoHotkey
AutoHotkey
InputBox, Dynamic, Variable Name %Dynamic% = hello ListVars MsgBox % %dynamic% ; says hello
http://rosettacode.org/wiki/Egyptian_division
Egyptian division
Egyptian division is a method of dividing integers using addition and doubling that is similar to the algorithm of Ethiopian multiplication Algorithm: Given two numbers where the dividend is to be divided by the divisor: Start the construction of a table of two columns: powers_of_2, and doublings; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column. Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order. Continue with successive i’th rows of 2^i and 2^i * divisor. Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend. We now assemble two separate sums that both start as zero, called here answer and accumulator Consider each row of the table, in the reverse order of its construction. If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer. When the first row has been considered as above, then the integer division of dividend by divisor is given by answer. (And the remainder is given by the absolute value of accumulator - dividend). Example: 580 / 34 Table creation: powers_of_2 doublings 1 34 2 68 4 136 8 272 16 544 Initialization of sums: powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 0 0 Considering table rows, bottom-up: When a row is considered it is shown crossed out if it is not accumulated, or bold if the row causes summations. powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 4 136 16 544 8 272 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 16 544 4 136 8 272 16 544 powers_of_2 doublings answer accumulator 1 34 17 578 2 68 4 136 8 272 16 544 Answer So 580 divided by 34 using the Egyptian method is 17 remainder (578 - 580) or 2. Task The task is to create a function that does Egyptian division. The function should closely follow the description above in using a list/array of powers of two, and another of doublings. Functions should be clear interpretations of the algorithm. Use the function to divide 580 by 34 and show the answer here, on this page. Related tasks   Egyptian fractions References   Egyptian Number System
#C
C
  #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <assert.h>   uint64_t egyptian_division(uint64_t dividend, uint64_t divisor, uint64_t *remainder) { // remainder is an out parameter, pass NULL if you do not need the remainder   static uint64_t powers[64]; static uint64_t doublings[64];   int i;   for(i = 0; i < 64; i++) { powers[i] = 1 << i; doublings[i] = divisor << i; if(doublings[i] > dividend) break; }   uint64_t answer = 0; uint64_t accumulator = 0;   for(i = i - 1; i >= 0; i--) { // If the current value of the accumulator added to the // doublings cell would be less than or equal to the // dividend then add it to the accumulator if(accumulator + doublings[i] <= dividend) { accumulator += doublings[i]; answer += powers[i]; } }   if(remainder) *remainder = dividend - accumulator; return answer; }   void go(uint64_t a, uint64_t b) { uint64_t x, y; x = egyptian_division(a, b, &y); printf("%llu / %llu = %llu remainder %llu\n", a, b, x, y); assert(a == b * x + y); }   int main(void) { go(580, 32); }  
http://rosettacode.org/wiki/Egyptian_fractions
Egyptian fractions
An   Egyptian fraction   is the sum of distinct unit fractions such as: 1 2 + 1 3 + 1 16 ( = 43 48 ) {\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})} Each fraction in the expression has a numerator equal to   1   (unity)   and a denominator that is a positive integer,   and all the denominators are distinct   (i.e., no repetitions). Fibonacci's   Greedy algorithm for Egyptian fractions   expands the fraction   x y {\displaystyle {\tfrac {x}{y}}}   to be represented by repeatedly performing the replacement x y = 1 ⌈ y / x ⌉ + ( − y ) mod x y ⌈ y / x ⌉ {\displaystyle {\frac {x}{y}}={\frac {1}{\lceil y/x\rceil }}+{\frac {(-y)\!\!\!\!\mod x}{y\lceil y/x\rceil }}} (simplifying the 2nd term in this replacement as necessary, and where   ⌈ x ⌉ {\displaystyle \lceil x\rceil }   is the   ceiling   function). For this task,   Proper and improper fractions   must be able to be expressed. Proper  fractions   are of the form   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive integers, such that   a < b {\displaystyle a<b} ,     and improper fractions are of the form   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive integers, such that   a ≥ b. (See the REXX programming example to view one method of expressing the whole number part of an improper fraction.) For improper fractions, the integer part of any improper fraction should be first isolated and shown preceding the Egyptian unit fractions, and be surrounded by square brackets [n]. Task requirements   show the Egyptian fractions for: 43 48 {\displaystyle {\tfrac {43}{48}}} and 5 121 {\displaystyle {\tfrac {5}{121}}} and 2014 59 {\displaystyle {\tfrac {2014}{59}}}   for all proper fractions,   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive one-or two-digit (decimal) integers, find and show an Egyptian fraction that has:   the largest number of terms,   the largest denominator.   for all one-, two-, and three-digit integers,   find and show (as above).     {extra credit} Also see   Wolfram MathWorld™ entry: Egyptian fraction
#Common_Lisp
Common Lisp
(defun egyption-fractions (x y &optional acc) (let* ((a (/ x y))) (cond ((> (numerator a) (denominator a)) (multiple-value-bind (q r) (floor x y) (if (zerop r) (cons q acc) (egyption-fractions r y (cons q acc))))) ((= (numerator a) 1) (reverse (cons a acc))) (t (let ((b (ceiling y x))) (egyption-fractions (mod (- y) x) (* y b) (cons (/ b) acc)))))))   (defun test (n fn) (car (sort (loop for i from 1 to n append (loop for j from 2 to n collect (cons (/ i j) (funcall fn (egyption-fractions i j))))) #'> :key #'cdr)))  
http://rosettacode.org/wiki/Eertree
Eertree
An eertree is a data structure designed for efficient processing of certain palindrome tasks, for instance counting the number of sub-palindromes in an input string. The data structure has commonalities to both tries and suffix trees.   See links below. Task Construct an eertree for the string "eertree", then output all sub-palindromes by traversing the tree. See also   Wikipedia entry:   trie.   Wikipedia entry:   suffix tree   Cornell University Library, Computer Science, Data Structures and Algorithms ───► EERTREE: An Efficient Data Structure for Processing Palindromes in Strings.
#Python
Python
#!/bin/python from __future__ import print_function   class Node(object): def __init__(self): self.edges = {} # edges (or forward links) self.link = None # suffix link (backward links) self.len = 0 # the length of the node   class Eertree(object): def __init__(self): self.nodes = [] # two initial root nodes self.rto = Node() #odd length root node, or node -1 self.rte = Node() #even length root node, or node 0   # Initialize empty tree self.rto.link = self.rte.link = self.rto; self.rto.len = -1 self.rte.len = 0 self.S = [0] # accumulated input string, T=S[1..i] self.maxSufT = self.rte # maximum suffix of tree T   def get_max_suffix_pal(self, startNode, a): # We traverse the suffix-palindromes of T in the order of decreasing length. # For each palindrome we read its length k and compare T[i-k] against a # until we get an equality or arrive at the -1 node. u = startNode i = len(self.S) k = u.len while id(u) != id(self.rto) and self.S[i - k - 1] != a: assert id(u) != id(u.link) #Prevent infinte loop u = u.link k = u.len   return u   def add(self, a):   # We need to find the maximum suffix-palindrome P of Ta # Start by finding maximum suffix-palindrome Q of T. # To do this, we traverse the suffix-palindromes of T # in the order of decreasing length, starting with maxSuf(T) Q = self.get_max_suffix_pal(self.maxSufT, a)   # We check Q to see whether it has an outgoing edge labeled by a. createANewNode = not a in Q.edges   if createANewNode: # We create the node P of length Q+2 P = Node() self.nodes.append(P) P.len = Q.len + 2 if P.len == 1: # if P = a, create the suffix link (P,0) P.link = self.rte else: # It remains to create the suffix link from P if |P|>1. Just # continue traversing suffix-palindromes of T starting with the suffix # link of Q. P.link = self.get_max_suffix_pal(Q.link, a).edges[a]   # create the edge (Q,P) Q.edges[a] = P   #P becomes the new maxSufT self.maxSufT = Q.edges[a]   #Store accumulated input string self.S.append(a)   return createANewNode   def get_sub_palindromes(self, nd, nodesToHere, charsToHere, result): #Each node represents a palindrome, which can be reconstructed #by the path from the root node to each non-root node.   #Traverse all edges, since they represent other palindromes for lnkName in nd.edges: nd2 = nd.edges[lnkName] #The lnkName is the character used for this edge self.get_sub_palindromes(nd2, nodesToHere+[nd2], charsToHere+[lnkName], result)   #Reconstruct based on charsToHere characters. if id(nd) != id(self.rto) and id(nd) != id(self.rte): #Don't print for root nodes tmp = "".join(charsToHere) if id(nodesToHere[0]) == id(self.rte): #Even string assembled = tmp[::-1] + tmp else: #Odd string assembled = tmp[::-1] + tmp[1:] result.append(assembled)   if __name__=="__main__": st = "eertree" print ("Processing string", st) eertree = Eertree() for ch in st: eertree.add(ch)   print ("Number of sub-palindromes:", len(eertree.nodes))   #Traverse tree to find sub-palindromes result = [] eertree.get_sub_palindromes(eertree.rto, [eertree.rto], [], result) #Odd length words eertree.get_sub_palindromes(eertree.rte, [eertree.rte], [], result) #Even length words print ("Sub-palindromes:", result)
http://rosettacode.org/wiki/Ethiopian_multiplication
Ethiopian multiplication
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last in the same column, until you write a value of 1. In the right-hand column repeatedly double the last number and write the result below. stop when you add a result in the same row as where the left hand column shows 1. Examine the table produced and discard any row where the value in the left column is even. Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together For example:   17 × 34 17 34 Halving the first column: 17 34 8 4 2 1 Doubling the second column: 17 34 8 68 4 136 2 272 1 544 Strike-out rows whose first cell is even: 17 34 8 68 4 136 2 272 1 544 Sum the remaining numbers in the right-hand column: 17 34 8 -- 4 --- 2 --- 1 544 ==== 578 So 17 multiplied by 34, by the Ethiopian method is 578. Task The task is to define three named functions/methods/procedures/subroutines: one to halve an integer, one to double an integer, and one to state if an integer is even. Use these functions to create a function that does Ethiopian multiplication. References Ethiopian multiplication explained (BBC Video clip) A Night Of Numbers - Go Forth And Multiply (Video) Russian Peasant Multiplication Programming Praxis: Russian Peasant Multiplication
#Racket
Racket
#lang racket   (define (halve i) (quotient i 2)) (define (double i) (* i 2)) ;; `even?' is built-in   (define (ethiopian-multiply x y) (cond [(zero? x) 0] [(even? x) (ethiopian-multiply (halve x) (double y))] [else (+ y (ethiopian-multiply (halve x) (double y)))]))   (ethiopian-multiply 17 34) ; -> 578
http://rosettacode.org/wiki/Elementary_cellular_automaton
Elementary cellular automaton
An elementary cellular automaton is a one-dimensional cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three bits. The rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101. Task Create a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice. The space state should wrap: this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally. This task is basically a generalization of one-dimensional cellular automata. See also Cellular automata (natureofcode.com)
#Factor
Factor
USING: assocs formatting grouping io kernel math math.bits math.combinatorics sequences sequences.extras ;   : make-rules ( n -- assoc ) { f t } 3 selections swap make-bits 8 f pad-tail zip ;   : next-state ( assoc seq -- assoc seq' ) dupd 3 circular-clump -1 rotate [ of ] with map ;   : first-state ( -- seq ) 15 f <repetition> dup { t } glue ;   : show-state ( seq -- ) [ "#" "." ? write ] each nl ;   : show-automaton ( rule -- ) dup "Rule %d:\n" printf make-rules first-state 16 [ dup show-state next-state ] times 2drop ;   90 show-automaton
http://rosettacode.org/wiki/Elementary_cellular_automaton
Elementary cellular automaton
An elementary cellular automaton is a one-dimensional cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three bits. The rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101. Task Create a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice. The space state should wrap: this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally. This task is basically a generalization of one-dimensional cellular automata. See also Cellular automata (natureofcode.com)
#FreeBASIC
FreeBASIC
  #define NCELLS 400 #define border 16 dim as ubyte rule = 110   sub evolve( row as uinteger, rule as ubyte, pattern() as ubyte ) dim as ubyte newp(NCELLS) dim as uinteger i dim as ubyte lookup for i = 0 to NCELLS-1 pset (i + border, row + border ), pattern(i)*15 lookup = 4*pattern((i-1) mod NCELLS) + 2*pattern(i) + pattern( (i+1) mod NCELLS ) newp(i)=0 if ( 2^lookup and rule )<>0 then newp(i) = 1 next i for i = 0 to NCELLS-1 pattern(i) = newp(i) next i end sub   sub perform_simulation( rule as ubyte, pattern() as ubyte ) dim as integer i for i = 1 to NCELLS evolve(i, rule, pattern()) next i end sub   sub reseed( pattern() as ubyte ) dim as integer i for i = 0 to NCELLS-1 pattern(i) = int(rnd+0.5) next i end sub   sub display_text( rule as ubyte ) locate 4,58 : print using "Rule ###";rule locate 6,53 : print " R: reshuffle seed " locate 8,53 : print " <,>: change rule " locate 10,53 : print " Q: quit " end sub   screen 12 randomize timer dim as boolean pattern(0 to NCELLS-1) dim as string key="R"   do if key = "R" then cls reseed(pattern()) perform_simulation(rule,pattern()) display_text(rule) end if if key="<" then cls rule = (rule-1) mod 256 reseed(pattern()) perform_simulation(rule,pattern()) display_text(rule) end if if key=">" then cls rule = (rule+1) mod 256 reseed(pattern()) perform_simulation(rule,pattern()) display_text(rule) end if key = ucase(inkey) loop until ucase(key) = "Q"
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#TI-89_BASIC
TI-89 BASIC
factorial(x) Func Return Π(y,y,1,x) EndFunc
http://rosettacode.org/wiki/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd. Use modular congruences: i ≡ 0 (mod 2) iff i is even. i ≡ 1 (mod 2) iff i is odd.
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Sub Main() Dim str As String Dim num As Integer While True Console.Write("Enter an integer or 0 to finish: ") str = Console.ReadLine() If Integer.TryParse(str, num) Then If num = 0 Then Exit While End If If num Mod 2 = 0 Then Console.WriteLine("Even") Else Console.WriteLine("Odd") End If Else Console.WriteLine("Bad input.") End If End While End Sub   End Module
http://rosettacode.org/wiki/Echo_server
Echo server
Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary to support connections from localhost (127.0.0.1 or perhaps ::1). Logging of connection information to standard output is recommended. The implementation must be able to handle simultaneous connections from multiple clients. A multi-threaded or multi-process solution may be used. Each connection must be able to echo more than a single line. The implementation must not stop responding to other clients if one client sends a partial line or stops reading responses.
#Go
Go
package main   import ( "fmt" "net" "bufio" )   func echo(s net.Conn, i int) { defer s.Close();   fmt.Printf("%d: %v <-> %v\n", i, s.LocalAddr(), s.RemoteAddr()) b := bufio.NewReader(s) for { line, e := b.ReadBytes('\n') if e != nil { break } s.Write(line) } fmt.Printf("%d: closed\n", i) }   func main() { l, e := net.Listen("tcp", ":12321") for i := 0; e == nil; i++ { var s net.Conn s, e = l.Accept() go echo(s, i) } }
http://rosettacode.org/wiki/Empty_string
Empty string
Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. 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
#ZX_Spectrum_Basic
ZX Spectrum Basic
const std = @import("std");   pub fn main() !void { // default is [:0]const u8, which is a 0-terminated string with len field const str = ""; if (str.len == 0) { std.debug.print("string empty\n", .{}); } if (str.len != 0) { std.debug.print("string empty\n", .{}); } }
http://rosettacode.org/wiki/Empty_string
Empty string
Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. 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
#Zig
Zig
const std = @import("std");   pub fn main() !void { // default is [:0]const u8, which is a 0-terminated string with len field const str = ""; if (str.len == 0) { std.debug.print("string empty\n", .{}); } if (str.len != 0) { std.debug.print("string empty\n", .{}); } }
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Standard_ML
Standard ML
;
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Stata
Stata
program define nop version 15 end
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Suneido
Suneido
function () { }
http://rosettacode.org/wiki/Earliest_difference_between_prime_gaps
Earliest difference between prime gaps
When calculating prime numbers > 2, the difference between adjacent primes is always an even number. This difference, also referred to as the gap, varies in an random pattern; at least, no pattern has ever been discovered, and it is strongly conjectured that no pattern exists. However, it is also conjectured that between some two adjacent primes will be a gap corresponding to every positive even integer. gap minimal starting prime ending prime 2 3 5 4 7 11 6 23 29 8 89 97 10 139 149 12 199 211 14 113 127 16 1831 1847 18 523 541 20 887 907 22 1129 1151 24 1669 1693 26 2477 2503 28 2971 2999 30 4297 4327 This task involves locating the minimal primes corresponding to those gaps. Though every gap value exists, they don't seem to come in any particular order. For example, this table shows the gaps and minimum starting value primes for 2 through 30: For the purposes of this task, considering only primes greater than 2, consider prime gaps that differ by exactly two to be adjacent. Task For each order of magnitude m from 10¹ through 10⁶: Find the first two sets of adjacent minimum prime gaps where the absolute value of the difference between the prime gap start values is greater than m. E.G. For an m of 10¹; The start value of gap 2 is 3, the start value of gap 4 is 7, the difference is 7 - 3 or 4. 4 < 10¹ so keep going. The start value of gap 4 is 7, the start value of gap 6 is 23, the difference is 23 - 7, or 16. 16 > 10¹ so this the earliest adjacent gap difference > 10¹. Stretch goal Do the same for 10⁷ and 10⁸ (and higher?) orders of magnitude Note: the earliest value found for each order of magnitude may not be unique, in fact, is not unique; also, with the gaps in ascending order, the minimal starting values are not strictly ascending.
#Rust
Rust
// [dependencies] // primal = "0.3"   fn main() { use std::collections::HashMap;   let mut primes = primal::Primes::all(); let mut last_prime = primes.next().unwrap(); let mut gap_starts = HashMap::new();   let mut find_gap_start = move |gap: usize| -> usize { if let Some(start) = gap_starts.get(&gap) { return *start; } loop { let prev = last_prime; last_prime = primes.next().unwrap(); let diff = last_prime - prev; if !gap_starts.contains_key(&diff) { gap_starts.insert(diff, prev); } if gap == diff { return prev; } } };   let limit = 100000000000;   let mut pm = 10; let mut gap1 = 2; loop { let start1 = find_gap_start(gap1); let gap2 = gap1 + 2; let start2 = find_gap_start(gap2); let diff = if start2 > start1 { start2 - start1 } else { start1 - start2 }; if diff > pm { println!( "Earliest difference > {} between adjacent prime gap starting primes:\n\ Gap {} starts at {}, gap {} starts at {}, difference is {}.\n", pm, gap1, start1, gap2, start2, diff ); if pm == limit { break; } pm *= 10; } else { gap1 = gap2; } } }
http://rosettacode.org/wiki/Earliest_difference_between_prime_gaps
Earliest difference between prime gaps
When calculating prime numbers > 2, the difference between adjacent primes is always an even number. This difference, also referred to as the gap, varies in an random pattern; at least, no pattern has ever been discovered, and it is strongly conjectured that no pattern exists. However, it is also conjectured that between some two adjacent primes will be a gap corresponding to every positive even integer. gap minimal starting prime ending prime 2 3 5 4 7 11 6 23 29 8 89 97 10 139 149 12 199 211 14 113 127 16 1831 1847 18 523 541 20 887 907 22 1129 1151 24 1669 1693 26 2477 2503 28 2971 2999 30 4297 4327 This task involves locating the minimal primes corresponding to those gaps. Though every gap value exists, they don't seem to come in any particular order. For example, this table shows the gaps and minimum starting value primes for 2 through 30: For the purposes of this task, considering only primes greater than 2, consider prime gaps that differ by exactly two to be adjacent. Task For each order of magnitude m from 10¹ through 10⁶: Find the first two sets of adjacent minimum prime gaps where the absolute value of the difference between the prime gap start values is greater than m. E.G. For an m of 10¹; The start value of gap 2 is 3, the start value of gap 4 is 7, the difference is 7 - 3 or 4. 4 < 10¹ so keep going. The start value of gap 4 is 7, the start value of gap 6 is 23, the difference is 23 - 7, or 16. 16 > 10¹ so this the earliest adjacent gap difference > 10¹. Stretch goal Do the same for 10⁷ and 10⁸ (and higher?) orders of magnitude Note: the earliest value found for each order of magnitude may not be unique, in fact, is not unique; also, with the gaps in ascending order, the minimal starting values are not strictly ascending.
#Sidef
Sidef
func prime_gap_records(upto) {   var gaps = [] var p = 3   each_prime(p.next_prime, upto, {|q| gaps[q-p] := p p = q })   gaps.grep { defined(_) } }   var gaps = prime_gap_records(1e8)   for m in (1 .. gaps.max.len) { gaps.each_cons(2, {|p,q| if (abs(q-p) > 10**m) { say "10^#{m} -> (#{p}, #{q}) with gaps (#{ p.next_prime-p}, #{q.next_prime-q}) and difference #{abs(q-p)}" break } }) }
http://rosettacode.org/wiki/Earliest_difference_between_prime_gaps
Earliest difference between prime gaps
When calculating prime numbers > 2, the difference between adjacent primes is always an even number. This difference, also referred to as the gap, varies in an random pattern; at least, no pattern has ever been discovered, and it is strongly conjectured that no pattern exists. However, it is also conjectured that between some two adjacent primes will be a gap corresponding to every positive even integer. gap minimal starting prime ending prime 2 3 5 4 7 11 6 23 29 8 89 97 10 139 149 12 199 211 14 113 127 16 1831 1847 18 523 541 20 887 907 22 1129 1151 24 1669 1693 26 2477 2503 28 2971 2999 30 4297 4327 This task involves locating the minimal primes corresponding to those gaps. Though every gap value exists, they don't seem to come in any particular order. For example, this table shows the gaps and minimum starting value primes for 2 through 30: For the purposes of this task, considering only primes greater than 2, consider prime gaps that differ by exactly two to be adjacent. Task For each order of magnitude m from 10¹ through 10⁶: Find the first two sets of adjacent minimum prime gaps where the absolute value of the difference between the prime gap start values is greater than m. E.G. For an m of 10¹; The start value of gap 2 is 3, the start value of gap 4 is 7, the difference is 7 - 3 or 4. 4 < 10¹ so keep going. The start value of gap 4 is 7, the start value of gap 6 is 23, the difference is 23 - 7, or 16. 16 > 10¹ so this the earliest adjacent gap difference > 10¹. Stretch goal Do the same for 10⁷ and 10⁸ (and higher?) orders of magnitude Note: the earliest value found for each order of magnitude may not be unique, in fact, is not unique; also, with the gaps in ascending order, the minimal starting values are not strictly ascending.
#Wren
Wren
import "./math" for Int import "/fmt" for Fmt   var limit = 1e9 var gapStarts = {} var primes = Int.segmentedSieve(limit * 5, 8 * 1024 * 1024) // 8 MB cache for (i in 1...primes.count) { var gap = primes[i] - primes[i-1] if (!gapStarts[gap]) gapStarts[gap] = primes[i-1] } var pm = 10 var gap1 = 2 while (true) { while (!gapStarts[gap1]) gap1 = gap1 + 2 var start1 = gapStarts[gap1] var gap2 = gap1 + 2 if (!gapStarts[gap2]) { gap1 = gap2 + 2 continue } var start2 = gapStarts[gap2] var diff = (start2 - start1).abs if (diff > pm) { Fmt.print("Earliest difference > $,d between adjacent prime gap starting primes:", pm) Fmt.print("Gap $d starts at $,d, gap $d starts at $,d, difference is $,d.\n", gap1, start1, gap2, start2, diff) if (pm == limit) break pm = pm * 10 } else { gap1 = gap2 } }
http://rosettacode.org/wiki/Eban_numbers
Eban numbers
Definition An   eban   number is a number that has no letter   e   in it when the number is spelled in English. Or more literally,   spelled numbers that contain the letter   e   are banned. The American version of spelling numbers will be used here   (as opposed to the British). 2,000,000,000   is two billion,   not   two milliard. Only numbers less than   one sextillion   (1021)   will be considered in/for this task. This will allow optimizations to be used. Task   show all eban numbers   ≤   1,000   (in a horizontal format),   and a count   show all eban numbers between   1,000   and   4,000   (inclusive),   and a count   show a count of all eban numbers up and including           10,000   show a count of all eban numbers up and including         100,000   show a count of all eban numbers up and including      1,000,000   show a count of all eban numbers up and including    10,000,000   show all output here. See also   The MathWorld entry:   eban numbers.   The OEIS entry:   A6933, eban numbers.
#AppleScript
AppleScript
(* Quickly generate all the (positive) eban numbers up to and including the specified end number, then lose those before the start number. 0 is taken as "zero" rather than as "nought" or "nil".   WARNING: The getEbans() handler returns a potentially very long list of numbers. Don't let such a list get assigned to a persistent variable or be the end result displayed in an editor! *)   on getEbans(startNumber, endNumber) script o property output : {} property listCollector : missing value property temp : missing value end script   if (startNumber > endNumber) then set {startNumber, endNumber} to {endNumber, startNumber} -- The range is limited to between 0 and 10^15 to keep within AppleScript's current number precision. -- Even so, some of the numbers may not /look/ right when displayed in a editor. set limit to 10 ^ 15 - 1 if (endNumber > limit) then set endNumber to limit if (startNumber > limit) then set startNumber to limit   -- Initialise the output list with 0 and the sub-1000 ebans, stopping if the end number's reached. -- The 0's needed for rest of the process, but is removed at the end. repeat with tens in {0, 30, 40, 50, 60} repeat with units in {0, 2, 4, 6} set thisEban to tens + units if (thisEban ≤ endNumber) then set end of o's output to thisEban end repeat end repeat   -- Repeatedly sweep the output list, adding new ebans formed from the addition of those found previously -- to a suitable power of 1000 times each one. Stop when the end number's reached or exceeded. -- The output list may become very long and appending items to it individually take forever, so results are -- collected in short, 1000-item lists, which are concatenated to the output at the end of each sweep. set sweepLength to (count o's output) set multiplier to 1000 repeat while (thisEban < endNumber) -- Per sweep. set o's temp to {} set o's listCollector to {o's temp} repeat with i from 2 to sweepLength -- Per eban found already. (Not the 0.) set baseAmount to (item i of o's output) * multiplier repeat with j from 1 to sweepLength by 1000 -- Per 1000-item list. set z to j + 999 if (z > sweepLength) then set z to sweepLength repeat with k from j to z -- Per new eban. set thisEban to baseAmount + (item k of o's output) if (thisEban ≤ endNumber) then set end of o's temp to thisEban if (thisEban ≥ endNumber) then exit repeat end repeat if (thisEban ≥ endNumber) then exit repeat set o's temp to {} set end of o's listCollector to o's temp end repeat if (thisEban ≥ endNumber) then exit repeat end repeat   -- Concatentate this sweep's new lists together set listCount to (count o's listCollector) repeat until (listCount is 1) set o's temp to {} repeat with i from 2 to listCount by 2 set end of o's temp to (item (i - 1) of o's listCollector) & (item i of o's listCollector) end repeat if (listCount mod 2 is 1) then set item -1 of o's temp to (end of o's temp) & (end of o's listCollector) set o's listCollector to o's temp set o's temp to {} set listCount to (count o's listCollector) end repeat -- Concatenate the result to the output list and prepare to go round again. set o's output to o's output & (beginning of o's listCollector) set sweepLength to sweepLength * sweepLength set multiplier to multiplier * multiplier end repeat   -- Lose the initial 0 and any ebans before the specified start number. set resultCount to (count o's output) if (resultCount is 1) then set o's output to {} else repeat with i from 2 to resultCount if (item i of o's output ≥ startNumber) then exit repeat end repeat set o's output to items i thru resultCount of o's output end if if (endNumber = limit) then set end of o's output to "(Limit of AppleScript's number precision.)"   return o's output end getEbans   -- Task code: on runTask() set output to {} set astid to AppleScript's text item delimiters set AppleScript's text item delimiters to ", "   set ebans to getEbans(0, 1000) set end of output to ((count ebans) as text) & " eban numbers between 0 and 1,000:" & (linefeed & " " & ebans) set ebans to getEbans(1000, 4000) set end of output to ((count ebans) as text) & " between 1,000 and 4,000:" & (linefeed & " " & ebans) set end of output to ((count getEbans(0, 10000)) as text) & " up to and including 10,000" set end of output to ((count getEbans(0, 100000)) as text) & " up to and including 100,000" set end of output to ((count getEbans(0, 1000000)) as text) & " up to and including 1,000,000" set end of output to ((count getEbans(0, 10000000)) as text) & " up to and including 10,000,000" set ebans to getEbans(6.606606602E+10, 1.0E+12) set end of output to ((count ebans) as text) & " between 66,066,066,020 and 1,000,000,000,000:" & (linefeed & " " & ebans)   set AppleScript's text item delimiters to linefeed set output to output as text set AppleScript's text item delimiters to astid   return output end runTask   runTask()
http://rosettacode.org/wiki/Duffinian_numbers
Duffinian numbers
A Duffinian number is a composite number k that is relatively prime to its sigma sum σ. The sigma sum of k is the sum of the divisors of k. E.G. 161 is a Duffinian number. It is composite. (7 × 23) The sigma sum 192 (1 + 7 + 23 + 161) is relatively prime to 161. Duffinian numbers are very common. It is not uncommon for two consecutive integers to be Duffinian (a Duffinian twin) (8, 9), (35, 36), (49, 50), etc. Less common are Duffinian triplets; three consecutive Duffinian numbers. (63, 64, 65), (323, 324, 325), etc. Much, much less common are Duffinian quadruplets and quintuplets. The first Duffinian quintuplet is (202605639573839041, 202605639573839042, 202605639573839043, 202605639573839044, 202605639573839045). It is not possible to have six consecutive Duffinian numbers Task Find and show the first 50 Duffinian numbers. Find and show at least the first 15 Duffinian triplets. See also Numbers Aplenty - Duffinian numbers OEIS:A003624 - Duffinian numbers: composite numbers k relatively prime to sigma(k)
#AppleScript
AppleScript
on aliquotSum(n) if (n < 2) then return 0 set sum to 1 set sqrt to n ^ 0.5 set limit to sqrt div 1 if (limit = sqrt) then set sum to sum + limit set limit to limit - 1 end if repeat with i from 2 to limit if (n mod i is 0) then set sum to sum + i + n div i end repeat   return sum end aliquotSum   on hcf(a, b) repeat until (b = 0) set x to a set a to b set b to x mod b end repeat   if (a < 0) then return -a return a end hcf   on isDuffinian(n) set aliquot to aliquotSum(n) -- = sigma sum - n. = 1 if n's prime. return ((aliquot > 1) and (hcf(n, aliquot + n) = 1)) end isDuffinian   -- Task code: on matrixToText(matrix, w) script o property matrix : missing value property row : missing value end script   set o's matrix to matrix set padding to " " repeat with r from 1 to (count o's matrix) set o's row to o's matrix's item r repeat with i from 1 to (count o's row) set o's row's item i to text -w thru end of (padding & o's row's item i) end repeat set o's matrix's item r to join(o's row, "") end repeat   return join(o's matrix, linefeed) end matrixToText   on join(lst, delim) set astid to AppleScript's text item delimiters set AppleScript's text item delimiters to delim set txt to lst as text set AppleScript's text item delimiters to astid return txt end join   on task(duffTarget, tupTarget, tupSize) if ((duffTarget < 1) or (tupTarget < 1) or (tupSize < 2)) then error "Duff parameter(s)." script o property duffinians : {} property tuplets : {} end script   -- Populate o's duffinians and tuplets lists. set n to 1 set tuplet to {} repeat while (((count o's tuplets) < tupTarget) or ((count o's duffinians) < duffTarget)) if (isDuffinian(n)) then if ((count o's duffinians) < duffTarget) then set end of o's duffinians to n if (tuplet ends with n - 1) then set end of tuplet to n else if ((count tuplet) = tupSize) then set end of o's tuplets to tuplet set tuplet to {n} end if end if set n to n + 1 end repeat   -- Format for output. set duffinians to {} repeat with i from 1 to duffTarget by 20 set j to i + 19 if (j > duffTarget) then set j to duffTarget set end of duffinians to items i thru j of o's duffinians end repeat set part1 to "First " & duffTarget & " Duffinian numbers:" & linefeed & ¬ matrixToText(duffinians, (count (end of o's duffinians as text)) + 2) set tupletTypes to {missing value, "twins", "triplets:", "quadruplets:", "quintuplets:"} set part2 to "First " & tupTarget & " Duffinian " & item tupSize of tupletTypes & linefeed & ¬ matrixToText(o's tuplets, (count (end of end of o's tuplets as text)) + 2)   return part1 & (linefeed & linefeed & part2) end task   return task(50, 20, 3) -- First 50 Duffinians, first 20 3-item tuplets.
http://rosettacode.org/wiki/Element-wise_operations
Element-wise operations
This task is similar to:   Matrix multiplication   Matrix transposition Task Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks. Implement:   addition   subtraction   multiplication   division   exponentiation Extend the task if necessary to include additional basic operations, which should not require their own specialised task.
#Common_Lisp
Common Lisp
(defun element-wise-matrix (fn A B) (let* ((len (array-total-size A)) (m (car (array-dimensions A))) (n (cadr (array-dimensions A))) (C (make-array `(,m ,n) :initial-element 0.0d0)))   (loop for i from 0 to (1- len) do (setf (row-major-aref C i) (funcall fn (row-major-aref A i) (row-major-aref B i)))) C))   ;; A.+B, A.-B, A.*B, A./B, A.^B. (defun m+ (A B) (element-wise-matrix #'+ A B)) (defun m- (A B) (element-wise-matrix #'- A B)) (defun m* (A B) (element-wise-matrix #'* A B)) (defun m/ (A B) (element-wise-matrix #'/ A B)) (defun m^ (A B) (element-wise-matrix #'expt A B))
http://rosettacode.org/wiki/Dynamic_variable_names
Dynamic variable names
Task Create a variable with a user-defined name. The variable name should not be written in the program text, but should be taken from the user dynamically. See also   Eval in environment is a similar task.
#AWK
AWK
  # syntax: GAWK -f DYNAMIC_VARIABLE_NAMES.AWK # Variables created in GAWK's internal SYMTAB (symbol table) can only be accessed via SYMTAB[name] BEGIN { PROCINFO["sorted_in"] = "@ind_str_asc" show_symbol_table() while (1) { printf("enter variable name? ") getline v_name if (v_name in SYMTAB) { printf("name already exists with a value of '%s'\n",SYMTAB[v_name]) continue } if (v_name ~ /^$/) { printf("name is null\n") continue } if (v_name !~ /^[A-Za-z][A-Za-z0-9_]*$/) { printf("name illegally constructed\n") continue } break } printf("enter value? ") getline v_value SYMTAB[v_name] = v_value printf("variable '%s' has been created and assigned the value '%s'\n\n",v_name,v_value) show_symbol_table() exit(0) } function show_symbol_table( count,i) { for (i in SYMTAB) { printf("%s ",i) if (isarray(SYMTAB[i])) { count++ } } printf("\nsymbol table contains %d names of which %d are arrays\n\n",length(SYMTAB),count) }  
http://rosettacode.org/wiki/Egyptian_division
Egyptian division
Egyptian division is a method of dividing integers using addition and doubling that is similar to the algorithm of Ethiopian multiplication Algorithm: Given two numbers where the dividend is to be divided by the divisor: Start the construction of a table of two columns: powers_of_2, and doublings; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column. Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order. Continue with successive i’th rows of 2^i and 2^i * divisor. Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend. We now assemble two separate sums that both start as zero, called here answer and accumulator Consider each row of the table, in the reverse order of its construction. If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer. When the first row has been considered as above, then the integer division of dividend by divisor is given by answer. (And the remainder is given by the absolute value of accumulator - dividend). Example: 580 / 34 Table creation: powers_of_2 doublings 1 34 2 68 4 136 8 272 16 544 Initialization of sums: powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 0 0 Considering table rows, bottom-up: When a row is considered it is shown crossed out if it is not accumulated, or bold if the row causes summations. powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 4 136 16 544 8 272 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 16 544 4 136 8 272 16 544 powers_of_2 doublings answer accumulator 1 34 17 578 2 68 4 136 8 272 16 544 Answer So 580 divided by 34 using the Egyptian method is 17 remainder (578 - 580) or 2. Task The task is to create a function that does Egyptian division. The function should closely follow the description above in using a list/array of powers of two, and another of doublings. Functions should be clear interpretations of the algorithm. Use the function to divide 580 by 34 and show the answer here, on this page. Related tasks   Egyptian fractions References   Egyptian Number System
#C.23
C#
  using System; using System.Collections;   namespace Egyptian_division { class Program { public static void Main(string[] args) { Console.Clear(); Console.WriteLine(); Console.WriteLine(" Egyptian division "); Console.WriteLine(); Console.Write(" Enter value of dividend : "); int dividend = int.Parse(Console.ReadLine());   Console.Write(" Enter value of divisor : "); int divisor = int.Parse(Console.ReadLine());   Divide(dividend, divisor);   Console.WriteLine(); Console.Write("Press any key to continue . . . "); Console.ReadKey(true);       }   static void Divide(int dividend, int divisor) { // // Local variable declaration and initialization // int result = 0; int reminder = 0;   int powers_of_two = 0; int doublings = 0;   int answer = 0; int accumulator = 0;   int two = 2; int pow = 0; int row = 0;   // // Tables declaration // ArrayList table_powers_of_two = new ArrayList(); ArrayList table_doublings = new ArrayList();   // // Fill and Show table values // Console.WriteLine(" "); Console.WriteLine(" powers_of_2 doublings "); Console.WriteLine(" ");   // Set initial values powers_of_two = 1; doublings = divisor; while( doublings <= dividend ) { // Set table value table_powers_of_two.Add( powers_of_two ); table_doublings.Add( doublings );   // Show new table row Console.WriteLine("{0,8}{1,16}",powers_of_two, doublings);     pow++;   powers_of_two = (int)Math.Pow( two, pow ); doublings = powers_of_two * divisor; } Console.WriteLine(" ");   // // Calculate division and Show table values // row = pow - 1; Console.WriteLine(" "); Console.WriteLine(" powers_of_2 doublings answer accumulator"); Console.WriteLine(" "); Console.SetCursorPosition(Console.CursorLeft, Console.CursorTop + row);   pow--; while( pow >= 0 && accumulator < dividend ) { // Get values from tables doublings = int.Parse(table_doublings[pow].ToString()); powers_of_two = int.Parse(table_powers_of_two[pow].ToString());   if(accumulator + int.Parse(table_doublings[pow].ToString()) <= dividend ) { // Set new values accumulator += doublings; answer += powers_of_two;   // Show accumulated row values in different collor Console.ForegroundColor = ConsoleColor.Green; Console.Write("{0,8}{1,16}",powers_of_two, doublings); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("{0,10}{1,12}", answer, accumulator); Console.SetCursorPosition(Console.CursorLeft, Console.CursorTop - 2); } else { // Show not accumulated row walues Console.ForegroundColor = ConsoleColor.DarkGray; Console.Write("{0,8}{1,16}",powers_of_two, doublings); Console.ForegroundColor = ConsoleColor.Gray; Console.WriteLine("{0,10}{1,12}", answer, accumulator); Console.SetCursorPosition(Console.CursorLeft, Console.CursorTop - 2); }     pow--; }   Console.WriteLine(); Console.SetCursorPosition(Console.CursorLeft, Console.CursorTop + row + 2); Console.ResetColor();   // Set result and reminder result = answer; if( accumulator < dividend ) { reminder = dividend - accumulator;   Console.WriteLine(" So " + dividend + " divided by " + divisor + " using the Egyptian method is \n " + result + " remainder (" + dividend + " - " + accumulator + ") or " + reminder); Console.WriteLine(); } else { reminder = 0;   Console.WriteLine(" So " + dividend + " divided by " + divisor + " using the Egyptian method is \n " + result + " remainder " + reminder); Console.WriteLine(); } } } }  
http://rosettacode.org/wiki/Egyptian_fractions
Egyptian fractions
An   Egyptian fraction   is the sum of distinct unit fractions such as: 1 2 + 1 3 + 1 16 ( = 43 48 ) {\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})} Each fraction in the expression has a numerator equal to   1   (unity)   and a denominator that is a positive integer,   and all the denominators are distinct   (i.e., no repetitions). Fibonacci's   Greedy algorithm for Egyptian fractions   expands the fraction   x y {\displaystyle {\tfrac {x}{y}}}   to be represented by repeatedly performing the replacement x y = 1 ⌈ y / x ⌉ + ( − y ) mod x y ⌈ y / x ⌉ {\displaystyle {\frac {x}{y}}={\frac {1}{\lceil y/x\rceil }}+{\frac {(-y)\!\!\!\!\mod x}{y\lceil y/x\rceil }}} (simplifying the 2nd term in this replacement as necessary, and where   ⌈ x ⌉ {\displaystyle \lceil x\rceil }   is the   ceiling   function). For this task,   Proper and improper fractions   must be able to be expressed. Proper  fractions   are of the form   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive integers, such that   a < b {\displaystyle a<b} ,     and improper fractions are of the form   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive integers, such that   a ≥ b. (See the REXX programming example to view one method of expressing the whole number part of an improper fraction.) For improper fractions, the integer part of any improper fraction should be first isolated and shown preceding the Egyptian unit fractions, and be surrounded by square brackets [n]. Task requirements   show the Egyptian fractions for: 43 48 {\displaystyle {\tfrac {43}{48}}} and 5 121 {\displaystyle {\tfrac {5}{121}}} and 2014 59 {\displaystyle {\tfrac {2014}{59}}}   for all proper fractions,   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive one-or two-digit (decimal) integers, find and show an Egyptian fraction that has:   the largest number of terms,   the largest denominator.   for all one-, two-, and three-digit integers,   find and show (as above).     {extra credit} Also see   Wolfram MathWorld™ entry: Egyptian fraction
#D
D
import std.stdio, std.bigint, std.algorithm, std.range, std.conv, std.typecons, arithmetic_rational: Rat = Rational;   Rat[] egyptian(Rat r) pure nothrow { typeof(return) result;   if (r >= 1) { if (r.denominator == 1) return [r, Rat(0, 1)]; result = [Rat(r.numerator / r.denominator, 1)]; r -= result[0]; }   static enum mod = (in BigInt m, in BigInt n) pure nothrow => ((m % n) + n) % n;   while (r.numerator != 1) { immutable q = (r.denominator + r.numerator - 1) / r.numerator; result ~= Rat(1, q); r = Rat(mod(-r.denominator, r.numerator), r.denominator * q); }   result ~= r; return result; }   void main() { foreach (immutable r; [Rat(43, 48), Rat(5, 121), Rat(2014, 59)]) writefln("%s => %(%s %)", r, r.egyptian);   Tuple!(size_t, Rat) lenMax; Tuple!(BigInt, Rat) denomMax;   foreach (immutable r; iota(1, 100).cartesianProduct(iota(1, 100)) .map!(nd => nd[].Rat).array.sort().uniq) { immutable e = r.egyptian; immutable eLen = e.length; immutable eDenom = e.back.denominator; if (eLen > lenMax[0]) lenMax = tuple(eLen, r); if (eDenom > denomMax[0]) denomMax = tuple(eDenom, r); } writefln("Term max is %s with %d terms", lenMax[1], lenMax[0]); immutable dStr = denomMax[0].text; writefln("Denominator max is %s with %d digits %s...%s", denomMax[1], dStr.length, dStr[0 .. 5], dStr[$ - 5 .. $]); }
http://rosettacode.org/wiki/Eertree
Eertree
An eertree is a data structure designed for efficient processing of certain palindrome tasks, for instance counting the number of sub-palindromes in an input string. The data structure has commonalities to both tries and suffix trees.   See links below. Task Construct an eertree for the string "eertree", then output all sub-palindromes by traversing the tree. See also   Wikipedia entry:   trie.   Wikipedia entry:   suffix tree   Cornell University Library, Computer Science, Data Structures and Algorithms ───► EERTREE: An Efficient Data Structure for Processing Palindromes in Strings.
#Racket
Racket
#lang racket (struct node (edges ; edges (or forward links) link ; suffix link (backward links) len) ; the length of the node #:mutable)   (define (new-node link len) (node (make-hash) link len))   (struct eertree (nodes rto ; odd length root node, or node -1 rte ; even length root node, or node 0 S ; accumulated input string, T=S[1..i] max-suf-t) ; maximum suffix of tree T #:mutable)   (define (new-eertree) (let* ((rto (new-node #f -1)) (rte (new-node rto 0))) (eertree null rto rte (list 0) rte)))   (define (eertree-get-max-suffix-pal et start-node a) #| We traverse the suffix-palindromes of T in the order of decreasing length. For each palindrome we read its length k and compare T[i-k] against a until we get an equality or arrive at the -1 node. |# (match et [(eertree nodes rto rte (and S (app length i)) max-suf-t) (let loop ((u start-node)) (let ((k (node-len u))) (if (or (eq? u rto) (= (list-ref S (- i k 1)) a)) u (let ((u→ (node-link u))) (when (eq? u u→) (error 'eertree-get-max-suffix-pal "infinite loop")) (loop u→)))))]))   (define (eertree-add! et a) #| We need to find the maximum suffix-palindrome P of Ta Start by finding maximum suffix-palindrome Q of T. To do this, we traverse the suffix-palindromes of T in the order of decreasing length, starting with maxSuf(T) |# (match (eertree-get-max-suffix-pal et (eertree-max-suf-t et) a) [(node Q.edges Q.→ Q.len)  ;; We check Q to see whether it has an outgoing edge labeled by a. (define new-node? (not (hash-has-key? Q.edges a))) (when new-node? (define P (new-node #f (+ Q.len 2))) ; We create the node P of length Q+2 (set-eertree-nodes! et (append (eertree-nodes et) (list P))) (define P→ (if (= (node-len P) 1) (eertree-rte et) ; if P = a, create the suffix link (P,0)  ;; It remains to c reate the suffix link from P if |P|>1.  ;; Just continue traversing suffix-palindromes of T starting with the suffix link of Q. (hash-ref (node-edges (eertree-get-max-suffix-pal et Q.→ a)) a))) (set-node-link! P P→) (hash-set! Q.edges a P)) ; create the edge (Q,P)   (set-eertree-max-suf-t! et (hash-ref Q.edges a)) ; P becomes the new maxSufT (set-eertree-S! et (append (eertree-S et) (list a))) ; Store accumulated input string new-node?]))   (define (eertree-get-sub-palindromes et) (define (inr nd (node-path (list nd)) (char-path/rev null))  ;; Each node represents a palindrome, which can be reconstructed by the path from the root node to  ;; each non-root node. (let ((deeper ; Traverse all edges, since they represent other palindromes (for/fold ((result null)) (([→-name nd2] (in-hash (node-edges nd))))  ; The lnk-name is the character used for this edge (append result (inr nd2 (append node-path (list nd2)) (cons →-name char-path/rev))))) (root-node? (or (eq? (eertree-rto et) nd) (eq? (eertree-rte et) nd)))) (if root-node? ; Don't add root nodes deeper (let ((even-string? (eq? (car node-path) (eertree-rte et))) (char-path (reverse char-path/rev))) (cons (append char-path/rev (if even-string? char-path (cdr char-path))) deeper))))) inr)   (define (eertree-get-palindromes et) (define sub (eertree-get-sub-palindromes et)) (append (sub (eertree-rto et)) (sub (eertree-rte et))))   (module+ main (define et (new-eertree))  ;; eertree works in integer space, so we'll map to/from char space here (for ((c "eertree")) (eertree-add! et (char->integer c))) (map (compose list->string (curry map integer->char)) (eertree-get-palindromes et)))  
http://rosettacode.org/wiki/Eertree
Eertree
An eertree is a data structure designed for efficient processing of certain palindrome tasks, for instance counting the number of sub-palindromes in an input string. The data structure has commonalities to both tries and suffix trees.   See links below. Task Construct an eertree for the string "eertree", then output all sub-palindromes by traversing the tree. See also   Wikipedia entry:   trie.   Wikipedia entry:   suffix tree   Cornell University Library, Computer Science, Data Structures and Algorithms ───► EERTREE: An Efficient Data Structure for Processing Palindromes in Strings.
#Raku
Raku
my $str = "eertree"; my @pal = (); my ($strrev,$strpal);   for (1 .. $str.chars) -> $n { for (1 .. $str.chars) -> $m { $strrev = ""; $strpal = $str.substr($n-1, $m); if ($strpal ne "") { for ($strpal.chars ... 1) -> $p { $strrev ~= $strpal.substr($p-1,1); } ($strpal eq $strrev) and @pal.push($strpal); } } }   say @pal.unique;  
http://rosettacode.org/wiki/Ethiopian_multiplication
Ethiopian multiplication
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last in the same column, until you write a value of 1. In the right-hand column repeatedly double the last number and write the result below. stop when you add a result in the same row as where the left hand column shows 1. Examine the table produced and discard any row where the value in the left column is even. Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together For example:   17 × 34 17 34 Halving the first column: 17 34 8 4 2 1 Doubling the second column: 17 34 8 68 4 136 2 272 1 544 Strike-out rows whose first cell is even: 17 34 8 68 4 136 2 272 1 544 Sum the remaining numbers in the right-hand column: 17 34 8 -- 4 --- 2 --- 1 544 ==== 578 So 17 multiplied by 34, by the Ethiopian method is 578. Task The task is to define three named functions/methods/procedures/subroutines: one to halve an integer, one to double an integer, and one to state if an integer is even. Use these functions to create a function that does Ethiopian multiplication. References Ethiopian multiplication explained (BBC Video clip) A Night Of Numbers - Go Forth And Multiply (Video) Russian Peasant Multiplication Programming Praxis: Russian Peasant Multiplication
#Raku
Raku
sub halve (Int $n is rw) { $n div= 2 } sub double (Int $n is rw) { $n *= 2 } sub even (Int $n --> Bool) { $n %% 2 }   sub ethiopic-mult (Int $a is copy, Int $b is copy --> Int) { my Int $r = 0; while $a { even $a or $r += $b; halve $a; double $b; } return $r; }   say ethiopic-mult(17,34);
http://rosettacode.org/wiki/Elementary_cellular_automaton
Elementary cellular automaton
An elementary cellular automaton is a one-dimensional cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three bits. The rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101. Task Create a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice. The space state should wrap: this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally. This task is basically a generalization of one-dimensional cellular automata. See also Cellular automata (natureofcode.com)
#F.C5.8Drmul.C3.A6
Fōrmulæ
  argc 4 < { ."Usage: " 0 argv sprint SPACE 1 argv sprint SPACE ."rule size\n" ."The \"rule\" and \"size\" are numbers.\n" ."0<=rule<=255\n" end } zero gen 3 argv #s (#g) sto maxcell 2 argv (#g) sto rule #g argc 5 >= { 4 argv #s (#g) sto gen } @maxcell mem !maximize sto livingspace @maxcell mem sto originallivingspace @maxcell {| @livingspace {} 0 [^] |} @livingspace @maxcell #g 2 / 1 [^] infi: {... originallivingspace @livingspace #s = @livingspace {~ #k @@ { '* }{ '. } print |} NL #g @livingspace~ lsp: {| zero a @originallivingspace {} ? @maxcell -- [] { 4 sto a } @originallivingspace {} [] { @a 2 | sto a } @originallivingspace {+} @maxcell == { 0 }{ {+} } [] { @a 1 | sto a } 8 {| @rule 1 {} << & { {} @a == { @livingspace {}§lsp 1 [^] {<}§lsp } } |} z: @livingspace {} 0 [^] {<} |}   #s @originallivingspace @livingspace == { {.>.} } @gen { {...} @gen #g == { {.>.} } }   ...} ."Generations: " {...}§infi #g printnl @livingspace free @originallivingspace free end { „maxcell” } { „rule” } { „state” } { „livingspace” } { „originallivingspace” } { „a” } { „gen” }   // =================================================  
http://rosettacode.org/wiki/Elementary_cellular_automaton
Elementary cellular automaton
An elementary cellular automaton is a one-dimensional cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three bits. The rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101. Task Create a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice. The space state should wrap: this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally. This task is basically a generalization of one-dimensional cellular automata. See also Cellular automata (natureofcode.com)
#Furor
Furor
  argc 4 < { ."Usage: " 0 argv sprint SPACE 1 argv sprint SPACE ."rule size\n" ."The \"rule\" and \"size\" are numbers.\n" ."0<=rule<=255\n" end } zero gen 3 argv #s (#g) sto maxcell 2 argv (#g) sto rule #g argc 5 >= { 4 argv #s (#g) sto gen } @maxcell mem !maximize sto livingspace @maxcell mem sto originallivingspace @maxcell {| @livingspace {} 0 [^] |} @livingspace @maxcell #g 2 / 1 [^] infi: {... originallivingspace @livingspace #s = @livingspace {~ #k @@ { '* }{ '. } print |} NL #g @livingspace~ lsp: {| zero a @originallivingspace {} ? @maxcell -- [] { 4 sto a } @originallivingspace {} [] { @a 2 | sto a } @originallivingspace {+} @maxcell == { 0 }{ {+} } [] { @a 1 | sto a } 8 {| @rule 1 {} << & { {} @a == { @livingspace {}§lsp 1 [^] {<}§lsp } } |} z: @livingspace {} 0 [^] {<} |}   #s @originallivingspace @livingspace == { {.>.} } @gen { {...} @gen #g == { {.>.} } }   ...} ."Generations: " {...}§infi #g printnl @livingspace free @originallivingspace free end { „maxcell” } { „rule” } { „state” } { „livingspace” } { „originallivingspace” } { „a” } { „gen” }   // =================================================  
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#TorqueScript
TorqueScript
function Factorial(%num) { if(%num < 2) return 1; for(%a = %num-1; %a > 1; %a--)  %num *= %a; return %num; }
http://rosettacode.org/wiki/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd. Use modular congruences: i ≡ 0 (mod 2) iff i is even. i ≡ 1 (mod 2) iff i is odd.
#Vlang
Vlang
fn test(n i64) { print('Testing integer $n')   if n&1 == 0 { print(' even') }else{ print(' odd') }   if n%2 == 0 { println(' even') }else{ println(' odd') } }   fn main(){ test(-2) test(-1) test(0) test(1) test(2) }
http://rosettacode.org/wiki/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd. Use modular congruences: i ≡ 0 (mod 2) iff i is even. i ≡ 1 (mod 2) iff i is odd.
#WDTE
WDTE
let s => import 'stream'; let str => import 'strings';   let evenOrOdd n => ( let even n => == (% n 2) 0; switch n { even => 'even'; default => 'odd'; }; );   s.range 10 -> s.map (@ s n => str.format '{} is {}.' n (evenOrOdd n)) -> s.map (io.writeln io.stdout) -> s.drain;
http://rosettacode.org/wiki/Echo_server
Echo server
Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary to support connections from localhost (127.0.0.1 or perhaps ::1). Logging of connection information to standard output is recommended. The implementation must be able to handle simultaneous connections from multiple clients. A multi-threaded or multi-process solution may be used. Each connection must be able to echo more than a single line. The implementation must not stop responding to other clients if one client sends a partial line or stops reading responses.
#Haskell
Haskell
module Main where import Network (withSocketsDo, accept, listenOn, sClose, PortID(PortNumber)) import Control.Monad (forever) import System.IO (hGetLine, hPutStrLn, hFlush, hClose) import System.IO.Error (isEOFError) import Control.Concurrent (forkIO) import Control.Exception (bracket)   -- For convenience in testing, ensure that the listen socket is closed if the main loop is aborted withListenOn port body = bracket (listenOn port) sClose body   echo (handle, host, port) = catch (forever doOneLine) stop where doOneLine = do line <- hGetLine handle print (host, port, init line) hPutStrLn handle line hFlush handle stop error = do putStrLn $ "Closed connection from " ++ show (host, port) ++ " due to " ++ show error hClose handle   main = withSocketsDo $ withListenOn (PortNumber 12321) $ \listener -> forever $ do acc@(_, host, port) <- accept listener putStrLn $ "Accepted connection from " ++ show (host, port) forkIO (echo acc)
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Swift
Swift
 
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Symsyn
Symsyn
 
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Tcl
Tcl
 
http://rosettacode.org/wiki/Eban_numbers
Eban numbers
Definition An   eban   number is a number that has no letter   e   in it when the number is spelled in English. Or more literally,   spelled numbers that contain the letter   e   are banned. The American version of spelling numbers will be used here   (as opposed to the British). 2,000,000,000   is two billion,   not   two milliard. Only numbers less than   one sextillion   (1021)   will be considered in/for this task. This will allow optimizations to be used. Task   show all eban numbers   ≤   1,000   (in a horizontal format),   and a count   show all eban numbers between   1,000   and   4,000   (inclusive),   and a count   show a count of all eban numbers up and including           10,000   show a count of all eban numbers up and including         100,000   show a count of all eban numbers up and including      1,000,000   show a count of all eban numbers up and including    10,000,000   show all output here. See also   The MathWorld entry:   eban numbers.   The OEIS entry:   A6933, eban numbers.
#AutoHotkey
AutoHotkey
eban_numbers(min, max, show:=0){ counter := 0, output := "" i := min while ((i+=2) <= max) { b := floor(i / 1000000000) r := Mod(i, 1000000000) m := floor(r / 1000000) r := Mod(i, 1000000) t := floor(r / 1000) r := Mod(r, 1000) if (m >= 30 && m <= 66) m := Mod(m, 10) if (t >= 30 && t <= 66) t := Mod(t, 10) if (r >= 30 && r <= 66) r := Mod(r, 10) if (b = 0 || b = 2 || b = 4 || b = 6) && (m = 0 || m = 2 || m = 4 || m = 6) && (t = 0 || t = 2 || t = 4 || t = 6) && (r = 0 || r = 2 || r = 4 || r = 6) counter++, (show ? output .= i " " : "") } return min "-" max " : " output " Count = " counter }
http://rosettacode.org/wiki/Duffinian_numbers
Duffinian numbers
A Duffinian number is a composite number k that is relatively prime to its sigma sum σ. The sigma sum of k is the sum of the divisors of k. E.G. 161 is a Duffinian number. It is composite. (7 × 23) The sigma sum 192 (1 + 7 + 23 + 161) is relatively prime to 161. Duffinian numbers are very common. It is not uncommon for two consecutive integers to be Duffinian (a Duffinian twin) (8, 9), (35, 36), (49, 50), etc. Less common are Duffinian triplets; three consecutive Duffinian numbers. (63, 64, 65), (323, 324, 325), etc. Much, much less common are Duffinian quadruplets and quintuplets. The first Duffinian quintuplet is (202605639573839041, 202605639573839042, 202605639573839043, 202605639573839044, 202605639573839045). It is not possible to have six consecutive Duffinian numbers Task Find and show the first 50 Duffinian numbers. Find and show at least the first 15 Duffinian triplets. See also Numbers Aplenty - Duffinian numbers OEIS:A003624 - Duffinian numbers: composite numbers k relatively prime to sigma(k)
#Arturo
Arturo
duffinian?: function [n]-> and? [not? prime? n] [ fn: factors n [1] = intersection factors sum fn fn ]   first50: new [] i: 0 while [50 > size first50][ if duffinian? i -> 'first50 ++ i i: i + 1 ]   print "The first 50 Duffinian numbers:" loop split.every: 10 first50 'row [ print map to [:string] row 'item -> pad item 3 ]   first15: new [] i: 0 while [15 > size first15][ if every? i..i+2 => duffinian? [ 'first15 ++ @[@[i, i+1, i+2]] i: i+2 ] i: i + 1 ]   print "" print "The first 15 Duffinian triplets:" loop split.every: 5 first15 'row [ print map row 'item -> pad.right as.code item 17 ]
http://rosettacode.org/wiki/Duffinian_numbers
Duffinian numbers
A Duffinian number is a composite number k that is relatively prime to its sigma sum σ. The sigma sum of k is the sum of the divisors of k. E.G. 161 is a Duffinian number. It is composite. (7 × 23) The sigma sum 192 (1 + 7 + 23 + 161) is relatively prime to 161. Duffinian numbers are very common. It is not uncommon for two consecutive integers to be Duffinian (a Duffinian twin) (8, 9), (35, 36), (49, 50), etc. Less common are Duffinian triplets; three consecutive Duffinian numbers. (63, 64, 65), (323, 324, 325), etc. Much, much less common are Duffinian quadruplets and quintuplets. The first Duffinian quintuplet is (202605639573839041, 202605639573839042, 202605639573839043, 202605639573839044, 202605639573839045). It is not possible to have six consecutive Duffinian numbers Task Find and show the first 50 Duffinian numbers. Find and show at least the first 15 Duffinian triplets. See also Numbers Aplenty - Duffinian numbers OEIS:A003624 - Duffinian numbers: composite numbers k relatively prime to sigma(k)
#C.2B.2B
C++
#include <iomanip> #include <iostream> #include <numeric> #include <sstream>   bool duffinian(int n) { if (n == 2) return false; int total = 1, power = 2, m = n; for (; (n & 1) == 0; power <<= 1, n >>= 1) total += power; for (int p = 3; p * p <= n; p += 2) { int sum = 1; for (power = p; n % p == 0; power *= p, n /= p) sum += power; total *= sum; } if (m == n) return false; if (n > 1) total *= n + 1; return std::gcd(total, m) == 1; }   int main() { std::cout << "First 50 Duffinian numbers:\n"; for (int n = 1, count = 0; count < 50; ++n) { if (duffinian(n)) std::cout << std::setw(3) << n << (++count % 10 == 0 ? '\n' : ' '); } std::cout << "\nFirst 50 Duffinian triplets:\n"; for (int n = 1, m = 0, count = 0; count < 50; ++n) { if (duffinian(n)) ++m; else m = 0; if (m == 3) { std::ostringstream os; os << '(' << n - 2 << ", " << n - 1 << ", " << n << ')'; std::cout << std::left << std::setw(24) << os.str() << (++count % 3 == 0 ? '\n' : ' '); } } std::cout << '\n'; }
http://rosettacode.org/wiki/Element-wise_operations
Element-wise operations
This task is similar to:   Matrix multiplication   Matrix transposition Task Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks. Implement:   addition   subtraction   multiplication   division   exponentiation Extend the task if necessary to include additional basic operations, which should not require their own specialised task.
#D
D
import std.stdio, std.typetuple, std.traits;   T[][] elementwise(string op, T, U)(in T[][] A, in U B) { auto R = new typeof(return)(A.length, A[0].length); foreach (r, row; A) R[r][] = mixin("row[] " ~ op ~ (isNumeric!U ? "B" : "B[r][]")); return R; }   void main() { const M = [[3, 5, 7], [1, 2, 3], [2, 4, 6]]; foreach (op; TypeTuple!("+", "-", "*", "/", "^^")) writefln("%s:\n[%([%(%d, %)],\n %)]]\n\n[%([%(%d, %)],\n %)]]\n", op, elementwise!op(M, 2), elementwise!op(M, M)); }
http://rosettacode.org/wiki/Dynamic_variable_names
Dynamic variable names
Task Create a variable with a user-defined name. The variable name should not be written in the program text, but should be taken from the user dynamically. See also   Eval in environment is a similar task.
#BASIC
BASIC
10 INPUT "Enter a variable name", v$ 20 KEYIN "LET "+v$+"=42"
http://rosettacode.org/wiki/Dynamic_variable_names
Dynamic variable names
Task Create a variable with a user-defined name. The variable name should not be written in the program text, but should be taken from the user dynamically. See also   Eval in environment is a similar task.
#Batch_File
Batch File
@echo off setlocal enableDelayedExpansion   set /p "name=Enter a variable name: " set /p "value=Enter a value: " ::Create the variable and set its value set "%name%=%value%" ::Display the value without delayed expansion call echo %name%=%%%name%%% ::Display the value using delayed expansion echo %name%=!%name%!
http://rosettacode.org/wiki/Egyptian_division
Egyptian division
Egyptian division is a method of dividing integers using addition and doubling that is similar to the algorithm of Ethiopian multiplication Algorithm: Given two numbers where the dividend is to be divided by the divisor: Start the construction of a table of two columns: powers_of_2, and doublings; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column. Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order. Continue with successive i’th rows of 2^i and 2^i * divisor. Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend. We now assemble two separate sums that both start as zero, called here answer and accumulator Consider each row of the table, in the reverse order of its construction. If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer. When the first row has been considered as above, then the integer division of dividend by divisor is given by answer. (And the remainder is given by the absolute value of accumulator - dividend). Example: 580 / 34 Table creation: powers_of_2 doublings 1 34 2 68 4 136 8 272 16 544 Initialization of sums: powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 0 0 Considering table rows, bottom-up: When a row is considered it is shown crossed out if it is not accumulated, or bold if the row causes summations. powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 4 136 16 544 8 272 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 16 544 4 136 8 272 16 544 powers_of_2 doublings answer accumulator 1 34 17 578 2 68 4 136 8 272 16 544 Answer So 580 divided by 34 using the Egyptian method is 17 remainder (578 - 580) or 2. Task The task is to create a function that does Egyptian division. The function should closely follow the description above in using a list/array of powers of two, and another of doublings. Functions should be clear interpretations of the algorithm. Use the function to divide 580 by 34 and show the answer here, on this page. Related tasks   Egyptian fractions References   Egyptian Number System
#C.2B.2B
C++
#include <cassert> #include <iostream>   typedef unsigned long ulong;   /* * Remainder is an out paramerter. Use nullptr if the remainder is not needed. */ ulong egyptian_division(ulong dividend, ulong divisor, ulong* remainder) { constexpr int SIZE = 64; ulong powers[SIZE]; ulong doublings[SIZE]; int i = 0;   for (; i < SIZE; ++i) { powers[i] = 1 << i; doublings[i] = divisor << i; if (doublings[i] > dividend) { break; } }   ulong answer = 0; ulong accumulator = 0;   for (i = i - 1; i >= 0; --i) { /* * If the current value of the accumulator added to the * doublings cell would be less than or equal to the * dividend then add it to the accumulator */ if (accumulator + doublings[i] <= dividend) { accumulator += doublings[i]; answer += powers[i]; } }   if (remainder) { *remainder = dividend - accumulator; } return answer; }   void print(ulong a, ulong b) { using namespace std;   ulong x, y; x = egyptian_division(a, b, &y);   cout << a << " / " << b << " = " << x << " remainder " << y << endl; assert(a == b * x + y); }   int main() { print(580, 34);   return 0; }
http://rosettacode.org/wiki/Egyptian_fractions
Egyptian fractions
An   Egyptian fraction   is the sum of distinct unit fractions such as: 1 2 + 1 3 + 1 16 ( = 43 48 ) {\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})} Each fraction in the expression has a numerator equal to   1   (unity)   and a denominator that is a positive integer,   and all the denominators are distinct   (i.e., no repetitions). Fibonacci's   Greedy algorithm for Egyptian fractions   expands the fraction   x y {\displaystyle {\tfrac {x}{y}}}   to be represented by repeatedly performing the replacement x y = 1 ⌈ y / x ⌉ + ( − y ) mod x y ⌈ y / x ⌉ {\displaystyle {\frac {x}{y}}={\frac {1}{\lceil y/x\rceil }}+{\frac {(-y)\!\!\!\!\mod x}{y\lceil y/x\rceil }}} (simplifying the 2nd term in this replacement as necessary, and where   ⌈ x ⌉ {\displaystyle \lceil x\rceil }   is the   ceiling   function). For this task,   Proper and improper fractions   must be able to be expressed. Proper  fractions   are of the form   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive integers, such that   a < b {\displaystyle a<b} ,     and improper fractions are of the form   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive integers, such that   a ≥ b. (See the REXX programming example to view one method of expressing the whole number part of an improper fraction.) For improper fractions, the integer part of any improper fraction should be first isolated and shown preceding the Egyptian unit fractions, and be surrounded by square brackets [n]. Task requirements   show the Egyptian fractions for: 43 48 {\displaystyle {\tfrac {43}{48}}} and 5 121 {\displaystyle {\tfrac {5}{121}}} and 2014 59 {\displaystyle {\tfrac {2014}{59}}}   for all proper fractions,   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive one-or two-digit (decimal) integers, find and show an Egyptian fraction that has:   the largest number of terms,   the largest denominator.   for all one-, two-, and three-digit integers,   find and show (as above).     {extra credit} Also see   Wolfram MathWorld™ entry: Egyptian fraction
#Erlang
Erlang
-module(egypt).   -import(lists, [reverse/1, seq/2]). -export([frac/2, show/2, rosetta/0]).   rosetta() -> Fractions = [{N, D, second(frac(N, D))} || N <- seq(2,99), D <- seq(N+1, 99)], {Longest, A1, B1} = findmax(fun length/1, Fractions), io:format("~b/~b has ~b terms.~n", [A1, B1, Longest]), {Largest, A2, B2} = findmax(fun (L) -> hd(reverse(L)) end, Fractions), io:format("~b/~b has a really long denominator. (~b)~n", [A2, B2, Largest]).   second({_, B}) -> B.   findmax(Fn, L) -> findmax(Fn, L, 0, 0, 0). findmax(_, [], M, A, B) -> {M, A, B}; findmax(Fn, [{A,B,Frac}|Fracs], M, A0, B0) -> Val = Fn(Frac), case Val > M of true -> findmax(Fn, Fracs, Val, A, B); false -> findmax(Fn, Fracs, M, A0, B0) end.   show(A, B) -> {W, R} = frac(A, B), case W of 0 -> ok; _ -> io:format("[~b] ", [W]) end, case R of [] -> ok; [D0|Ds] -> io:format("1/~b ", [D0]), [io:format("+ 1/~b ", [D]) || D <- Ds], ok end.   frac(A, B) -> {A div B, reverse(proper(A rem B, B, []))}.   proper(0, _, L) -> L; proper(1, Y, L) -> [Y|L]; proper(X, Y, L) -> D = ceildiv(Y, X), X2 = mod(-Y, X), Y2 = Y*ceildiv(Y, X), proper(X2, Y2, [D|L]).   ceildiv(A, B) -> Q = A div B, case A rem B of 0 -> Q; _ -> Q+1 end.   mod(A, M) -> B = A rem M, if B < 0 -> B + M; true -> B end.  
http://rosettacode.org/wiki/Eertree
Eertree
An eertree is a data structure designed for efficient processing of certain palindrome tasks, for instance counting the number of sub-palindromes in an input string. The data structure has commonalities to both tries and suffix trees.   See links below. Task Construct an eertree for the string "eertree", then output all sub-palindromes by traversing the tree. See also   Wikipedia entry:   trie.   Wikipedia entry:   suffix tree   Cornell University Library, Computer Science, Data Structures and Algorithms ───► EERTREE: An Efficient Data Structure for Processing Palindromes in Strings.
#REXX
REXX
/*REXX program creates a list of (unique) sub─palindromes that exist in an input string.*/ parse arg x . /*obtain optional input string from CL.*/ if x=='' | x=="," then x= 'eertree' /*Not specified? Then use the default.*/ L= length(x) /*the length (in chars) of input string*/ @.= . /*@ tree indicates uniqueness of pals. */ $= /*list of unsorted & unique palindromes*/ do j=1 for L /*start at the left side of the string.*/ do k=1 for L /*traverse from left to right of string*/ parse var x =(j) y +(k) /*extract a substring from the string. */ if reverse(y)\==y | @.y\==. then iterate /*Partial string a palindrome? Skip it*/ @.y= y /*indicate a sub─palindrome was found. */ $= $' ' y /*append the sub─palindrome to the list*/ end /*k*/ /* [↑] an extra blank is inserted. */ end /*j*/   say '──────── The input string that is being used: ' space(x) say '──────── The number of sub─palindromes found: ' words($) say '──────── The list of sub─palindromes found: ' strip($) /*stick a fork in it, we're all done. */
http://rosettacode.org/wiki/Eertree
Eertree
An eertree is a data structure designed for efficient processing of certain palindrome tasks, for instance counting the number of sub-palindromes in an input string. The data structure has commonalities to both tries and suffix trees.   See links below. Task Construct an eertree for the string "eertree", then output all sub-palindromes by traversing the tree. See also   Wikipedia entry:   trie.   Wikipedia entry:   suffix tree   Cornell University Library, Computer Science, Data Structures and Algorithms ───► EERTREE: An Efficient Data Structure for Processing Palindromes in Strings.
#Ring
Ring
  # Project : Eertree   str = "eertree" pal = [] for n=1 to len(str) for m=1 to len(str) strrev = "" strpal = substr(str, n, m) if strpal != "" for p=len(strpal) to 1 step -1 strrev = strrev + strpal[p] next if strpal = strrev add(pal, strpal) ok ok next next sortpal = sort(pal) for n=len(sortpal) to 2 step -1 if sortpal[n] = sortpal[n-1] del(sortpal, n) ok next see sortpal + nl  
http://rosettacode.org/wiki/Ethiopian_multiplication
Ethiopian multiplication
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last in the same column, until you write a value of 1. In the right-hand column repeatedly double the last number and write the result below. stop when you add a result in the same row as where the left hand column shows 1. Examine the table produced and discard any row where the value in the left column is even. Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together For example:   17 × 34 17 34 Halving the first column: 17 34 8 4 2 1 Doubling the second column: 17 34 8 68 4 136 2 272 1 544 Strike-out rows whose first cell is even: 17 34 8 68 4 136 2 272 1 544 Sum the remaining numbers in the right-hand column: 17 34 8 -- 4 --- 2 --- 1 544 ==== 578 So 17 multiplied by 34, by the Ethiopian method is 578. Task The task is to define three named functions/methods/procedures/subroutines: one to halve an integer, one to double an integer, and one to state if an integer is even. Use these functions to create a function that does Ethiopian multiplication. References Ethiopian multiplication explained (BBC Video clip) A Night Of Numbers - Go Forth And Multiply (Video) Russian Peasant Multiplication Programming Praxis: Russian Peasant Multiplication
#Rascal
Rascal
import IO;   public int halve(int n) = n/2;   public int double(int n) = n*2;   public bool uneven(int n) = (n % 2) != 0);   public int ethiopianMul(int n, int m) { result = 0; while(n >= 1) { if(uneven(n)) result += m; n = halve(n); m = double(m); } return result; }
http://rosettacode.org/wiki/Elementary_cellular_automaton
Elementary cellular automaton
An elementary cellular automaton is a one-dimensional cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three bits. The rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101. Task Create a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice. The space state should wrap: this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally. This task is basically a generalization of one-dimensional cellular automata. See also Cellular automata (natureofcode.com)
#GFA_Basic
GFA Basic
  ' ' Elementary One-Dimensional Cellular Automaton ' ' World is cyclic, and rules are defined by a parameter ' ' start$="01110110101010100100" ! start state for world ' rules%=104 ! number defining rule-set to use start$="00000000000000000000100000000000000000000" rules%=18 max_cycles%=20 ! give a maximum depth to world ' ' Global variables hold the world, with two rows ' world! is treated as cyclical ' cur% gives the row for current world, ' new% gives the row for the next world. ' size%=LEN(start$) DIM world!(size%,2) cur%=0 new%=1 clock%=0 ' @setup_world(start$) OPENW 1 CLEARW 1 DO @display_world @update_world EXIT IF @same_state clock%=clock%+1 EXIT IF clock%>max_cycles% ! safety net LOOP ~INP(2) CLOSEW 1 ' ' parse given string to set up initial states in world ' -- assumes world! is of correct size ' PROCEDURE setup_world(defn$) LOCAL i% ' clear out the array ARRAYFILL world!(),FALSE ' for each 1 in string, set cell to true FOR i%=1 TO LEN(defn$) IF MID$(defn$,i%,1)="1" world!(i%-1,0)=TRUE ENDIF NEXT i% ' set references to cur and new cur%=0 new%=1 RETURN ' ' Display the world ' PROCEDURE display_world LOCAL i% FOR i%=1 TO size% IF world!(i%-1,cur%) PRINT "#"; ELSE PRINT "."; ENDIF NEXT i% PRINT "" RETURN ' ' Create new version of world ' PROCEDURE update_world LOCAL i% FOR i%=1 TO size% world!(i%-1,new%)=@new_state(@get_value(i%-1)) NEXT i% ' reverse cur/new cur%=1-cur% new%=1-new% RETURN ' ' Test if cur/new states are the same ' FUNCTION same_state LOCAL i% FOR i%=1 TO size% IF world!(i%-1,cur%)<>world!(i%-1,new%) RETURN FALSE ENDIF NEXT i% RETURN TRUE ENDFUNC ' ' Return new state of cell given value ' FUNCTION new_state(value%) RETURN BTST(rules%,value%) ENDFUNC ' ' Compute value for cell + neighbours ' FUNCTION get_value(cell%) LOCAL result% result%=0 IF cell%-1<0 ! check for wrapping at left IF world!(size%-1,cur%) result%=result%+4 ENDIF ELSE ! no wrapping IF world!(cell%-1,cur%) result%=result%+4 ENDIF ENDIF IF world!(cell%,cur%) result%=result%+2 ENDIF IF cell%+1>size% ! check for wrapping at right IF world!(0,cur%) result%=result%+1 ENDIF ELSE ! no wrapping IF world!(cell%+1,cur%) result%=result%+1 ENDIF ENDIF RETURN result% ENDFUNC  
http://rosettacode.org/wiki/Elementary_cellular_automaton
Elementary cellular automaton
An elementary cellular automaton is a one-dimensional cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three bits. The rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101. Task Create a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice. The space state should wrap: this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally. This task is basically a generalization of one-dimensional cellular automata. See also Cellular automata (natureofcode.com)
#Go
Go
package main   import ( "fmt" "math/big" "math/rand" "strings" )   func main() { const cells = 20 const generations = 9 fmt.Println("Single 1, rule 90:") a := big.NewInt(1) a.Lsh(a, cells/2) elem(90, cells, generations, a) fmt.Println("Random intial state, rule 30:") a = big.NewInt(1) a.Rand(rand.New(rand.NewSource(3)), a.Lsh(a, cells)) elem(30, cells, generations, a) }   func elem(rule uint, cells, generations int, a *big.Int) { output := func() { fmt.Println(strings.Replace(strings.Replace( fmt.Sprintf("%0*b", cells, a), "0", " ", -1), "1", "#", -1)) } output() a1 := new(big.Int) set := func(cell int, k uint) { a1.SetBit(a1, cell, rule>>k&1) } last := cells - 1 for r := 0; r < generations; r++ { k := a.Bit(last) | a.Bit(0)<<1 | a.Bit(1)<<2 set(0, k) for c := 1; c < last; c++ { k = k>>1 | a.Bit(c+1)<<2 set(c, k) } set(last, k>>1|a.Bit(0)<<2) a, a1 = a1, a output() } }
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#TransFORTH
TransFORTH
: FACTORIAL 1 SWAP 1 + 1 DO I * LOOP ;
http://rosettacode.org/wiki/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd. Use modular congruences: i ≡ 0 (mod 2) iff i is even. i ≡ 1 (mod 2) iff i is odd.
#WebAssembly
WebAssembly
(module  ;; function isOdd: returns 1 if its argument is odd, 0 if it is even. (func $isOdd (param $n i32) (result i32) get_local $n i32.const 1 i32.and  ;; computes (n & 1), i.e. returns low bit of n ) (export "isOdd" (func $isOdd)) )
http://rosettacode.org/wiki/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd. Use modular congruences: i ≡ 0 (mod 2) iff i is even. i ≡ 1 (mod 2) iff i is odd.
#Wren
Wren
import "/fmt" for Fmt   var isEven1 = Fn.new { |i| i & 1 == 0 }   var isEven2 = Fn.new { |i| i % 2 == 0 }   var tests = [10, 11, 0, 57, 34, -23, -42] System.print("Tests  : %(Fmt.v("s", -4, tests, 0, " ", ""))") var res1 = tests.map { |t| isEven1.call(t) ? "even" : "odd" }.toList System.print("Method 1 : %(Fmt.v("s", -4, res1, 0, " ", ""))") var res2 = tests.map { |t| isEven2.call(t) ? "even" : "odd" }.toList System.print("Method 2 : %(Fmt.v("s", -4, res2, 0, " ", ""))")
http://rosettacode.org/wiki/Echo_server
Echo server
Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary to support connections from localhost (127.0.0.1 or perhaps ::1). Logging of connection information to standard output is recommended. The implementation must be able to handle simultaneous connections from multiple clients. A multi-threaded or multi-process solution may be used. Each connection must be able to echo more than a single line. The implementation must not stop responding to other clients if one client sends a partial line or stops reading responses.
#Icon_and_Unicon
Icon and Unicon
global mlck, nCons   procedure main() mlck := mutex() nCons := 0 while f := open(":12321","na") do { handle_client(f) critical mlck: if nCons <= 0 then close(f) } end   procedure handle_client(f) critical mlck: nCons +:= 1 thread { select(f,1000) & repeat writes(f,reads(f)) critical mlck: nCons -:= 1 } end
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#TI-83_BASIC
TI-83 BASIC
 
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#TI-83_Hex_Assembly
TI-83 Hex Assembly
PROGRAM:EMPTY :AsmPrgmC9
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#TI-89_BASIC
TI-89 BASIC
Prgm EndPrgm