task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: Fn = Fn+2 - Fn+1, if n<0 support for negative     n     in the solution is optional. Related tasks   Fibonacci n-step number sequences‎   Leonardo numbers References   Wikipedia, Fibonacci number   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#VBScript
VBScript
class generator dim t1 dim t2 dim tn dim cur_overflow   Private Sub Class_Initialize cur_overflow = false t1 = ccur(0) t2 = ccur(1) tn = ccur(t1 + t2) end sub   public default property get generated on error resume next   generated = ccur(tn) if err.number <> 0 then generated = cdbl(tn) cur_overflow = true end if t1 = ccur(t2) if err.number <> 0 then t1 = cdbl(t2) cur_overflow = true end if t2 = ccur(tn) if err.number <> 0 then t2 = cdbl(tn) cur_overflow = true end if tn = ccur(t1+ t2) if err.number <> 0 then tn = cdbl(t1) + cdbl(t2) cur_overflow = true end if on error goto 0 end property   public property get overflow overflow = cur_overflow end property   end class
http://rosettacode.org/wiki/Equal_prime_and_composite_sums
Equal prime and composite sums
Suppose we have a sequence of prime sums, where each term Pn is the sum of the first n primes. P = (2), (2 + 3), (2 + 3 + 5), (2 + 3 + 5 + 7), (2 + 3 + 5 + 7 + 11), ... P = 2, 5, 10, 17, 28, etc. Further; suppose we have a sequence of composite sums, where each term Cm is the sum of the first m composites. C = (4), (4 + 6), (4 + 6 + 8), (4 + 6 + 8 + 9), (4 + 6 + 8 + 9 + 10), ... C = 4, 10, 18, 27, 37, etc. Notice that the third term of P; P3 (10) is equal to the second term of C; C2 (10); Task Find and display the indices (n, m) and value of at least the first 6 terms of the sequence of numbers that are both the sum of the first n primes and the first m composites. See also OEIS:A007504 - Sum of the first n primes OEIS:A053767 - Sum of first n composite numbers OEIS:A294174 - Numbers that can be expressed both as the sum of first primes and as the sum of first composites
#XPL0
XPL0
func IsPrime(N); \Return 'true' if N is prime int N, I; [if N <= 2 then return N = 2; if (N&1) = 0 then \even >2\ return false; for I:= 3 to sqrt(N) do [if rem(N/I) = 0 then return false; I:= I+1; ]; return true; ];   int Cnt, N, M, SumP, SumC, NumP, NumC; [Cnt:= 0; N:= 1; M:= 1; NumP:= 2; NumC:= 4; SumP:= 2; SumC:= 4; Format(8, 0); Text(0, " sum prime composit "); loop [if SumC > SumP then [repeat NumP:= NumP+1 until IsPrime(NumP); SumP:= SumP + NumP; N:= N+1; ]; if SumP > SumC then [repeat NumC:= NumC+1 until not IsPrime(NumC); SumC:= SumC + NumC; M:= M+1; ]; if SumP = SumC then [RlOut(0, float(SumP)); RlOut(0, float(N)); RlOut(0, float(M)); CrLf(0); Cnt:= Cnt+1; if Cnt >= 6 then quit; repeat NumC:= NumC+1 until not IsPrime(NumC); SumC:= SumC + NumC; M:= M+1; ]; ]; ]
http://rosettacode.org/wiki/Entropy/Narcissist
Entropy/Narcissist
Task Write a computer program that computes and shows its own   entropy. Related Tasks   Fibonacci_word   Entropy
#Ada
Ada
with Ada.Text_Io; with Ada.Command_Line; with Ada.Numerics.Elementary_Functions;   procedure Entropy is use Ada.Text_Io;   type Hist_Type is array (Character) of Natural;   function Log_2 (V : Float) return Float is use Ada.Numerics.Elementary_Functions; begin return Log (V) / Log (2.0); end Log_2;   procedure Read_File (Name : String; Hist : out Hist_Type) is File : File_Type; Char : Character; begin Hist := (others => 0); Open (File, In_File, Name); while not End_Of_File (File) loop Get (File, Char); Hist (Char) := Hist (Char) + 1; end loop; Close (File); end Read_File;   function Length_Of (Hist : Hist_Type) return Natural is Sum : Natural := 0; begin for V of Hist loop Sum := Sum + V; end loop; return Sum; end Length_Of;   function Entropy_Of (Hist : Hist_Type) return Float is Length : constant Float := Float (Length_Of (Hist)); Sum  : Float := 0.0; begin for V of Hist loop if V > 0 then Sum := Sum + Float (V) / Length * Log_2 (Float (V) / Length); end if; end loop; return -Sum; end Entropy_Of;   package Float_Io is new Ada.Text_Io.Float_Io (Float); Name : constant String := Ada.Command_Line.Argument (1); Hist : Hist_Type; Entr : Float; begin Float_Io.Default_Exp := 0; Float_Io.Default_Aft := 6;   Read_File (Name, Hist); Entr := Entropy_Of (Hist);   Put ("Entropy of '"); Put (Name); Put ("' is "); Float_Io.Put (Entr); New_Line; end Entropy;
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
#ActionScript
ActionScript
function Divide(a:Number):Number { return ((a-(a%2))/2); } function Multiply(a:Number):Number { return (a *= 2); } function isEven(a:Number):Boolean { if (a%2 == 0) { return (true); } else { return (false); } } function Ethiopian(left:Number, right:Number) { var r:Number = 0; trace(left+" "+right); while (left != 1) { var State:String = "Keep"; if (isEven(Divide(left))) { State = "Strike"; } trace(Divide(left)+" "+Multiply(right)+" "+State); left = Divide(left); right = Multiply(right); if (State == "Keep") { r += right; } } trace("="+" "+r); } }
http://rosettacode.org/wiki/Equilibrium_index
Equilibrium index
An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices. For example, in a sequence   A {\displaystyle A} :   A 0 = − 7 {\displaystyle A_{0}=-7}   A 1 = 1 {\displaystyle A_{1}=1}   A 2 = 5 {\displaystyle A_{2}=5}   A 3 = 2 {\displaystyle A_{3}=2}   A 4 = − 4 {\displaystyle A_{4}=-4}   A 5 = 3 {\displaystyle A_{5}=3}   A 6 = 0 {\displaystyle A_{6}=0} 3   is an equilibrium index, because:   A 0 + A 1 + A 2 = A 4 + A 5 + A 6 {\displaystyle A_{0}+A_{1}+A_{2}=A_{4}+A_{5}+A_{6}} 6   is also an equilibrium index, because:   A 0 + A 1 + A 2 + A 3 + A 4 + A 5 = 0 {\displaystyle A_{0}+A_{1}+A_{2}+A_{3}+A_{4}+A_{5}=0} (sum of zero elements is zero) 7   is not an equilibrium index, because it is not a valid index of sequence A {\displaystyle A} . Task; Write a function that, given a sequence, returns its equilibrium indices (if any). Assume that the sequence may be very long.
#ABAP
ABAP
REPORT equilibrium_index.   TYPES: y_i TYPE STANDARD TABLE OF i WITH EMPTY KEY.   cl_demo_output=>display( REDUCE y_i( LET sequences = VALUE y_i( ( -7 ) ( 1 ) ( 5 ) ( 2 ) ( -4 ) ( 3 ) ( 0 ) ) total_sum = REDUCE #( INIT sum = 0 FOR sequence IN sequences NEXT sum = sum + ( sequence ) ) IN INIT x = VALUE y_i( ) y = 0 FOR i = 1 UNTIL i > lines( sequences ) LET z = sequences[ i ] IN NEXT x = COND #( WHEN y = ( total_sum - y - z ) THEN VALUE y_i( BASE x ( i - 1 ) ) ELSE x ) y = y + z ) ).
http://rosettacode.org/wiki/Environment_variables
Environment variables
Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
#Ada
Ada
with Ada.Environment_Variables; use Ada.Environment_Variables; with Ada.Text_Io; use Ada.Text_Io;   procedure Print_Path is begin Put_Line("Path : " & Value("PATH")); end Print_Path;
http://rosettacode.org/wiki/Environment_variables
Environment variables
Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
#ALGOL_68
ALGOL 68
print((getenv("HOME"), new line))
http://rosettacode.org/wiki/Environment_variables
Environment variables
Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
#APL
APL
  ⎕ENV 'HOME' HOME /home/russtopia  
http://rosettacode.org/wiki/Esthetic_numbers
Esthetic numbers
An esthetic number is a positive integer where every adjacent digit differs from its neighbour by 1. E.G. 12 is an esthetic number. One and two differ by 1. 5654 is an esthetic number. Each digit is exactly 1 away from its neighbour. 890 is not an esthetic number. Nine and zero differ by 9. These examples are nominally in base 10 but the concept extends easily to numbers in other bases. Traditionally, single digit numbers are included in esthetic numbers; zero may or may not be. For our purposes, for this task, do not include zero (0) as an esthetic number. Do not include numbers with leading zeros. Esthetic numbers are also sometimes referred to as stepping numbers. Task Write a routine (function, procedure, whatever) to find esthetic numbers in a given base. Use that routine to find esthetic numbers in bases 2 through 16 and display, here on this page, the esthectic numbers from index (base × 4) through index (base × 6), inclusive. (E.G. for base 2: 8th through 12th, for base 6: 24th through 36th, etc.) Find and display, here on this page, the base 10 esthetic numbers with a magnitude between 1000 and 9999. Stretch: Find and display, here on this page, the base 10 esthetic numbers with a magnitude between 1.0e8 and 1.3e8. Related task   numbers with equal rises and falls See also OEIS A033075 - Positive numbers n such that all pairs of consecutive decimal digits differ by 1 Numbers Aplenty - Esthetic numbers Geeks for Geeks - Stepping numbers
#J
J
isesthetic=: 10&$: :(1 */ .=2 |@-/\ #.inv)"0   gen=: {{r=.$k=.1 while.y>#r do. r=.r,k#~u k k=.1+({:k)+i.2*#k end.y{.r}}
http://rosettacode.org/wiki/Euler%27s_sum_of_powers_conjecture
Euler's sum of powers conjecture
There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin. Euler's (disproved) sum of powers   conjecture At least k positive kth powers are required to sum to a kth power, except for the trivial case of one kth power: yk = yk In 1966,   Leon J. Lander   and   Thomas R. Parkin   used a brute-force search on a   CDC 6600   computer restricting numbers to those less than 250. Task Write a program to search for an integer solution for: x05 + x15 + x25 + x35 == y5 Where all   xi's   and   y   are distinct integers between   0   and   250   (exclusive). Show an answer here. Related tasks   Pythagorean quadruples.   Pythagorean triples.
#AWK
AWK
  # syntax: GAWK -f EULERS_SUM_OF_POWERS_CONJECTURE.AWK BEGIN { start_int = systime() main() printf("%d seconds\n",systime()-start_int) exit(0) } function main( sum,s1,x0,x1,x2,x3) { for (x0=1; x0<=250; x0++) { for (x1=1; x1<=x0; x1++) { for (x2=1; x2<=x1; x2++) { for (x3=1; x3<=x2; x3++) { sum = (x0^5) + (x1^5) + (x2^5) + (x3^5) s1 = int(sum ^ 0.2) if (sum == s1^5) { printf("%d^5 + %d^5 + %d^5 + %d^5 = %d^5\n",x0,x1,x2,x3,s1) return } } } } } }  
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
#Microsoft_Small_Basic
Microsoft Small Basic
'Factorial - smallbasic - 05/01/2019 For n = 1 To 25 f = 1 For i = 1 To n f = f * i EndFor TextWindow.WriteLine("Factorial(" + n + ")=" + f) EndFor
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.
#ALGOL-M
ALGOL-M
  BEGIN   % RETURN 1 IF EVEN, OTHERWISE 0 % INTEGER FUNCTION EVEN(I); INTEGER I; BEGIN EVEN := 1 - (I - 2 * (I / 2)); END;   % TEST THE ROUTINE % INTEGER K; FOR K := 1 STEP 3 UNTIL 10 DO WRITE(K," IS ", IF EVEN(K) = 1 THEN "EVEN" ELSE "ODD");   END
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.
#ALGOL_W
ALGOL W
begin  % the Algol W standard procedure odd returns true if its integer  %  % parameter is odd, false if it is even  % for i := 1, 1702, 23, -26 do begin write( i, " is ", if odd( i ) then "odd" else "even" ) end for_i end.
http://rosettacode.org/wiki/Euler_method
Euler method
Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value.   It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page. The ODE has to be provided in the following form: d y ( t ) d t = f ( t , y ( t ) ) {\displaystyle {\frac {dy(t)}{dt}}=f(t,y(t))} with an initial value y ( t 0 ) = y 0 {\displaystyle y(t_{0})=y_{0}} To get a numeric solution, we replace the derivative on the   LHS   with a finite difference approximation: d y ( t ) d t ≈ y ( t + h ) − y ( t ) h {\displaystyle {\frac {dy(t)}{dt}}\approx {\frac {y(t+h)-y(t)}{h}}} then solve for y ( t + h ) {\displaystyle y(t+h)} : y ( t + h ) ≈ y ( t ) + h d y ( t ) d t {\displaystyle y(t+h)\approx y(t)+h\,{\frac {dy(t)}{dt}}} which is the same as y ( t + h ) ≈ y ( t ) + h f ( t , y ( t ) ) {\displaystyle y(t+h)\approx y(t)+h\,f(t,y(t))} The iterative solution rule is then: y n + 1 = y n + h f ( t n , y n ) {\displaystyle y_{n+1}=y_{n}+h\,f(t_{n},y_{n})} where   h {\displaystyle h}   is the step size, the most relevant parameter for accuracy of the solution.   A smaller step size increases accuracy but also the computation cost, so it has always has to be hand-picked according to the problem at hand. Example: Newton's Cooling Law Newton's cooling law describes how an object of initial temperature   T ( t 0 ) = T 0 {\displaystyle T(t_{0})=T_{0}}   cools down in an environment of temperature   T R {\displaystyle T_{R}} : d T ( t ) d t = − k Δ T {\displaystyle {\frac {dT(t)}{dt}}=-k\,\Delta T} or d T ( t ) d t = − k ( T ( t ) − T R ) {\displaystyle {\frac {dT(t)}{dt}}=-k\,(T(t)-T_{R})} It says that the cooling rate   d T ( t ) d t {\displaystyle {\frac {dT(t)}{dt}}}   of the object is proportional to the current temperature difference   Δ T = ( T ( t ) − T R ) {\displaystyle \Delta T=(T(t)-T_{R})}   to the surrounding environment. The analytical solution, which we will compare to the numerical approximation, is T ( t ) = T R + ( T 0 − T R ) e − k t {\displaystyle T(t)=T_{R}+(T_{0}-T_{R})\;e^{-kt}} Task Implement a routine of Euler's method and then to use it to solve the given example of Newton's cooling law with it for three different step sizes of:   2 s   5 s       and   10 s and to compare with the analytical solution. Initial values   initial temperature   T 0 {\displaystyle T_{0}}   shall be   100 °C   room temperature   T R {\displaystyle T_{R}}   shall be   20 °C   cooling constant     k {\displaystyle k}     shall be   0.07   time interval to calculate shall be from   0 s   ──►   100 s A reference solution (Common Lisp) can be seen below.   We see that bigger step sizes lead to reduced approximation accuracy.
#J
J
NB.*euler a Approximates Y(t) in Y'(t)=f(t,Y) with Y(a)=Y0 and t=a..b and step size h. euler=: adverb define 'Y0 a b h'=. 4{. y t=. i.@>:&.(%&h) b - a Y=. (+ h * u)^:(<#t) Y0 t,.Y )   ncl=: _0.07 * -&20 NB. Newton's Cooling Law  
http://rosettacode.org/wiki/Euler_method
Euler method
Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value.   It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page. The ODE has to be provided in the following form: d y ( t ) d t = f ( t , y ( t ) ) {\displaystyle {\frac {dy(t)}{dt}}=f(t,y(t))} with an initial value y ( t 0 ) = y 0 {\displaystyle y(t_{0})=y_{0}} To get a numeric solution, we replace the derivative on the   LHS   with a finite difference approximation: d y ( t ) d t ≈ y ( t + h ) − y ( t ) h {\displaystyle {\frac {dy(t)}{dt}}\approx {\frac {y(t+h)-y(t)}{h}}} then solve for y ( t + h ) {\displaystyle y(t+h)} : y ( t + h ) ≈ y ( t ) + h d y ( t ) d t {\displaystyle y(t+h)\approx y(t)+h\,{\frac {dy(t)}{dt}}} which is the same as y ( t + h ) ≈ y ( t ) + h f ( t , y ( t ) ) {\displaystyle y(t+h)\approx y(t)+h\,f(t,y(t))} The iterative solution rule is then: y n + 1 = y n + h f ( t n , y n ) {\displaystyle y_{n+1}=y_{n}+h\,f(t_{n},y_{n})} where   h {\displaystyle h}   is the step size, the most relevant parameter for accuracy of the solution.   A smaller step size increases accuracy but also the computation cost, so it has always has to be hand-picked according to the problem at hand. Example: Newton's Cooling Law Newton's cooling law describes how an object of initial temperature   T ( t 0 ) = T 0 {\displaystyle T(t_{0})=T_{0}}   cools down in an environment of temperature   T R {\displaystyle T_{R}} : d T ( t ) d t = − k Δ T {\displaystyle {\frac {dT(t)}{dt}}=-k\,\Delta T} or d T ( t ) d t = − k ( T ( t ) − T R ) {\displaystyle {\frac {dT(t)}{dt}}=-k\,(T(t)-T_{R})} It says that the cooling rate   d T ( t ) d t {\displaystyle {\frac {dT(t)}{dt}}}   of the object is proportional to the current temperature difference   Δ T = ( T ( t ) − T R ) {\displaystyle \Delta T=(T(t)-T_{R})}   to the surrounding environment. The analytical solution, which we will compare to the numerical approximation, is T ( t ) = T R + ( T 0 − T R ) e − k t {\displaystyle T(t)=T_{R}+(T_{0}-T_{R})\;e^{-kt}} Task Implement a routine of Euler's method and then to use it to solve the given example of Newton's cooling law with it for three different step sizes of:   2 s   5 s       and   10 s and to compare with the analytical solution. Initial values   initial temperature   T 0 {\displaystyle T_{0}}   shall be   100 °C   room temperature   T R {\displaystyle T_{R}}   shall be   20 °C   cooling constant     k {\displaystyle k}     shall be   0.07   time interval to calculate shall be from   0 s   ──►   100 s A reference solution (Common Lisp) can be seen below.   We see that bigger step sizes lead to reduced approximation accuracy.
#Java
Java
  public class Euler { private static void euler (Callable f, double y0, int a, int b, int h) { int t = a; double y = y0; while (t < b) { System.out.println ("" + t + " " + y); t += h; y += h * f.compute (t, y); } System.out.println ("DONE"); }   public static void main (String[] args) { Callable cooling = new Cooling (); int[] steps = {2, 5, 10}; for (int stepSize : steps) { System.out.println ("Step size: " + stepSize); euler (cooling, 100.0, 0, 100, stepSize); } } }   // interface used so we can plug in alternative functions to Euler interface Callable { public double compute (int time, double t); }   // class to implement the newton cooling equation class Cooling implements Callable { public double compute (int time, double t) { return -0.07 * (t - 20); } }  
http://rosettacode.org/wiki/Evaluate_binomial_coefficients
Evaluate binomial coefficients
This programming task, is to calculate ANY binomial coefficient. However, it has to be able to output   ( 5 3 ) {\displaystyle {\binom {5}{3}}} ,   which is   10. This formula is recommended: ( n k ) = n ! ( n − k ) ! k ! = n ( n − 1 ) ( n − 2 ) … ( n − k + 1 ) k ( k − 1 ) ( k − 2 ) … 1 {\displaystyle {\binom {n}{k}}={\frac {n!}{(n-k)!k!}}={\frac {n(n-1)(n-2)\ldots (n-k+1)}{k(k-1)(k-2)\ldots 1}}} See Also: Combinations and permutations Pascal's triangle The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#C.23
C#
using System;   namespace BinomialCoefficients { class Program { static void Main(string[] args) { ulong n = 1000000, k = 3; ulong result = biCoefficient(n, k); Console.WriteLine("The Binomial Coefficient of {0}, and {1}, is equal to: {2}", n, k, result); Console.ReadLine(); }   static int fact(int n) { if (n == 0) return 1; else return n * fact(n - 1); }   static ulong biCoefficient(ulong n, ulong k) { if (k > n - k) { k = n - k; }   ulong c = 1; for (uint i = 0; i < k; i++) { c = c * (n - i); c = c / (i + 1); } return c; } } }
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: Fn = Fn+2 - Fn+1, if n<0 support for negative     n     in the solution is optional. Related tasks   Fibonacci n-step number sequences‎   Leonardo numbers References   Wikipedia, Fibonacci number   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#Vedit_macro_language
Vedit macro language
:FIBONACCI: #11 = 0 #12 = 1 Repeat(#1) { #10 = #11 + #12 #11 = #12 #12 = #10 } Return(#11)
http://rosettacode.org/wiki/Entropy/Narcissist
Entropy/Narcissist
Task Write a computer program that computes and shows its own   entropy. Related Tasks   Fibonacci_word   Entropy
#ALGOL_68
ALGOL 68
BEGIN # calculate the shannon entropy of a string # PROC shannon entropy = ( STRING s )REAL: BEGIN INT string length = ( UPB s - LWB s ) + 1; # count the occurances of each character # [ 0 : max abs char ]INT char count; FOR char pos FROM LWB char count TO UPB char count DO char count[ char pos ] := 0 OD; FOR char pos FROM LWB s TO UPB s DO char count[ ABS s[ char pos ] ] +:= 1 OD; # calculate the entropy, we use log base 10 and then convert # # to log base 2 after calculating the sum # REAL entropy := 0; FOR char pos FROM LWB char count TO UPB char count DO IF char count[ char pos ] /= 0 THEN # have a character that occurs in the string # REAL probability = char count[ char pos ] / string length; entropy -:= probability * log( probability ) FI OD; entropy / log( 2 ) END; # shannon entropy #   IF FILE input file; STRING file name = "entropyNarcissist.a68"; open( input file, file name, stand in channel ) /= 0 THEN # failed to open the file # print( ( "Unable to open """ + file name + """", newline ) ) ELSE # file opened OK # BOOL at eof := FALSE; # set the EOF handler for the file # on logical file end( input file , ( REF FILE f )BOOL: BEGIN # note that we reached EOF on the latest read # at eof := TRUE; # return TRUE so processing can continue # TRUE END ); # construct a string containing the whole file # STRING file contents := ""; WHILE STRING line; get( input file, ( line, newline ) ); NOT at eof DO file contents +:= line + REPR 12 OD; close( input file ); # show the entropy of the file cotents # print( ( shannon entropy( file contents ), newline ) ) FI END
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
#Ada
Ada
  with ada.text_io;use ada.text_io;   procedure ethiopian is function double (n : Natural) return Natural is (2*n); function halve (n : Natural) return Natural is (n/2); function is_even (n : Natural) return Boolean is (n mod 2 = 0);   function mul (l, r : Natural) return Natural is (if l = 0 then 0 elsif l = 1 then r elsif is_even (l) then mul (halve (l),double (r)) else r + double (mul (halve (l), r)));   begin put_line (mul (17,34)'img); end ethiopian;
http://rosettacode.org/wiki/Equilibrium_index
Equilibrium index
An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices. For example, in a sequence   A {\displaystyle A} :   A 0 = − 7 {\displaystyle A_{0}=-7}   A 1 = 1 {\displaystyle A_{1}=1}   A 2 = 5 {\displaystyle A_{2}=5}   A 3 = 2 {\displaystyle A_{3}=2}   A 4 = − 4 {\displaystyle A_{4}=-4}   A 5 = 3 {\displaystyle A_{5}=3}   A 6 = 0 {\displaystyle A_{6}=0} 3   is an equilibrium index, because:   A 0 + A 1 + A 2 = A 4 + A 5 + A 6 {\displaystyle A_{0}+A_{1}+A_{2}=A_{4}+A_{5}+A_{6}} 6   is also an equilibrium index, because:   A 0 + A 1 + A 2 + A 3 + A 4 + A 5 = 0 {\displaystyle A_{0}+A_{1}+A_{2}+A_{3}+A_{4}+A_{5}=0} (sum of zero elements is zero) 7   is not an equilibrium index, because it is not a valid index of sequence A {\displaystyle A} . Task; Write a function that, given a sequence, returns its equilibrium indices (if any). Assume that the sequence may be very long.
#Action.21
Action!
PROC PrintArray(INT ARRAY a INT size) INT i   Put('[) FOR i=0 TO size-1 DO IF i>0 THEN Put(' ) FI PrintI(a(i)) OD Put(']) PutE() RETURN   INT FUNC SumRange(INT ARRAY a INT first,last) INT sum INT i   sum=0 FOR i=first TO last DO sum==+a(i) OD RETURN(sum)   PROC EquilibriumIndices(INT ARRAY a INT size INT ARRAY indices INT POINTER indSize) INT i,left,right   indSize^=0 FOR i=0 TO size-1 DO left=SumRange(a,0,i-1) right=SumRange(a,i+1,size-1) IF left=right THEN indices(indSize^)=i indSize^==+1 FI OD RETURN   PROC Test(INT ARRAY a INT size) INT ARRAY indices(100) INT indSize   EquilibriumIndices(a,size,indices,@indSize) Print("Array=") PrintArray(a,size) Print("Equilibrium indices=") PrintArray(indices,indSize) PutE() RETURN   PROC Main() INT ARRAY a=[65529 1 5 2 65532 3 0] INT ARRAY b=[65535 1 65535 1 65535 1 65535] INT ARRAY c=[1 2 3 4 5 6 7 8 9] INT ARRAY d=[0]   Test(a,7) Test(b,7) Test(c,9) Test(d,1) RETURN
http://rosettacode.org/wiki/Equilibrium_index
Equilibrium index
An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices. For example, in a sequence   A {\displaystyle A} :   A 0 = − 7 {\displaystyle A_{0}=-7}   A 1 = 1 {\displaystyle A_{1}=1}   A 2 = 5 {\displaystyle A_{2}=5}   A 3 = 2 {\displaystyle A_{3}=2}   A 4 = − 4 {\displaystyle A_{4}=-4}   A 5 = 3 {\displaystyle A_{5}=3}   A 6 = 0 {\displaystyle A_{6}=0} 3   is an equilibrium index, because:   A 0 + A 1 + A 2 = A 4 + A 5 + A 6 {\displaystyle A_{0}+A_{1}+A_{2}=A_{4}+A_{5}+A_{6}} 6   is also an equilibrium index, because:   A 0 + A 1 + A 2 + A 3 + A 4 + A 5 = 0 {\displaystyle A_{0}+A_{1}+A_{2}+A_{3}+A_{4}+A_{5}=0} (sum of zero elements is zero) 7   is not an equilibrium index, because it is not a valid index of sequence A {\displaystyle A} . Task; Write a function that, given a sequence, returns its equilibrium indices (if any). Assume that the sequence may be very long.
#Ada
Ada
with Ada.Containers.Vectors;   generic type Index_Type is range <>; type Element_Type is private; Zero : Element_Type; with function "+" (Left, Right : Element_Type) return Element_Type is <>; with function "-" (Left, Right : Element_Type) return Element_Type is <>; with function "=" (Left, Right : Element_Type) return Boolean is <>; type Array_Type is private; with function Element (From : Array_Type; Key : Index_Type) return Element_Type is <>; package Equilibrium is package Index_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Index_Type);   function Get_Indices (From : Array_Type) return Index_Vectors.Vector;   end Equilibrium;
http://rosettacode.org/wiki/Environment_variables
Environment variables
Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
#AppleScript
AppleScript
  tell application "Finder" to get name of home  
http://rosettacode.org/wiki/Environment_variables
Environment variables
Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
#Arturo
Arturo
print ["path:" env\PATH] print ["user:" env\USER] print ["home:" env\HOME]
http://rosettacode.org/wiki/Environment_variables
Environment variables
Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
#AutoHotkey
AutoHotkey
EnvGet, OutputVar, Path MsgBox, %OutputVar%
http://rosettacode.org/wiki/Esthetic_numbers
Esthetic numbers
An esthetic number is a positive integer where every adjacent digit differs from its neighbour by 1. E.G. 12 is an esthetic number. One and two differ by 1. 5654 is an esthetic number. Each digit is exactly 1 away from its neighbour. 890 is not an esthetic number. Nine and zero differ by 9. These examples are nominally in base 10 but the concept extends easily to numbers in other bases. Traditionally, single digit numbers are included in esthetic numbers; zero may or may not be. For our purposes, for this task, do not include zero (0) as an esthetic number. Do not include numbers with leading zeros. Esthetic numbers are also sometimes referred to as stepping numbers. Task Write a routine (function, procedure, whatever) to find esthetic numbers in a given base. Use that routine to find esthetic numbers in bases 2 through 16 and display, here on this page, the esthectic numbers from index (base × 4) through index (base × 6), inclusive. (E.G. for base 2: 8th through 12th, for base 6: 24th through 36th, etc.) Find and display, here on this page, the base 10 esthetic numbers with a magnitude between 1000 and 9999. Stretch: Find and display, here on this page, the base 10 esthetic numbers with a magnitude between 1.0e8 and 1.3e8. Related task   numbers with equal rises and falls See also OEIS A033075 - Positive numbers n such that all pairs of consecutive decimal digits differ by 1 Numbers Aplenty - Esthetic numbers Geeks for Geeks - Stepping numbers
#Java
Java
import java.util.ArrayList; import java.util.stream.IntStream; import java.util.stream.LongStream;   public class EstheticNumbers { interface RecTriConsumer<A, B, C> { void accept(RecTriConsumer<A, B, C> f, A a, B b, C c); }   private static boolean isEsthetic(long n, long b) { if (n == 0) { return false; } var i = n % b; var n2 = n / b; while (n2 > 0) { var j = n2 % b; if (Math.abs(i - j) != 1) { return false; } n2 /= b; i = j; } return true; }   private static void listEsths(long n, long n2, long m, long m2, int perLine, boolean all) { var esths = new ArrayList<Long>(); var dfs = new RecTriConsumer<Long, Long, Long>() { public void accept(Long n, Long m, Long i) { accept(this, n, m, i); }   @Override public void accept(RecTriConsumer<Long, Long, Long> f, Long n, Long m, Long i) { if (n <= i && i <= m) { esths.add(i); } if (i == 0 || i > m) { return; } var d = i % 10; var i1 = i * 10 + d - 1; var i2 = i1 + 2; if (d == 0) { f.accept(f, n, m, i2); } else if (d == 9) { f.accept(f, n, m, i1); } else { f.accept(f, n, m, i1); f.accept(f, n, m, i2); } } };   LongStream.range(0, 10).forEach(i -> dfs.accept(n2, m2, i));   var le = esths.size(); System.out.printf("Base 10: %d esthetic numbers between %d and %d:%n", le, n, m); if (all) { for (int i = 0; i < esths.size(); i++) { System.out.printf("%d ", esths.get(i)); if ((i + 1) % perLine == 0) { System.out.println(); } } } else { for (int i = 0; i < perLine; i++) { System.out.printf("%d ", esths.get(i)); } System.out.println(); System.out.println("............"); for (int i = le - perLine; i < le; i++) { System.out.printf("%d ", esths.get(i)); } } System.out.println(); System.out.println(); }   public static void main(String[] args) { IntStream.rangeClosed(2, 16).forEach(b -> { System.out.printf("Base %d: %dth to %dth esthetic numbers:%n", b, 4 * b, 6 * b); var n = 1L; var c = 0L; while (c < 6 * b) { if (isEsthetic(n, b)) { c++; if (c >= 4 * b) { System.out.printf("%s ", Long.toString(n, b)); } } n++; } System.out.println(); }); System.out.println();   // the following all use the obvious range limitations for the numbers in question listEsths(1000, 1010, 9999, 9898, 16, true); listEsths((long) 1e8, 101_010_101, 13 * (long) 1e7, 123_456_789, 9, true); listEsths((long) 1e11, 101_010_101_010L, 13 * (long) 1e10, 123_456_789_898L, 7, false); listEsths((long) 1e14, 101_010_101_010_101L, 13 * (long) 1e13, 123_456_789_898_989L, 5, false); listEsths((long) 1e17, 101_010_101_010_101_010L, 13 * (long) 1e16, 123_456_789_898_989_898L, 4, false); } }
http://rosettacode.org/wiki/Euler%27s_sum_of_powers_conjecture
Euler's sum of powers conjecture
There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin. Euler's (disproved) sum of powers   conjecture At least k positive kth powers are required to sum to a kth power, except for the trivial case of one kth power: yk = yk In 1966,   Leon J. Lander   and   Thomas R. Parkin   used a brute-force search on a   CDC 6600   computer restricting numbers to those less than 250. Task Write a program to search for an integer solution for: x05 + x15 + x25 + x35 == y5 Where all   xi's   and   y   are distinct integers between   0   and   250   (exclusive). Show an answer here. Related tasks   Pythagorean quadruples.   Pythagorean triples.
#BCPL
BCPL
  GET "libhdr"   LET solve() BE { LET pow5 = VEC 249 LET sum = ?   FOR i = 1 TO 249 pow5!i := i * i * i * i * i   FOR w = 4 TO 249 FOR x = 3 TO w - 1 FOR y = 2 TO x - 1 FOR z = 1 TO y - 1 { sum := pow5!w + pow5!x + pow5!y + pow5!z FOR a = w + 1 TO 249 IF pow5!a = sum { writef("solution found: %d  %d  %d  %d  %d *n", w, x, y, z, a) RETURN } } writef("Sorry, no solution found.*n") }   LET start() = VALOF { solve() RESULTIS 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
#min
min
((dup 0 ==) 'succ (dup pred) '* linrec) :factorial
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.
#AntLang
AntLang
odd: {x mod 2} even: {1 - x mod 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.
#APL
APL
2|28 0 2|37 1
http://rosettacode.org/wiki/Euler_method
Euler method
Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value.   It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page. The ODE has to be provided in the following form: d y ( t ) d t = f ( t , y ( t ) ) {\displaystyle {\frac {dy(t)}{dt}}=f(t,y(t))} with an initial value y ( t 0 ) = y 0 {\displaystyle y(t_{0})=y_{0}} To get a numeric solution, we replace the derivative on the   LHS   with a finite difference approximation: d y ( t ) d t ≈ y ( t + h ) − y ( t ) h {\displaystyle {\frac {dy(t)}{dt}}\approx {\frac {y(t+h)-y(t)}{h}}} then solve for y ( t + h ) {\displaystyle y(t+h)} : y ( t + h ) ≈ y ( t ) + h d y ( t ) d t {\displaystyle y(t+h)\approx y(t)+h\,{\frac {dy(t)}{dt}}} which is the same as y ( t + h ) ≈ y ( t ) + h f ( t , y ( t ) ) {\displaystyle y(t+h)\approx y(t)+h\,f(t,y(t))} The iterative solution rule is then: y n + 1 = y n + h f ( t n , y n ) {\displaystyle y_{n+1}=y_{n}+h\,f(t_{n},y_{n})} where   h {\displaystyle h}   is the step size, the most relevant parameter for accuracy of the solution.   A smaller step size increases accuracy but also the computation cost, so it has always has to be hand-picked according to the problem at hand. Example: Newton's Cooling Law Newton's cooling law describes how an object of initial temperature   T ( t 0 ) = T 0 {\displaystyle T(t_{0})=T_{0}}   cools down in an environment of temperature   T R {\displaystyle T_{R}} : d T ( t ) d t = − k Δ T {\displaystyle {\frac {dT(t)}{dt}}=-k\,\Delta T} or d T ( t ) d t = − k ( T ( t ) − T R ) {\displaystyle {\frac {dT(t)}{dt}}=-k\,(T(t)-T_{R})} It says that the cooling rate   d T ( t ) d t {\displaystyle {\frac {dT(t)}{dt}}}   of the object is proportional to the current temperature difference   Δ T = ( T ( t ) − T R ) {\displaystyle \Delta T=(T(t)-T_{R})}   to the surrounding environment. The analytical solution, which we will compare to the numerical approximation, is T ( t ) = T R + ( T 0 − T R ) e − k t {\displaystyle T(t)=T_{R}+(T_{0}-T_{R})\;e^{-kt}} Task Implement a routine of Euler's method and then to use it to solve the given example of Newton's cooling law with it for three different step sizes of:   2 s   5 s       and   10 s and to compare with the analytical solution. Initial values   initial temperature   T 0 {\displaystyle T_{0}}   shall be   100 °C   room temperature   T R {\displaystyle T_{R}}   shall be   20 °C   cooling constant     k {\displaystyle k}     shall be   0.07   time interval to calculate shall be from   0 s   ──►   100 s A reference solution (Common Lisp) can be seen below.   We see that bigger step sizes lead to reduced approximation accuracy.
#JavaScript
JavaScript
  // Function that takes differential-equation, initial condition, // ending x, and step size as parameters function eulersMethod(f, x1, y1, x2, h) { // Header console.log("\tX\t|\tY\t"); console.log("------------------------------------");   // Initial Variables var x=x1, y=y1;   // While we're not done yet // Both sides of the OR let you do Euler's Method backwards while ((x<x2 && x1<x2) || (x>x2 && x1>x2)) { // Print what we have console.log("\t" + x + "\t|\t" + y);   // Calculate the next values y += h*f(x, y) x += h; }   return y; }   function cooling(x, y) { return -0.07 * (y-20); }   eulersMethod(cooling, 0, 100, 100, 10);  
http://rosettacode.org/wiki/Evaluate_binomial_coefficients
Evaluate binomial coefficients
This programming task, is to calculate ANY binomial coefficient. However, it has to be able to output   ( 5 3 ) {\displaystyle {\binom {5}{3}}} ,   which is   10. This formula is recommended: ( n k ) = n ! ( n − k ) ! k ! = n ( n − 1 ) ( n − 2 ) … ( n − k + 1 ) k ( k − 1 ) ( k − 2 ) … 1 {\displaystyle {\binom {n}{k}}={\frac {n!}{(n-k)!k!}}={\frac {n(n-1)(n-2)\ldots (n-k+1)}{k(k-1)(k-2)\ldots 1}}} See Also: Combinations and permutations Pascal's triangle The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#C.2B.2B
C++
double Factorial(double nValue) { double result = nValue; double result_next; double pc = nValue; do { result_next = result*(pc-1); result = result_next; pc--; }while(pc>2); nValue = result; return nValue; }   double binomialCoefficient(double n, double k) { if (abs(n - k) < 1e-7 || k < 1e-7) return 1.0; if( abs(k-1.0) < 1e-7 || abs(k - (n-1)) < 1e-7)return n; return Factorial(n) /(Factorial(k)*Factorial((n - k))); }  
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: Fn = Fn+2 - Fn+1, if n<0 support for negative     n     in the solution is optional. Related tasks   Fibonacci n-step number sequences‎   Leonardo numbers References   Wikipedia, Fibonacci number   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#Visual_Basic
Visual Basic
Sub fibonacci() Const n = 139 Dim i As Integer Dim f1 As Variant, f2 As Variant, f3 As Variant 'for Decimal f1 = CDec(0): f2 = CDec(1) 'for Decimal setting Debug.Print "fibo("; 0; ")="; f1 Debug.Print "fibo("; 1; ")="; f2 For i = 2 To n f3 = f1 + f2 Debug.Print "fibo("; i; ")="; f3 f1 = f2 f2 = f3 Next i End Sub 'fibonacci
http://rosettacode.org/wiki/Entropy/Narcissist
Entropy/Narcissist
Task Write a computer program that computes and shows its own   entropy. Related Tasks   Fibonacci_word   Entropy
#AutoHotkey
AutoHotkey
FileRead, var, *C %A_ScriptFullPath% MsgBox, % Entropy(var)   Entropy(n) { a := [], len := StrLen(n), m := n while StrLen(m) { s := SubStr(m, 1, 1) m := RegExReplace(m, s, "", c) a[s] := c } for key, val in a { m := Log(p := val / len) e -= p * m / Log(2) } return, e }
http://rosettacode.org/wiki/Entropy/Narcissist
Entropy/Narcissist
Task Write a computer program that computes and shows its own   entropy. Related Tasks   Fibonacci_word   Entropy
#AWK
AWK
  BEGIN{FS="" RS="\x04"#EOF getline<"entropy.awk" for(i=1;i<=NF;i++)H[$i]++ for(i in H)E-=(h=H[i]/NF)*log(h) print "bytes ",NF," entropy ",E/log(2) exit}
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#11l
11l
T.enum TokenCategory NAME KEYWORD CONSTANT TEST_CATEGORY = 10
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
#Aime
Aime
void halve(integer &x) { x >>= 1; }   void double(integer &x) { x <<= 1; }   integer iseven(integer x) { return (x & 1) == 0; }   integer ethiopian(integer plier, integer plicand, integer tutor) { integer result;   result = 0;   if (tutor) { o_form("ethiopian multiplication of ~ by ~\n", plier, plicand); }   while (plier >= 1) { if (iseven(plier)) { if (tutor) { o_form("/w4/ /w6/ struck\n", plier, plicand); } } else { if (tutor) { o_form("/w4/ /w6/ kept\n", plier, plicand); }   result += plicand; }   halve(plier); double(plicand); }   return result; }   integer main(void) { o_integer(ethiopian(17, 34, 1)); o_byte('\n');   return 0; }
http://rosettacode.org/wiki/Equilibrium_index
Equilibrium index
An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices. For example, in a sequence   A {\displaystyle A} :   A 0 = − 7 {\displaystyle A_{0}=-7}   A 1 = 1 {\displaystyle A_{1}=1}   A 2 = 5 {\displaystyle A_{2}=5}   A 3 = 2 {\displaystyle A_{3}=2}   A 4 = − 4 {\displaystyle A_{4}=-4}   A 5 = 3 {\displaystyle A_{5}=3}   A 6 = 0 {\displaystyle A_{6}=0} 3   is an equilibrium index, because:   A 0 + A 1 + A 2 = A 4 + A 5 + A 6 {\displaystyle A_{0}+A_{1}+A_{2}=A_{4}+A_{5}+A_{6}} 6   is also an equilibrium index, because:   A 0 + A 1 + A 2 + A 3 + A 4 + A 5 = 0 {\displaystyle A_{0}+A_{1}+A_{2}+A_{3}+A_{4}+A_{5}=0} (sum of zero elements is zero) 7   is not an equilibrium index, because it is not a valid index of sequence A {\displaystyle A} . Task; Write a function that, given a sequence, returns its equilibrium indices (if any). Assume that the sequence may be very long.
#Aime
Aime
list eqindex(list l) { integer e, i, s, sum; list x;   s = sum = 0; l.ucall(add_i, 1, sum); for (i, e in l) { if (s * 2 + e == sum) { x.append(i); } s += e; }   x; }   integer main(void) { list(-7, 1, 5, 2, -4, 3, 0).eqindex.ucall(o_, 0, "\n");   0; }
http://rosettacode.org/wiki/Equilibrium_index
Equilibrium index
An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices. For example, in a sequence   A {\displaystyle A} :   A 0 = − 7 {\displaystyle A_{0}=-7}   A 1 = 1 {\displaystyle A_{1}=1}   A 2 = 5 {\displaystyle A_{2}=5}   A 3 = 2 {\displaystyle A_{3}=2}   A 4 = − 4 {\displaystyle A_{4}=-4}   A 5 = 3 {\displaystyle A_{5}=3}   A 6 = 0 {\displaystyle A_{6}=0} 3   is an equilibrium index, because:   A 0 + A 1 + A 2 = A 4 + A 5 + A 6 {\displaystyle A_{0}+A_{1}+A_{2}=A_{4}+A_{5}+A_{6}} 6   is also an equilibrium index, because:   A 0 + A 1 + A 2 + A 3 + A 4 + A 5 = 0 {\displaystyle A_{0}+A_{1}+A_{2}+A_{3}+A_{4}+A_{5}=0} (sum of zero elements is zero) 7   is not an equilibrium index, because it is not a valid index of sequence A {\displaystyle A} . Task; Write a function that, given a sequence, returns its equilibrium indices (if any). Assume that the sequence may be very long.
#ALGOL_68
ALGOL 68
MODE YIELDINT = PROC(INT)VOID;   PROC gen equilibrium index = ([]INT arr, YIELDINT yield)VOID: ( INT sum := 0; FOR i FROM LWB arr TO UPB arr DO sum +:= arr[i] OD;   INT left:=0, right:=sum; FOR i FROM LWB arr TO UPB arr DO right -:= arr[i]; IF left = right THEN yield(i) FI; left +:= arr[i] OD );   test:( []INT arr = []INT(-7, 1, 5, 2, -4, 3, 0)[@0]; # FOR INT index IN # gen equilibrium index(arr, # ) DO ( # ## (INT index)VOID: print(index) # OD # ); print(new line) )
http://rosettacode.org/wiki/Environment_variables
Environment variables
Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
#AutoIt
AutoIt
ConsoleWrite("# Environment:" & @CRLF)   Local $sEnvVar = EnvGet("LANG") ConsoleWrite("LANG : " & $sEnvVar & @CRLF)   ShowEnv("SystemDrive") ShowEnv("USERNAME")   Func ShowEnv($N) ConsoleWrite( StringFormat("%-12s : %s\n", $N, EnvGet($N)) ) EndFunc ;==>ShowEnv
http://rosettacode.org/wiki/Environment_variables
Environment variables
Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
#AWK
AWK
$ awk 'BEGIN{print "HOME:"ENVIRON["HOME"],"USER:"ENVIRON["USER"]}'
http://rosettacode.org/wiki/Environment_variables
Environment variables
Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
#BASIC
BASIC
x$ = ENVIRON$("path") PRINT x$
http://rosettacode.org/wiki/Esthetic_numbers
Esthetic numbers
An esthetic number is a positive integer where every adjacent digit differs from its neighbour by 1. E.G. 12 is an esthetic number. One and two differ by 1. 5654 is an esthetic number. Each digit is exactly 1 away from its neighbour. 890 is not an esthetic number. Nine and zero differ by 9. These examples are nominally in base 10 but the concept extends easily to numbers in other bases. Traditionally, single digit numbers are included in esthetic numbers; zero may or may not be. For our purposes, for this task, do not include zero (0) as an esthetic number. Do not include numbers with leading zeros. Esthetic numbers are also sometimes referred to as stepping numbers. Task Write a routine (function, procedure, whatever) to find esthetic numbers in a given base. Use that routine to find esthetic numbers in bases 2 through 16 and display, here on this page, the esthectic numbers from index (base × 4) through index (base × 6), inclusive. (E.G. for base 2: 8th through 12th, for base 6: 24th through 36th, etc.) Find and display, here on this page, the base 10 esthetic numbers with a magnitude between 1000 and 9999. Stretch: Find and display, here on this page, the base 10 esthetic numbers with a magnitude between 1.0e8 and 1.3e8. Related task   numbers with equal rises and falls See also OEIS A033075 - Positive numbers n such that all pairs of consecutive decimal digits differ by 1 Numbers Aplenty - Esthetic numbers Geeks for Geeks - Stepping numbers
#JavaScript
JavaScript
function isEsthetic(inp, base = 10) { let arr = inp.toString(base).split(''); if (arr.length == 1) return false; for (let i = 0; i < arr.length; i++) arr[i] = parseInt(arr[i], base); for (i = 0; i < arr.length-1; i++) if (Math.abs(arr[i]-arr[i+1]) !== 1) return false; return true; }   function collectEsthetics(base, range) { let out = [], x; if (range) { for (x = range[0]; x < range[1]; x++) if (isEsthetic(x)) out.push(x); return out; } else { x = 1; while (out.length < base*6) { s = x.toString(base); if (isEsthetic(s, base)) out.push(s.toUpperCase()); x++; } return out.slice(base*4); } }   // main let d = new Date(); for (let x = 2; x <= 36; x++) { // we put b17 .. b36 on top, because we can console.log(`${x}:`); console.log( collectEsthetics(x), (new Date() - d) / 1000 + ' s'); } console.log( collectEsthetics(10, [1000, 9999]), (new Date() - d) / 1000 + ' s' );   console.log( collectEsthetics(10, [1e8, 1.3e8]), (new Date() - d) / 1000 + ' s' );
http://rosettacode.org/wiki/Euler%27s_sum_of_powers_conjecture
Euler's sum of powers conjecture
There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin. Euler's (disproved) sum of powers   conjecture At least k positive kth powers are required to sum to a kth power, except for the trivial case of one kth power: yk = yk In 1966,   Leon J. Lander   and   Thomas R. Parkin   used a brute-force search on a   CDC 6600   computer restricting numbers to those less than 250. Task Write a program to search for an integer solution for: x05 + x15 + x25 + x35 == y5 Where all   xi's   and   y   are distinct integers between   0   and   250   (exclusive). Show an answer here. Related tasks   Pythagorean quadruples.   Pythagorean triples.
#Bracmat
Bracmat
0:?x0 & whl ' ( 1+!x0:<250:?x0 & out$(x0 !x0) & 0:?x1 & whl ' ( 1+!x1:~>!x0:?x1 & out$(x0 !x0 x1 !x1) & 0:?x2 & whl ' ( 1+!x2:~>!x1:?x2 & 0:?x3 & whl ' ( 1+!x3:~>!x2:?x3 & (!x0^5+!x1^5+!x2^5+!x3^5)^1/5  : ( #?y & out$(x0 !x0 x1 !x1 x2 !x2 x3 !x3 y !y) & 250:?x0:?x1:?x2:?x3 | ? ) ) ) ) )
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
#MiniScript
MiniScript
factorial = function(n) result = 1 for i in range(2,n) result = result * i end for return result end function   print factorial(10)
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.
#AppleScript
AppleScript
set L to {3, 2, 1, 0, -1, -2, -3}   set evens to {} set odds to {}   repeat with x in L if (x mod 2 = 0) then set the end of evens to x's contents else set the end of odds to x's contents end if end repeat   return {even:evens, odd:odds}
http://rosettacode.org/wiki/Euler_method
Euler method
Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value.   It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page. The ODE has to be provided in the following form: d y ( t ) d t = f ( t , y ( t ) ) {\displaystyle {\frac {dy(t)}{dt}}=f(t,y(t))} with an initial value y ( t 0 ) = y 0 {\displaystyle y(t_{0})=y_{0}} To get a numeric solution, we replace the derivative on the   LHS   with a finite difference approximation: d y ( t ) d t ≈ y ( t + h ) − y ( t ) h {\displaystyle {\frac {dy(t)}{dt}}\approx {\frac {y(t+h)-y(t)}{h}}} then solve for y ( t + h ) {\displaystyle y(t+h)} : y ( t + h ) ≈ y ( t ) + h d y ( t ) d t {\displaystyle y(t+h)\approx y(t)+h\,{\frac {dy(t)}{dt}}} which is the same as y ( t + h ) ≈ y ( t ) + h f ( t , y ( t ) ) {\displaystyle y(t+h)\approx y(t)+h\,f(t,y(t))} The iterative solution rule is then: y n + 1 = y n + h f ( t n , y n ) {\displaystyle y_{n+1}=y_{n}+h\,f(t_{n},y_{n})} where   h {\displaystyle h}   is the step size, the most relevant parameter for accuracy of the solution.   A smaller step size increases accuracy but also the computation cost, so it has always has to be hand-picked according to the problem at hand. Example: Newton's Cooling Law Newton's cooling law describes how an object of initial temperature   T ( t 0 ) = T 0 {\displaystyle T(t_{0})=T_{0}}   cools down in an environment of temperature   T R {\displaystyle T_{R}} : d T ( t ) d t = − k Δ T {\displaystyle {\frac {dT(t)}{dt}}=-k\,\Delta T} or d T ( t ) d t = − k ( T ( t ) − T R ) {\displaystyle {\frac {dT(t)}{dt}}=-k\,(T(t)-T_{R})} It says that the cooling rate   d T ( t ) d t {\displaystyle {\frac {dT(t)}{dt}}}   of the object is proportional to the current temperature difference   Δ T = ( T ( t ) − T R ) {\displaystyle \Delta T=(T(t)-T_{R})}   to the surrounding environment. The analytical solution, which we will compare to the numerical approximation, is T ( t ) = T R + ( T 0 − T R ) e − k t {\displaystyle T(t)=T_{R}+(T_{0}-T_{R})\;e^{-kt}} Task Implement a routine of Euler's method and then to use it to solve the given example of Newton's cooling law with it for three different step sizes of:   2 s   5 s       and   10 s and to compare with the analytical solution. Initial values   initial temperature   T 0 {\displaystyle T_{0}}   shall be   100 °C   room temperature   T R {\displaystyle T_{R}}   shall be   20 °C   cooling constant     k {\displaystyle k}     shall be   0.07   time interval to calculate shall be from   0 s   ──►   100 s A reference solution (Common Lisp) can be seen below.   We see that bigger step sizes lead to reduced approximation accuracy.
#jq
jq
# euler_method takes a filter (df), initial condition # (x1,y1), ending x (x2), and step size as parameters; # it emits the y values at each iteration. # df must take [x,y] as its input. def euler_method(df; x1; y1; x2; h): h as $h | [x1, y1] | recurse( if ((.[0] < x2 and x1 < x2) or (.[0] > x2 and x1 > x2)) then [ (.[0] + $h), (.[1] + $h*df) ] else empty end ) | .[1] ;     # We could now solve the task by writing for each step-size, $h # euler_method(-0.07 * (.[1]-20); 0; 100; 100; $h) # but for clarity, we shall define a function named "cooling":   # [x,y] is input def cooling: -0.07 * (.[1]-20);   # The following solves the task: # (2,5,10) | [., [ euler_method(cooling; 0; 100; 100; .) ] ]  
http://rosettacode.org/wiki/Euler_method
Euler method
Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value.   It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page. The ODE has to be provided in the following form: d y ( t ) d t = f ( t , y ( t ) ) {\displaystyle {\frac {dy(t)}{dt}}=f(t,y(t))} with an initial value y ( t 0 ) = y 0 {\displaystyle y(t_{0})=y_{0}} To get a numeric solution, we replace the derivative on the   LHS   with a finite difference approximation: d y ( t ) d t ≈ y ( t + h ) − y ( t ) h {\displaystyle {\frac {dy(t)}{dt}}\approx {\frac {y(t+h)-y(t)}{h}}} then solve for y ( t + h ) {\displaystyle y(t+h)} : y ( t + h ) ≈ y ( t ) + h d y ( t ) d t {\displaystyle y(t+h)\approx y(t)+h\,{\frac {dy(t)}{dt}}} which is the same as y ( t + h ) ≈ y ( t ) + h f ( t , y ( t ) ) {\displaystyle y(t+h)\approx y(t)+h\,f(t,y(t))} The iterative solution rule is then: y n + 1 = y n + h f ( t n , y n ) {\displaystyle y_{n+1}=y_{n}+h\,f(t_{n},y_{n})} where   h {\displaystyle h}   is the step size, the most relevant parameter for accuracy of the solution.   A smaller step size increases accuracy but also the computation cost, so it has always has to be hand-picked according to the problem at hand. Example: Newton's Cooling Law Newton's cooling law describes how an object of initial temperature   T ( t 0 ) = T 0 {\displaystyle T(t_{0})=T_{0}}   cools down in an environment of temperature   T R {\displaystyle T_{R}} : d T ( t ) d t = − k Δ T {\displaystyle {\frac {dT(t)}{dt}}=-k\,\Delta T} or d T ( t ) d t = − k ( T ( t ) − T R ) {\displaystyle {\frac {dT(t)}{dt}}=-k\,(T(t)-T_{R})} It says that the cooling rate   d T ( t ) d t {\displaystyle {\frac {dT(t)}{dt}}}   of the object is proportional to the current temperature difference   Δ T = ( T ( t ) − T R ) {\displaystyle \Delta T=(T(t)-T_{R})}   to the surrounding environment. The analytical solution, which we will compare to the numerical approximation, is T ( t ) = T R + ( T 0 − T R ) e − k t {\displaystyle T(t)=T_{R}+(T_{0}-T_{R})\;e^{-kt}} Task Implement a routine of Euler's method and then to use it to solve the given example of Newton's cooling law with it for three different step sizes of:   2 s   5 s       and   10 s and to compare with the analytical solution. Initial values   initial temperature   T 0 {\displaystyle T_{0}}   shall be   100 °C   room temperature   T R {\displaystyle T_{R}}   shall be   20 °C   cooling constant     k {\displaystyle k}     shall be   0.07   time interval to calculate shall be from   0 s   ──►   100 s A reference solution (Common Lisp) can be seen below.   We see that bigger step sizes lead to reduced approximation accuracy.
#Julia
Julia
euler(f::Function, T::Number, t0::Int, t1::Int, h::Int) = collect(begin T += h * f(T); T end for t in t0:h:t1)   # Prints a series of arbitrary values in a tabular form, left aligned in cells with a given width tabular(width, cells...) = println(join(map(s -> rpad(s, width), cells)))   # prints the table according to the task description for h=5 and 10 sec for h in (5, 10) print("Step $h:\n\n") tabular(15, "Time", "Euler", "Analytic") t = 0 for T in euler(y -> -0.07 * (y - 20.0), 100.0, 0, 100, h) tabular(15, t, round(T,digits=6), round(20.0 + 80.0 * exp(-0.07t), digits=6)) t += h end println() end
http://rosettacode.org/wiki/Evaluate_binomial_coefficients
Evaluate binomial coefficients
This programming task, is to calculate ANY binomial coefficient. However, it has to be able to output   ( 5 3 ) {\displaystyle {\binom {5}{3}}} ,   which is   10. This formula is recommended: ( n k ) = n ! ( n − k ) ! k ! = n ( n − 1 ) ( n − 2 ) … ( n − k + 1 ) k ( k − 1 ) ( k − 2 ) … 1 {\displaystyle {\binom {n}{k}}={\frac {n!}{(n-k)!k!}}={\frac {n(n-1)(n-2)\ldots (n-k+1)}{k(k-1)(k-2)\ldots 1}}} See Also: Combinations and permutations Pascal's triangle The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#Clojure
Clojure
(defn binomial-coefficient [n k] (let [rprod (fn [a b] (reduce * (range a (inc b))))] (/ (rprod (- n k -1) n) (rprod 1 k))))
http://rosettacode.org/wiki/Evaluate_binomial_coefficients
Evaluate binomial coefficients
This programming task, is to calculate ANY binomial coefficient. However, it has to be able to output   ( 5 3 ) {\displaystyle {\binom {5}{3}}} ,   which is   10. This formula is recommended: ( n k ) = n ! ( n − k ) ! k ! = n ( n − 1 ) ( n − 2 ) … ( n − k + 1 ) k ( k − 1 ) ( k − 2 ) … 1 {\displaystyle {\binom {n}{k}}={\frac {n!}{(n-k)!k!}}={\frac {n(n-1)(n-2)\ldots (n-k+1)}{k(k-1)(k-2)\ldots 1}}} See Also: Combinations and permutations Pascal's triangle The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#CoffeeScript
CoffeeScript
  binomial_coefficient = (n, k) -> result = 1 for i in [0...k] result *= (n - i) / (i + 1) result   n = 5 for k in [0..n] console.log "binomial_coefficient(#{n}, #{k}) = #{binomial_coefficient(n,k)}"  
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: Fn = Fn+2 - Fn+1, if n<0 support for negative     n     in the solution is optional. Related tasks   Fibonacci n-step number sequences‎   Leonardo numbers References   Wikipedia, Fibonacci number   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#Visual_Basic_.NET
Visual Basic .NET
Function Fib(ByVal n As Integer) As Decimal Dim fib0, fib1, sum As Decimal Dim i As Integer fib0 = 0 fib1 = 1 For i = 1 To n sum = fib0 + fib1 fib0 = fib1 fib1 = sum Next Fib = fib0 End Function
http://rosettacode.org/wiki/Entropy/Narcissist
Entropy/Narcissist
Task Write a computer program that computes and shows its own   entropy. Related Tasks   Fibonacci_word   Entropy
#C
C
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include <math.h>   #define MAXLEN 961 //maximum string length   int makehist(char *S,int *hist,int len){ int wherechar[256]; int i,histlen; histlen=0; for(i=0;i<256;i++)wherechar[i]=-1; for(i=0;i<len;i++){ if(wherechar[(int)S[i]]==-1){ wherechar[(int)S[i]]=histlen; histlen++; } hist[wherechar[(int)S[i]]]++; } return histlen; }   double entropy(int *hist,int histlen,int len){ int i; double H; H=0; for(i=0;i<histlen;i++){ H-=(double)hist[i]/len*log2((double)hist[i]/len); } return H; }   int main(void){ char S[MAXLEN]; int len,*hist,histlen; double H; FILE *f; f=fopen("entropy.c","r"); for(len=0;!feof(f);len++)S[len]=fgetc(f); S[--len]='\0'; hist=(int*)calloc(len,sizeof(int)); histlen=makehist(S,hist,len); //hist now has no order (known to the program) but that doesn't matter H=entropy(hist,histlen,len); printf("%lf\n",H); return 0; }
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#6502_Assembly
6502 Assembly
Sunday equ 0 Monday equ 1 Tuesday equ 2 Wednesday equ 3 Thursday equ 4 Friday equ 5 Saturday equ 6
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#68000_Assembly
68000 Assembly
Sunday equ 0 Monday equ 1 Tuesday equ 2 Wednesday equ 3 Thursday equ 4 Friday equ 5 Saturday equ 6
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#8086_Assembly
8086 Assembly
Sunday equ 0 Monday equ 1 Tuesday equ 2 Wednesday equ 3 Thursday equ 4 Friday equ 5 Saturday equ 6 Sunday equ 7
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
#ALGOL_68
ALGOL 68
PROC halve = (REF INT x)VOID: x := ABS(BIN x SHR 1); PROC doublit = (REF INT x)VOID: x := ABS(BIN x SHL 1); PROC iseven = (#CONST# INT x)BOOL: NOT ODD x;   PROC ethiopian = (INT in plier, INT in plicand, #CONST# BOOL tutor)INT: ( INT plier := in plier, plicand := in plicand; INT result:=0;   IF tutor THEN printf(($"ethiopian multiplication of "g(0)," by "g(0)l$, plier, plicand)) FI;   WHILE plier >= 1 DO IF iseven(plier) THEN IF tutor THEN printf(($" "4d," "6d" struck"l$, plier, plicand)) FI ELSE IF tutor THEN printf(($" "4d," "6d" kept"l$, plier, plicand)) FI; result +:= plicand FI; halve(plier); doublit(plicand) OD; result );   main: ( printf(($g(0)l$, ethiopian(17, 34, TRUE))) )
http://rosettacode.org/wiki/Equilibrium_index
Equilibrium index
An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices. For example, in a sequence   A {\displaystyle A} :   A 0 = − 7 {\displaystyle A_{0}=-7}   A 1 = 1 {\displaystyle A_{1}=1}   A 2 = 5 {\displaystyle A_{2}=5}   A 3 = 2 {\displaystyle A_{3}=2}   A 4 = − 4 {\displaystyle A_{4}=-4}   A 5 = 3 {\displaystyle A_{5}=3}   A 6 = 0 {\displaystyle A_{6}=0} 3   is an equilibrium index, because:   A 0 + A 1 + A 2 = A 4 + A 5 + A 6 {\displaystyle A_{0}+A_{1}+A_{2}=A_{4}+A_{5}+A_{6}} 6   is also an equilibrium index, because:   A 0 + A 1 + A 2 + A 3 + A 4 + A 5 = 0 {\displaystyle A_{0}+A_{1}+A_{2}+A_{3}+A_{4}+A_{5}=0} (sum of zero elements is zero) 7   is not an equilibrium index, because it is not a valid index of sequence A {\displaystyle A} . Task; Write a function that, given a sequence, returns its equilibrium indices (if any). Assume that the sequence may be very long.
#AppleScript
AppleScript
-- equilibriumIndices :: [Int] -> [Int] on equilibriumIndices(xs)   script balancedPair on |λ|(a, pair, i) set {x, y} to pair if x = y then {i - 1} & a else a end if end |λ| end script   script plus on |λ|(a, b) a + b end |λ| end script   -- Fold over zipped pairs of sums from left -- and sums from right   foldr(balancedPair, {}, ¬ zip(scanl1(plus, xs), scanr1(plus, xs)))   end equilibriumIndices   -- TEST ----------------------------------------------------------------------- on run   map(equilibriumIndices, {¬ {-7, 1, 5, 2, -4, 3, 0}, ¬ {2, 4, 6}, ¬ {2, 9, 2}, ¬ {1, -1, 1, -1, 1, -1, 1}, ¬ {1}, ¬ {}})   --> {{3, 6}, {}, {1}, {0, 1, 2, 3, 4, 5, 6}, {0}, {}} end run     -- GENERIC FUNCTIONS ----------------------------------------------------------   -- foldl :: (a -> b -> a) -> a -> [b] -> a on foldl(f, startValue, xs) tell mReturn(f) set v to startValue set lng to length of xs repeat with i from 1 to lng set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell end foldl   -- foldr :: (a -> b -> a) -> a -> [b] -> a on foldr(f, startValue, xs) tell mReturn(f) set v to startValue set lng to length of xs repeat with i from lng to 1 by -1 set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell end foldr   -- init :: [a] -> [a] on init(xs) set lng to length of xs if lng > 1 then items 1 thru -2 of xs else if lng > 0 then {} else missing value end if end init   -- map :: (a -> b) -> [a] -> [b] on map(f, xs) tell mReturn(f) set lng to length of xs set lst to {} repeat with i from 1 to lng set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell end map   -- min :: Ord a => a -> a -> a on min(x, y) if y < x then y else x end if end min   -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script on mReturn(f) if class of f is script then f else script property |λ| : f end script end if end mReturn   -- scanl :: (b -> a -> b) -> b -> [a] -> [b] on scanl(f, startValue, xs) tell mReturn(f) set v to startValue set lng to length of xs set lst to {startValue} repeat with i from 1 to lng set v to |λ|(v, item i of xs, i, xs) set end of lst to v end repeat return lst end tell end scanl   -- scanl1 :: (a -> a -> a) -> [a] -> [a] on scanl1(f, xs) if length of xs > 0 then scanl(f, item 1 of xs, tail(xs)) else {} end if end scanl1   -- scanr :: (b -> a -> b) -> b -> [a] -> [b] on scanr(f, startValue, xs) tell mReturn(f) set v to startValue set lng to length of xs set lst to {startValue} repeat with i from lng to 1 by -1 set v to |λ|(v, item i of xs, i, xs) set end of lst to v end repeat return reverse of lst end tell end scanr   -- scanr1 :: (a -> a -> a) -> [a] -> [a] on scanr1(f, xs) if length of xs > 0 then scanr(f, item -1 of xs, init(xs)) else {} end if end scanr1   -- tail :: [a] -> [a] on tail(xs) if length of xs > 1 then items 2 thru -1 of xs else {} end if end tail   -- zip :: [a] -> [b] -> [(a, b)] on zip(xs, ys) set lng to min(length of xs, length of ys) set lst to {} repeat with i from 1 to lng set end of lst to {item i of xs, item i of ys} end repeat return lst end zip
http://rosettacode.org/wiki/Environment_variables
Environment variables
Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
#Batch_File
Batch File
echo %Foo%
http://rosettacode.org/wiki/Environment_variables
Environment variables
Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
#BBC_BASIC
BBC BASIC
PRINT FNenvironment("PATH") PRINT FNenvironment("USERNAME") END   DEF FNenvironment(envar$) LOCAL buffer%, size% SYS "GetEnvironmentVariable", envar$, 0, 0 TO size% DIM buffer% LOCAL size% SYS "GetEnvironmentVariable", envar$, buffer%, size%+1 = $$buffer%
http://rosettacode.org/wiki/Environment_variables
Environment variables
Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
#C
C
#include <stdlib.h> #include <stdio.h>   int main() { puts(getenv("HOME")); puts(getenv("PATH")); puts(getenv("USER")); return 0; }  
http://rosettacode.org/wiki/Esthetic_numbers
Esthetic numbers
An esthetic number is a positive integer where every adjacent digit differs from its neighbour by 1. E.G. 12 is an esthetic number. One and two differ by 1. 5654 is an esthetic number. Each digit is exactly 1 away from its neighbour. 890 is not an esthetic number. Nine and zero differ by 9. These examples are nominally in base 10 but the concept extends easily to numbers in other bases. Traditionally, single digit numbers are included in esthetic numbers; zero may or may not be. For our purposes, for this task, do not include zero (0) as an esthetic number. Do not include numbers with leading zeros. Esthetic numbers are also sometimes referred to as stepping numbers. Task Write a routine (function, procedure, whatever) to find esthetic numbers in a given base. Use that routine to find esthetic numbers in bases 2 through 16 and display, here on this page, the esthectic numbers from index (base × 4) through index (base × 6), inclusive. (E.G. for base 2: 8th through 12th, for base 6: 24th through 36th, etc.) Find and display, here on this page, the base 10 esthetic numbers with a magnitude between 1000 and 9999. Stretch: Find and display, here on this page, the base 10 esthetic numbers with a magnitude between 1.0e8 and 1.3e8. Related task   numbers with equal rises and falls See also OEIS A033075 - Positive numbers n such that all pairs of consecutive decimal digits differ by 1 Numbers Aplenty - Esthetic numbers Geeks for Geeks - Stepping numbers
#Julia
Julia
using Formatting import Base.iterate, Base.IteratorSize, Base.IteratorEltype   """ struct Esthetic   Used for iteration of esthetic numbers """ struct Esthetic{T} lowerlimit::T where T <: Integer base::T upperlimit::T Esthetic{T}(n, bas, m=typemax(T)) where T = new{T}(nextesthetic(n, bas), bas, m) end   Base.IteratorSize(n::Esthetic) = Base.IsInfinite() Base.IteratorEltype(n::Esthetic) = Integer function Base.iterate(es::Esthetic, state=typeof(es.lowerlimit)[]) state = isempty(state) ? digits(es.lowerlimit, base=es.base) : increment!(state, es.base, 1) n = toInt(state, es.base) return n <= es.upperlimit ? (n, state) : nothing end   isesthetic(n, b) = (d = digits(n, base=b); all(i -> abs(d[i] - d[i + 1]) == 1, 1:length(d)-1)) toInt(dig, bas) = foldr((i, j) -> i + bas * j, dig) nextesthetic(n, b) = for i in n:typemax(typeof(n)) if isesthetic(i, b) return i end; end   """ Fill the digits below pos in vector with the least esthetic number fitting there """ function filldecreasing!(vec, pos) if pos > 1 n = vec[pos] for i in pos-1:-1:1 n = (n == 0) ? 1 : n - 1 vec[i] = n end end return vec end   """ Get the next esthetic number's digits from the previous number's digits """ function increment!(vec, bas, startpos = 1) len = length(vec) if len == 1 if vec[1] < bas - 1 vec[1] += 1 else vec[1] = 0 push!(vec, 1) end else pos = findfirst(i -> vec[i] < vec[i + 1], startpos:len-1) if pos == nothing if vec[end] >= bas - 1 push!(vec, 1) filldecreasing!(vec, len + 1) else vec[end] += 1 filldecreasing!(vec, len) end else for i in pos:len if i == len if vec[i] < bas - 1 vec[i] += 1 filldecreasing!(vec, i) else push!(vec, 1) filldecreasing!(vec, len + 1) end elseif vec[i] < vec[i + 1] && vec[i] < bas - 2 vec[i] += 2 filldecreasing!(vec, i) break end end end end return vec end   for b in 2:16 println("For base $b, the esthetic numbers indexed from $(4b) to $(6b) are:") printed = 0 for (i, n) in enumerate(Iterators.take(Esthetic{Int}(1, b), 6b)) if i >= 4b printed += 1 print(string(n, base=b), printed % 21 == 20 ? "\n" : " ") end end println("\n") end   for (bottom, top, cols, T) in [[1000, 9999, 16, Int], [100_000_000, 130_000_000, 8, Int], [101_010_000_000, 130_000_000_000, 6, Int], [101_010_101_010_000_000, 130_000_000_000_000_000, 4, Int], [101_010_101_010_101_000_000, 130_000_000_000_000_000_000, 4, Int128]] esth, count = Esthetic{T}(bottom, 10, top), 0 println("\nBase 10 esthetic numbers between $(format(bottom, commas=true)) and $(format(top, commas=true)):") for n in esth count += 1 if count == 64 println(" ...") elseif count < 64 print(format(n, commas=true), count % cols == 0 ? "\n" : " ") end end println("\nTotal esthetic numbers in interval: $count") end  
http://rosettacode.org/wiki/Euler%27s_sum_of_powers_conjecture
Euler's sum of powers conjecture
There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin. Euler's (disproved) sum of powers   conjecture At least k positive kth powers are required to sum to a kth power, except for the trivial case of one kth power: yk = yk In 1966,   Leon J. Lander   and   Thomas R. Parkin   used a brute-force search on a   CDC 6600   computer restricting numbers to those less than 250. Task Write a program to search for an integer solution for: x05 + x15 + x25 + x35 == y5 Where all   xi's   and   y   are distinct integers between   0   and   250   (exclusive). Show an answer here. Related tasks   Pythagorean quadruples.   Pythagorean triples.
#C
C
// Alexander Maximov, July 2nd, 2015 #include <stdio.h> #include <time.h> typedef long long mylong;   void compute(int N, char find_only_one_solution) { const int M = 30; /* x^5 == x modulo M=2*3*5 */ int a, b, c, d, e; mylong s, t, max, *p5 = (mylong*)malloc(sizeof(mylong)*(N+M));   for(s=0; s < N; ++s) p5[s] = s * s, p5[s] *= p5[s] * s; for(max = p5[N - 1]; s < (N + M); p5[s++] = max + 1);   for(a = 1; a < N; ++a) for(b = a + 1; b < N; ++b) for(c = b + 1; c < N; ++c) for(d = c + 1, e = d + ((t = p5[a] + p5[b] + p5[c]) % M); ((s = t + p5[d]) <= max); ++d, ++e) { for(e -= M; p5[e + M] <= s; e += M); /* jump over M=30 values for e>d */ if(p5[e] == s) { printf("%d %d %d %d %d\r\n", a, b, c, d, e); if(find_only_one_solution) goto onexit; } } onexit: free(p5); }   int main(void) { int tm = clock(); compute(250, 0); printf("time=%d milliseconds\r\n", (int)((clock() - tm) * 1000 / CLOCKS_PER_SEC)); return 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
#MiniZinc
MiniZinc
var int: factorial(int: n) = let { array[0..n] of var int: factorial; constraint forall(a in 0..n)( factorial[a] == if (a == 0) then 1 else a*factorial[a-1] endif )} in factorial[n];   var int: fac = factorial(6); solve satisfy; output [show(fac),"\n"];
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.
#Arendelle
Arendelle
( input , "Please enter a number: " ) { @input % 2 = 0 , "| @input | is even!" , "| @input | is odd!" }
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.
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI or android 32 bits */ /* program oddEven.s */   /* REMARK 1 : this program use routines in a include file see task Include a file language arm assembly for the routine affichageMess conversion10 see at end of this program the instruction include */ /* for constantes see task include a file in arm assembly */ /************************************/ /* Constantes */ /************************************/ .include "../constantes.inc"   /*********************************/ /* Initialized data */ /*********************************/ .data sMessResultOdd: .asciz " @ is odd (impair) \n" sMessResultEven: .asciz " @ is even (pair) \n" szCarriageReturn: .asciz "\n"   /*********************************/ /* UnInitialized data */ /*********************************/ .bss sZoneConv: .skip 24 /*********************************/ /* code section */ /*********************************/ .text .global main main: @ entry of program   mov r0,#5 bl testOddEven mov r0,#12 bl testOddEven mov r0,#2021 bl testOddEven 100: @ standard end of the program mov r0, #0 @ return code mov r7, #EXIT @ request to exit program svc #0 @ perform the system call   iAdrszCarriageReturn: .int szCarriageReturn iAdrsMessResultOdd: .int sMessResultOdd iAdrsMessResultEven: .int sMessResultEven iAdrsZoneConv: .int sZoneConv /***************************************************/ /* test if number is odd or even */ /***************************************************/ // r0 contains à number testOddEven: push {r2-r8,lr} @ save registers tst r0,#1 @ test bit 0 to one beq 1f @ if result are all zéro, go to even ldr r1,iAdrsZoneConv @ else display odd message bl conversion10 @ call decimal conversion ldr r0,iAdrsMessResultOdd ldr r1,iAdrsZoneConv @ insert value conversion in message bl strInsertAtCharInc bl affichageMess b 100f 1: ldr r1,iAdrsZoneConv bl conversion10 @ call decimal conversion ldr r0,iAdrsMessResultEven ldr r1,iAdrsZoneConv @ insert conversion in message bl strInsertAtCharInc bl affichageMess 100: pop {r2-r8,lr} @ restaur registers bx lr @ return /***************************************************/ /* ROUTINES INCLUDE */ /***************************************************/ .include "../affichage.inc"  
http://rosettacode.org/wiki/Euler_method
Euler method
Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value.   It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page. The ODE has to be provided in the following form: d y ( t ) d t = f ( t , y ( t ) ) {\displaystyle {\frac {dy(t)}{dt}}=f(t,y(t))} with an initial value y ( t 0 ) = y 0 {\displaystyle y(t_{0})=y_{0}} To get a numeric solution, we replace the derivative on the   LHS   with a finite difference approximation: d y ( t ) d t ≈ y ( t + h ) − y ( t ) h {\displaystyle {\frac {dy(t)}{dt}}\approx {\frac {y(t+h)-y(t)}{h}}} then solve for y ( t + h ) {\displaystyle y(t+h)} : y ( t + h ) ≈ y ( t ) + h d y ( t ) d t {\displaystyle y(t+h)\approx y(t)+h\,{\frac {dy(t)}{dt}}} which is the same as y ( t + h ) ≈ y ( t ) + h f ( t , y ( t ) ) {\displaystyle y(t+h)\approx y(t)+h\,f(t,y(t))} The iterative solution rule is then: y n + 1 = y n + h f ( t n , y n ) {\displaystyle y_{n+1}=y_{n}+h\,f(t_{n},y_{n})} where   h {\displaystyle h}   is the step size, the most relevant parameter for accuracy of the solution.   A smaller step size increases accuracy but also the computation cost, so it has always has to be hand-picked according to the problem at hand. Example: Newton's Cooling Law Newton's cooling law describes how an object of initial temperature   T ( t 0 ) = T 0 {\displaystyle T(t_{0})=T_{0}}   cools down in an environment of temperature   T R {\displaystyle T_{R}} : d T ( t ) d t = − k Δ T {\displaystyle {\frac {dT(t)}{dt}}=-k\,\Delta T} or d T ( t ) d t = − k ( T ( t ) − T R ) {\displaystyle {\frac {dT(t)}{dt}}=-k\,(T(t)-T_{R})} It says that the cooling rate   d T ( t ) d t {\displaystyle {\frac {dT(t)}{dt}}}   of the object is proportional to the current temperature difference   Δ T = ( T ( t ) − T R ) {\displaystyle \Delta T=(T(t)-T_{R})}   to the surrounding environment. The analytical solution, which we will compare to the numerical approximation, is T ( t ) = T R + ( T 0 − T R ) e − k t {\displaystyle T(t)=T_{R}+(T_{0}-T_{R})\;e^{-kt}} Task Implement a routine of Euler's method and then to use it to solve the given example of Newton's cooling law with it for three different step sizes of:   2 s   5 s       and   10 s and to compare with the analytical solution. Initial values   initial temperature   T 0 {\displaystyle T_{0}}   shall be   100 °C   room temperature   T R {\displaystyle T_{R}}   shall be   20 °C   cooling constant     k {\displaystyle k}     shall be   0.07   time interval to calculate shall be from   0 s   ──►   100 s A reference solution (Common Lisp) can be seen below.   We see that bigger step sizes lead to reduced approximation accuracy.
#Kotlin
Kotlin
// version 1.1.2   typealias Deriv = (Double) -> Double // only one parameter needed here   const val FMT = " %7.3f"   fun euler(f: Deriv, y: Double, step: Int, end: Int) { var yy = y print(" Step %2d: ".format(step)) for (t in 0..end step step) { if (t % 10 == 0) print(FMT.format(yy)) yy += step * f(yy) } println() }   fun analytic() { print(" Time: ") for (t in 0..100 step 10) print(" %7d".format(t)) print("\nAnalytic: ") for (t in 0..100 step 10) print(FMT.format(20.0 + 80.0 * Math.exp(-0.07 * t))) println() }   fun cooling(temp: Double) = -0.07 * (temp - 20.0)   fun main(args: Array<String>) { analytic() for (i in listOf(2, 5, 10)) euler(::cooling, 100.0, i, 100) }
http://rosettacode.org/wiki/Evaluate_binomial_coefficients
Evaluate binomial coefficients
This programming task, is to calculate ANY binomial coefficient. However, it has to be able to output   ( 5 3 ) {\displaystyle {\binom {5}{3}}} ,   which is   10. This formula is recommended: ( n k ) = n ! ( n − k ) ! k ! = n ( n − 1 ) ( n − 2 ) … ( n − k + 1 ) k ( k − 1 ) ( k − 2 ) … 1 {\displaystyle {\binom {n}{k}}={\frac {n!}{(n-k)!k!}}={\frac {n(n-1)(n-2)\ldots (n-k+1)}{k(k-1)(k-2)\ldots 1}}} See Also: Combinations and permutations Pascal's triangle The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#Commodore_BASIC
Commodore BASIC
  10 REM BINOMIAL COEFFICIENTS 20 REM COMMODORE BASIC 2.0 30 REM 2021-08-24 40 REM BY ALVALONGO 100 Z=0:U=1 110 FOR N=U TO 10 120 PRINT N; 130 FOR K=Z TO N 140 GOSUB 900 150 PRINT C; 160 NEXT K 170 PRINT 180 NEXT N 190 END 900 REM BINOMIAL COEFFICIENT 910 IF K<Z OR K>N THEN C=Z:RETURN 920 IF K=Z OR K=N THEN C=U:RETURN 930 P=K:IF N-K<P THEN P=N-K 940 C=U 950 FOR I=Z TO P-U 960 C=C/(I+U)*(N-I) 980 NEXT I 990 RETURN  
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: Fn = Fn+2 - Fn+1, if n<0 support for negative     n     in the solution is optional. Related tasks   Fibonacci n-step number sequences‎   Leonardo numbers References   Wikipedia, Fibonacci number   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#Vlang
Vlang
fn fib_iter(n int) int { if n < 2 { return n }   mut prev, mut fib := 0, 1 for _ in 0..(n - 1){ prev, fib = fib, prev + fib } return fib }   fn main() { for val in 0..11 { println('fibonacci(${val:2d}) = ${fib_iter(val):3d}') } }
http://rosettacode.org/wiki/Entropy/Narcissist
Entropy/Narcissist
Task Write a computer program that computes and shows its own   entropy. Related Tasks   Fibonacci_word   Entropy
#C.2B.2B
C++
#include <iostream> #include <fstream> #include <cmath>   using namespace std;   string readFile (string path) { string contents; string line; ifstream inFile(path); while (getline (inFile, line)) { contents.append(line); contents.append("\n"); } inFile.close(); return contents; }   double entropy (string X) { const int MAXCHAR = 127; int N = X.length(); int count[MAXCHAR]; double count_i; char ch; double sum = 0.0; for (int i = 0; i < MAXCHAR; i++) count[i] = 0; for (int pos = 0; pos < N; pos++) { ch = X[pos]; count[(int)ch]++; } for (int n_i = 0; n_i < MAXCHAR; n_i++) { count_i = count[n_i]; if (count_i > 0) sum -= count_i / N * log2(count_i / N); } return sum; }   int main () { cout<<entropy(readFile("entropy.cpp")); return 0; }
http://rosettacode.org/wiki/Entropy/Narcissist
Entropy/Narcissist
Task Write a computer program that computes and shows its own   entropy. Related Tasks   Fibonacci_word   Entropy
#Crystal
Crystal
def entropy(s) counts = s.chars.each_with_object(Hash(Char, Float64).new(0.0)) { |c, h| h[c] += 1 } counts.values.sum do |count| freq = count / s.size -freq * Math.log2(freq) end end   puts entropy File.read(__FILE__)
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#ACL2
ACL2
(defun symbol-to-constant (sym) (intern (concatenate 'string "*" (symbol-name sym) "*") "ACL2"))   (defmacro enum-with-vals (symbol value &rest args) (if (endp args) `(defconst ,(symbol-to-constant symbol) ,value) `(progn (defconst ,(symbol-to-constant symbol) ,value) (enum-with-vals ,@args))))   (defun interleave-with-nats-r (xs i) (if (endp xs) nil (cons (first xs) (cons i (interleave-with-nats-r (rest xs) (1+ i))))))   (defun interleave-with-nats (xs) (interleave-with-nats-r xs 0))   (defmacro enum (&rest symbols) `(enum-with-vals ,@(interleave-with-nats symbols)))
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#Ada
Ada
type Fruit is (apple, banana, cherry); -- No specification of the representation value; for Fruit use (apple => 1, banana => 2, cherry => 4); -- specification of the representation values
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
#ALGOL-M
ALGOL-M
  BEGIN   INTEGER FUNCTION HALF(I); INTEGER I; BEGIN HALF := I / 2; END;   INTEGER FUNCTION DOUBLE(I); INTEGER I; BEGIN DOUBLE := I + I; END;   % RETURN 1 IF EVEN, OTHERWISE 0 % INTEGER FUNCTION EVEN(I); INTEGER I; BEGIN EVEN := 1 - (I - 2 * (I / 2)); END;   % RETURN I * J AND OPTIONALLY SHOW COMPUTATIONAL STEPS % INTEGER FUNCTION ETHIOPIAN(I, J, SHOW); INTEGER I, J, SHOW; BEGIN INTEGER P, YES; YES := 1; P := 0; WHILE I >= 1 DO BEGIN IF EVEN(I) = YES THEN BEGIN IF SHOW = YES THEN WRITE(I," ----", J); END ELSE BEGIN IF SHOW = YES THEN WRITE(I,J); P := P + J; END; I := HALF(I); J := DOUBLE(J); END; IF SHOW = YES THEN WRITE(" ="); ETHIOPIAN := P; END;   % EXERCISE THE FUNCTION % INTEGER YES; YES := 1; WRITE(ETHIOPIAN(17,34,YES));   END
http://rosettacode.org/wiki/Equilibrium_index
Equilibrium index
An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices. For example, in a sequence   A {\displaystyle A} :   A 0 = − 7 {\displaystyle A_{0}=-7}   A 1 = 1 {\displaystyle A_{1}=1}   A 2 = 5 {\displaystyle A_{2}=5}   A 3 = 2 {\displaystyle A_{3}=2}   A 4 = − 4 {\displaystyle A_{4}=-4}   A 5 = 3 {\displaystyle A_{5}=3}   A 6 = 0 {\displaystyle A_{6}=0} 3   is an equilibrium index, because:   A 0 + A 1 + A 2 = A 4 + A 5 + A 6 {\displaystyle A_{0}+A_{1}+A_{2}=A_{4}+A_{5}+A_{6}} 6   is also an equilibrium index, because:   A 0 + A 1 + A 2 + A 3 + A 4 + A 5 = 0 {\displaystyle A_{0}+A_{1}+A_{2}+A_{3}+A_{4}+A_{5}=0} (sum of zero elements is zero) 7   is not an equilibrium index, because it is not a valid index of sequence A {\displaystyle A} . Task; Write a function that, given a sequence, returns its equilibrium indices (if any). Assume that the sequence may be very long.
#Arturo
Arturo
eqIndex: function [row][ suml: 0 delayed: 0 sumr: sum row result: new [] loop.with:'i row 'r [ suml: suml + delayed sumr: sumr - r delayed: r if suml = sumr -> 'result ++ i ] return result ]   data: @[ @[neg 7, 1, 5, 2, neg 4, 3, 0] @[2 4 6] @[2 9 2] @[1 neg 1 1 neg 1 1 neg 1 1] ]   loop data 'd -> print [pad.right join.with:", " to [:string] d 25 "=> equilibrium index:" eqIndex d]
http://rosettacode.org/wiki/Environment_variables
Environment variables
Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
#C.23
C#
using System;   namespace RosettaCode { class Program { static void Main() { string temp = Environment.GetEnvironmentVariable("TEMP"); Console.WriteLine("TEMP is " + temp); } } }
http://rosettacode.org/wiki/Environment_variables
Environment variables
Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
#C.2B.2B
C++
#include <cstdlib> #include <cstdio>   int main() { puts(getenv("HOME")); return 0; }
http://rosettacode.org/wiki/Environment_variables
Environment variables
Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
#Clojure
Clojure
(System/getenv "HOME")
http://rosettacode.org/wiki/Esthetic_numbers
Esthetic numbers
An esthetic number is a positive integer where every adjacent digit differs from its neighbour by 1. E.G. 12 is an esthetic number. One and two differ by 1. 5654 is an esthetic number. Each digit is exactly 1 away from its neighbour. 890 is not an esthetic number. Nine and zero differ by 9. These examples are nominally in base 10 but the concept extends easily to numbers in other bases. Traditionally, single digit numbers are included in esthetic numbers; zero may or may not be. For our purposes, for this task, do not include zero (0) as an esthetic number. Do not include numbers with leading zeros. Esthetic numbers are also sometimes referred to as stepping numbers. Task Write a routine (function, procedure, whatever) to find esthetic numbers in a given base. Use that routine to find esthetic numbers in bases 2 through 16 and display, here on this page, the esthectic numbers from index (base × 4) through index (base × 6), inclusive. (E.G. for base 2: 8th through 12th, for base 6: 24th through 36th, etc.) Find and display, here on this page, the base 10 esthetic numbers with a magnitude between 1000 and 9999. Stretch: Find and display, here on this page, the base 10 esthetic numbers with a magnitude between 1.0e8 and 1.3e8. Related task   numbers with equal rises and falls See also OEIS A033075 - Positive numbers n such that all pairs of consecutive decimal digits differ by 1 Numbers Aplenty - Esthetic numbers Geeks for Geeks - Stepping numbers
#Kotlin
Kotlin
import kotlin.math.abs   fun isEsthetic(n: Long, b: Long): Boolean { if (n == 0L) { return false } var i = n % b var n2 = n / b while (n2 > 0) { val j = n2 % b if (abs(i - j) != 1L) { return false } n2 /= b i = j } return true }   fun listEsths(n: Long, n2: Long, m: Long, m2: Long, perLine: Int, all: Boolean) { val esths = mutableListOf<Long>() fun dfs(n: Long, m: Long, i: Long) { if (i in n..m) { esths.add(i) } if (i == 0L || i > m) { return } val d = i % 10 val i1 = i * 10 + d - 1 val i2 = i1 + 2 when (d) { 0L -> { dfs(n, m, i2) } 9L -> { dfs(n, m, i1) } else -> { dfs(n, m, i1) dfs(n, m, i2) } } }   for (i in 0L until 10L) { dfs(n2, m2, i) }   val le = esths.size println("Base 10: $le esthetic numbers between $n and $m:") if (all) { for (c_esth in esths.withIndex()) { print("${c_esth.value} ") if ((c_esth.index + 1) % perLine == 0) { println() } } println() } else { for (i in 0 until perLine) { print("${esths[i]} ") } println() println("............") for (i in le - perLine until le) { print("${esths[i]} ") } println() } println() }   fun main() { for (b in 2..16) { println("Base $b: ${4 * b}th to ${6 * b}th esthetic numbers:") var n = 1L var c = 0L while (c < 6 * b) { if (isEsthetic(n, b.toLong())) { c++ if (c >= 4 * b) { print("${n.toString(b)} ") } } n++ } println() } println()   // the following all use the obvious range limitations for the numbers in question listEsths(1000, 1010, 9999, 9898, 16, true); listEsths(1e8.toLong(), 101_010_101, 13 * 1e7.toLong(), 123_456_789, 9, true); listEsths(1e11.toLong(), 101_010_101_010, 13 * 1e10.toLong(), 123_456_789_898, 7, false); listEsths(1e14.toLong(), 101_010_101_010_101, 13 * 1e13.toLong(), 123_456_789_898_989, 5, false); listEsths(1e17.toLong(), 101_010_101_010_101_010, 13 * 1e16.toLong(), 123_456_789_898_989_898, 4, false); }
http://rosettacode.org/wiki/Euler%27s_sum_of_powers_conjecture
Euler's sum of powers conjecture
There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin. Euler's (disproved) sum of powers   conjecture At least k positive kth powers are required to sum to a kth power, except for the trivial case of one kth power: yk = yk In 1966,   Leon J. Lander   and   Thomas R. Parkin   used a brute-force search on a   CDC 6600   computer restricting numbers to those less than 250. Task Write a program to search for an integer solution for: x05 + x15 + x25 + x35 == y5 Where all   xi's   and   y   are distinct integers between   0   and   250   (exclusive). Show an answer here. Related tasks   Pythagorean quadruples.   Pythagorean triples.
#C.23
C#
using System;   namespace EulerSumOfPowers { class Program { const int MAX_NUMBER = 250;   static void Main(string[] args) { bool found = false; long[] fifth = new long[MAX_NUMBER];   for (int i = 1; i <= MAX_NUMBER; i++) { long i2 = i * i; fifth[i - 1] = i2 * i2 * i; }   for (int a = 0; a < MAX_NUMBER && !found; a++) { for (int b = a; b < MAX_NUMBER && !found; b++) { for (int c = b; c < MAX_NUMBER && !found; c++) { for (int d = c; d < MAX_NUMBER && !found; d++) { long sum = fifth[a] + fifth[b] + fifth[c] + fifth[d]; int e = Array.BinarySearch(fifth, sum); found = e >= 0; if (found) { Console.WriteLine("{0}^5 + {1}^5 + {2}^5 + {3}^5 = {4}^5", a + 1, b + 1, c + 1, d + 1, e + 1); } } } } } } } }
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
#MIPS_Assembly
MIPS Assembly
  ################################## # Factorial; iterative # # By Keith Stellyes :) # # Targets Mars implementation # # August 24, 2016 # ##################################   # This example reads an integer from user, stores in register a1 # Then, it uses a0 as a multiplier and target, it is set to 1   # Pseudocode: # a0 = 1 # a1 = read_int_from_user() # while(a1 > 1) # { # a0 = a0*a1 # DECREMENT a1 # } # print(a0)   .text ### PROGRAM BEGIN ### ### GET INTEGER FROM USER ### li $v0, 5 #set syscall arg to READ_INTEGER syscall #make the syscall move $a1, $v0 #int from READ_INTEGER is returned in $v0, but we need $v0 #this will be used as a counter   ### SET $a1 TO INITAL VALUE OF 1 AS MULTIPLIER ### li $a0,1   ### Multiply our multiplier, $a1 by our counter, $a0 then store in $a1 ### loop: ble $a1,1,exit # If the counter is greater than 1, go back to start mul $a0,$a0,$a1 #a1 = a1*a0   subi $a1,$a1,1 # Decrement counter   j loop # Go back to start   exit: ### PRINT RESULT ### li $v0,1 #set syscall arg to PRINT_INTEGER #NOTE: syscall 1 (PRINT_INTEGER) takes a0 as its argument. Conveniently, that # is our result. syscall #make the syscall   #exit li $v0, 10 #set syscall arg to EXIT syscall #make the syscall  
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.
#ArnoldC
ArnoldC
LISTEN TO ME VERY CAREFULLY isOdd I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE n GIVE THESE PEOPLE AIR HEY CHRISTMAS TREE result YOU SET US UP @I LIED GET TO THE CHOPPER result HERE IS MY INVITATION n I LET HIM GO 2 ENOUGH TALK I'LL BE BACK result HASTA LA VISTA, BABY   LISTEN TO ME VERY CAREFULLY showParity I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE n TALK TO THE HAND n HEY CHRISTMAS TREE parity YOU SET US UP @I LIED GET YOUR A** TO MARS parity DO IT NOW isOdd n BECAUSE I'M GOING TO SAY PLEASE parity TALK TO THE HAND "odd" BULLS*** TALK TO THE HAND "even" YOU HAVE NO RESPECT FOR LOGIC TALK TO THE HAND "" HASTA LA VISTA, BABY   IT'S SHOWTIME DO IT NOW showParity 5 DO IT NOW showParity 6 DO IT NOW showParity -11 YOU HAVE BEEN TERMINATED
http://rosettacode.org/wiki/Euler_method
Euler method
Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value.   It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page. The ODE has to be provided in the following form: d y ( t ) d t = f ( t , y ( t ) ) {\displaystyle {\frac {dy(t)}{dt}}=f(t,y(t))} with an initial value y ( t 0 ) = y 0 {\displaystyle y(t_{0})=y_{0}} To get a numeric solution, we replace the derivative on the   LHS   with a finite difference approximation: d y ( t ) d t ≈ y ( t + h ) − y ( t ) h {\displaystyle {\frac {dy(t)}{dt}}\approx {\frac {y(t+h)-y(t)}{h}}} then solve for y ( t + h ) {\displaystyle y(t+h)} : y ( t + h ) ≈ y ( t ) + h d y ( t ) d t {\displaystyle y(t+h)\approx y(t)+h\,{\frac {dy(t)}{dt}}} which is the same as y ( t + h ) ≈ y ( t ) + h f ( t , y ( t ) ) {\displaystyle y(t+h)\approx y(t)+h\,f(t,y(t))} The iterative solution rule is then: y n + 1 = y n + h f ( t n , y n ) {\displaystyle y_{n+1}=y_{n}+h\,f(t_{n},y_{n})} where   h {\displaystyle h}   is the step size, the most relevant parameter for accuracy of the solution.   A smaller step size increases accuracy but also the computation cost, so it has always has to be hand-picked according to the problem at hand. Example: Newton's Cooling Law Newton's cooling law describes how an object of initial temperature   T ( t 0 ) = T 0 {\displaystyle T(t_{0})=T_{0}}   cools down in an environment of temperature   T R {\displaystyle T_{R}} : d T ( t ) d t = − k Δ T {\displaystyle {\frac {dT(t)}{dt}}=-k\,\Delta T} or d T ( t ) d t = − k ( T ( t ) − T R ) {\displaystyle {\frac {dT(t)}{dt}}=-k\,(T(t)-T_{R})} It says that the cooling rate   d T ( t ) d t {\displaystyle {\frac {dT(t)}{dt}}}   of the object is proportional to the current temperature difference   Δ T = ( T ( t ) − T R ) {\displaystyle \Delta T=(T(t)-T_{R})}   to the surrounding environment. The analytical solution, which we will compare to the numerical approximation, is T ( t ) = T R + ( T 0 − T R ) e − k t {\displaystyle T(t)=T_{R}+(T_{0}-T_{R})\;e^{-kt}} Task Implement a routine of Euler's method and then to use it to solve the given example of Newton's cooling law with it for three different step sizes of:   2 s   5 s       and   10 s and to compare with the analytical solution. Initial values   initial temperature   T 0 {\displaystyle T_{0}}   shall be   100 °C   room temperature   T R {\displaystyle T_{R}}   shall be   20 °C   cooling constant     k {\displaystyle k}     shall be   0.07   time interval to calculate shall be from   0 s   ──►   100 s A reference solution (Common Lisp) can be seen below.   We see that bigger step sizes lead to reduced approximation accuracy.
#Lambdatalk
Lambdatalk
  {def eulersMethod {def eulersMethod.r {lambda {:f :b :h :t :y} {if {<= :t :b} then {tr {td :t} {td {/ {round {* :y 1000}} 1000}}} {eulersMethod.r :f :b :h {+ :t :h} {+ :y {* :h {:f :t :y}}}} else}}} {lambda {:f :y0 :a :b :h} {table {eulersMethod.r :f :b :h :a :y0}}}}   {def cooling {lambda {:time :temp} {* -0.07 {- :temp 20}}}}   {eulersMethod cooling 100 0 100 10} -> 0 100 10 44 20 27.2 30 22.16 40 20.648 50 20.194 60 20.058 70 20.017 80 20.005 90 20.002 100 20  
http://rosettacode.org/wiki/Evaluate_binomial_coefficients
Evaluate binomial coefficients
This programming task, is to calculate ANY binomial coefficient. However, it has to be able to output   ( 5 3 ) {\displaystyle {\binom {5}{3}}} ,   which is   10. This formula is recommended: ( n k ) = n ! ( n − k ) ! k ! = n ( n − 1 ) ( n − 2 ) … ( n − k + 1 ) k ( k − 1 ) ( k − 2 ) … 1 {\displaystyle {\binom {n}{k}}={\frac {n!}{(n-k)!k!}}={\frac {n(n-1)(n-2)\ldots (n-k+1)}{k(k-1)(k-2)\ldots 1}}} See Also: Combinations and permutations Pascal's triangle The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#Common_Lisp
Common Lisp
  (defun choose (n k) (labels ((prod-enum (s e) (do ((i s (1+ i)) (r 1 (* i r))) ((> i e) r))) (fact (n) (prod-enum 1 n))) (/ (prod-enum (- (1+ n) k) n) (fact k))))  
http://rosettacode.org/wiki/Evaluate_binomial_coefficients
Evaluate binomial coefficients
This programming task, is to calculate ANY binomial coefficient. However, it has to be able to output   ( 5 3 ) {\displaystyle {\binom {5}{3}}} ,   which is   10. This formula is recommended: ( n k ) = n ! ( n − k ) ! k ! = n ( n − 1 ) ( n − 2 ) … ( n − k + 1 ) k ( k − 1 ) ( k − 2 ) … 1 {\displaystyle {\binom {n}{k}}={\frac {n!}{(n-k)!k!}}={\frac {n(n-1)(n-2)\ldots (n-k+1)}{k(k-1)(k-2)\ldots 1}}} See Also: Combinations and permutations Pascal's triangle The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#D
D
T binomial(T)(in T n, T k) pure nothrow { if (k > (n / 2)) k = n - k; T bc = 1; foreach (T i; T(2) .. k + 1) bc = (bc * (n - k + i)) / i; return bc; }   void main() { import std.stdio, std.bigint;   foreach (const d; [[5, 3], [100, 2], [100, 98]]) writefln("(%3d %3d) = %s", d[0], d[1], binomial(d[0], d[1])); writeln("(100 50) = ", binomial(100.BigInt, 50.BigInt)); }
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: Fn = Fn+2 - Fn+1, if n<0 support for negative     n     in the solution is optional. Related tasks   Fibonacci n-step number sequences‎   Leonardo numbers References   Wikipedia, Fibonacci number   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#Wart
Wart
def (fib n) if (n < 2) n (+ (fib n-1) (fib n-2))
http://rosettacode.org/wiki/Entropy/Narcissist
Entropy/Narcissist
Task Write a computer program that computes and shows its own   entropy. Related Tasks   Fibonacci_word   Entropy
#D
D
void main(in string[] args) { import std.stdio, std.algorithm, std.math, std.file;   auto data = sort(cast(ubyte[])args[0].read); return data .group .map!(g => g[1] / double(data.length)) .map!(p => -p * p.log2) .sum .writeln; }
http://rosettacode.org/wiki/Entropy/Narcissist
Entropy/Narcissist
Task Write a computer program that computes and shows its own   entropy. Related Tasks   Fibonacci_word   Entropy
#Elixir
Elixir
File.open(__ENV__.file, [:read], fn(file) -> text = IO.read(file, :all) leng = String.length(text) String.codepoints(text) |> Enum.group_by(&(&1)) |> Enum.map(fn{_,value} -> length(value) end) |> Enum.reduce(0, fn count, entropy -> freq = count / leng entropy - freq * :math.log2(freq) end) |> IO.puts end)
http://rosettacode.org/wiki/Entropy/Narcissist
Entropy/Narcissist
Task Write a computer program that computes and shows its own   entropy. Related Tasks   Fibonacci_word   Entropy
#Emacs_Lisp
Emacs Lisp
(defun shannon-entropy (input) (let ((freq-table (make-hash-table)) (entropy 0) (length (+ (length input) 0.0))) (mapcar (lambda (x) (puthash x (+ 1 (gethash x freq-table 0)) freq-table)) input) (maphash (lambda (k v) (set 'entropy (+ entropy (* (/ v length) (log (/ v length) 2))))) freq-table) (- entropy)))   (defun narcissist () (shannon-entropy (with-temp-buffer (insert-file-contents "U:/rosetta/narcissist.el") (buffer-string))))
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#ALGOL_68
ALGOL 68
BEGIN # example 1 # MODE FRUIT = INT; FRUIT apple = 1, banana = 2, cherry = 4; FRUIT x := cherry; CASE x IN print(("It is an apple #",x, new line)), print(("It is a banana #",x, new line)), SKIP, # 3 not defined # print(("It is a cherry #",x, new line)) OUT SKIP # other values # ESAC END;
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#AmigaE
AmigaE
ENUM APPLE, BANANA, CHERRY   PROC main() DEF x ForAll({x}, [APPLE, BANANA, CHERRY], `WriteF('\d\n', x)) ENDPROC
http://rosettacode.org/wiki/Enforced_immutability
Enforced immutability
Task Demonstrate any means your language has to prevent the modification of values, or to create objects that cannot be modified after they have been created.
#11l
11l
-V min_size = 10
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
#ALGOL_W
ALGOL W
begin  % returns half of a % integer procedure halve ( integer value a ) ; a div 2;  % returns a doubled % integer procedure double ( integer value a ) ; a * 2;  % returns true if a is even, false otherwise % logical procedure even ( integer value a ) ; not odd( a );  % returns the product of a and b using ethopian multiplication %  % rather than keep a table of the intermediate results,  %  % we examine then as they are generated  % integer procedure ethopianMultiplication ( integer value a, b ) ; begin integer v, r, accumulator; v  := a; r  := b; accumulator := 0; i_w := 4; s_w := 0; % set output formatting % while begin write( v ); if even( v ) then writeon( " ---" ) else begin accumulator := accumulator + r; writeon( " ", r ); end; v := halve( v ); r := double( r ); v > 0 end do begin end; write( " =====" ); accumulator end ethopianMultiplication ;  % task test case % begin integer m; m := ethopianMultiplication( 17, 34 ); write( " ", m ) end end.
http://rosettacode.org/wiki/Equilibrium_index
Equilibrium index
An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices. For example, in a sequence   A {\displaystyle A} :   A 0 = − 7 {\displaystyle A_{0}=-7}   A 1 = 1 {\displaystyle A_{1}=1}   A 2 = 5 {\displaystyle A_{2}=5}   A 3 = 2 {\displaystyle A_{3}=2}   A 4 = − 4 {\displaystyle A_{4}=-4}   A 5 = 3 {\displaystyle A_{5}=3}   A 6 = 0 {\displaystyle A_{6}=0} 3   is an equilibrium index, because:   A 0 + A 1 + A 2 = A 4 + A 5 + A 6 {\displaystyle A_{0}+A_{1}+A_{2}=A_{4}+A_{5}+A_{6}} 6   is also an equilibrium index, because:   A 0 + A 1 + A 2 + A 3 + A 4 + A 5 = 0 {\displaystyle A_{0}+A_{1}+A_{2}+A_{3}+A_{4}+A_{5}=0} (sum of zero elements is zero) 7   is not an equilibrium index, because it is not a valid index of sequence A {\displaystyle A} . Task; Write a function that, given a sequence, returns its equilibrium indices (if any). Assume that the sequence may be very long.
#AutoHotkey
AutoHotkey
Equilibrium_index(list, BaseIndex=0){ StringSplit, A, list, `, Loop % A0 { i := A_Index , Pre := Post := 0 loop, % A0 if (A_Index < i) Pre += A%A_Index% else if (A_Index > i) Post += A%A_Index% if (Pre = Post) Res .= (Res?", ":"") i - (BaseIndex?0:1) } return Res }
http://rosettacode.org/wiki/Equilibrium_index
Equilibrium index
An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices. For example, in a sequence   A {\displaystyle A} :   A 0 = − 7 {\displaystyle A_{0}=-7}   A 1 = 1 {\displaystyle A_{1}=1}   A 2 = 5 {\displaystyle A_{2}=5}   A 3 = 2 {\displaystyle A_{3}=2}   A 4 = − 4 {\displaystyle A_{4}=-4}   A 5 = 3 {\displaystyle A_{5}=3}   A 6 = 0 {\displaystyle A_{6}=0} 3   is an equilibrium index, because:   A 0 + A 1 + A 2 = A 4 + A 5 + A 6 {\displaystyle A_{0}+A_{1}+A_{2}=A_{4}+A_{5}+A_{6}} 6   is also an equilibrium index, because:   A 0 + A 1 + A 2 + A 3 + A 4 + A 5 = 0 {\displaystyle A_{0}+A_{1}+A_{2}+A_{3}+A_{4}+A_{5}=0} (sum of zero elements is zero) 7   is not an equilibrium index, because it is not a valid index of sequence A {\displaystyle A} . Task; Write a function that, given a sequence, returns its equilibrium indices (if any). Assume that the sequence may be very long.
#AWK
AWK
  # syntax: GAWK -f EQUILIBRIUM_INDEX.AWK BEGIN { main("-7 1 5 2 -4 3 0") main("2 4 6") main("2 9 2") main("1 -1 1 -1 1 -1 1") exit(0) } function main(numbers, x) { x = equilibrium(numbers) printf("numbers: %s\n",numbers) printf("indices: %s\n\n",length(x)==0?"none":x) } function equilibrium(numbers, arr,i,leftsum,leng,str,sum) { leng = split(numbers,arr," ") for (i=1; i<=leng; i++) { sum += arr[i] } for (i=1; i<=leng; i++) { sum -= arr[i] if (leftsum == sum) { str = str i " " } leftsum += arr[i] } return(str) }  
http://rosettacode.org/wiki/Environment_variables
Environment variables
Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. Environment-Vars.   DATA DIVISION. WORKING-STORAGE SECTION. 01 home PIC X(75).   PROCEDURE DIVISION. * *> Method 1. ACCEPT home FROM ENVIRONMENT "HOME" DISPLAY home   * *> Method 2. DISPLAY "HOME" UPON ENVIRONMENT-NAME ACCEPT home FROM ENVIRONMENT-VALUE   GOBACK .
http://rosettacode.org/wiki/Environment_variables
Environment variables
Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
#CoffeeScript
CoffeeScript
for var_name in ['PATH', 'HOME', 'LANG', 'USER'] console.log var_name, process.env[var_name]
http://rosettacode.org/wiki/Environment_variables
Environment variables
Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
#Common_Lisp
Common Lisp
(lispworks:environment-variable "USER")
http://rosettacode.org/wiki/Esthetic_numbers
Esthetic numbers
An esthetic number is a positive integer where every adjacent digit differs from its neighbour by 1. E.G. 12 is an esthetic number. One and two differ by 1. 5654 is an esthetic number. Each digit is exactly 1 away from its neighbour. 890 is not an esthetic number. Nine and zero differ by 9. These examples are nominally in base 10 but the concept extends easily to numbers in other bases. Traditionally, single digit numbers are included in esthetic numbers; zero may or may not be. For our purposes, for this task, do not include zero (0) as an esthetic number. Do not include numbers with leading zeros. Esthetic numbers are also sometimes referred to as stepping numbers. Task Write a routine (function, procedure, whatever) to find esthetic numbers in a given base. Use that routine to find esthetic numbers in bases 2 through 16 and display, here on this page, the esthectic numbers from index (base × 4) through index (base × 6), inclusive. (E.G. for base 2: 8th through 12th, for base 6: 24th through 36th, etc.) Find and display, here on this page, the base 10 esthetic numbers with a magnitude between 1000 and 9999. Stretch: Find and display, here on this page, the base 10 esthetic numbers with a magnitude between 1.0e8 and 1.3e8. Related task   numbers with equal rises and falls See also OEIS A033075 - Positive numbers n such that all pairs of consecutive decimal digits differ by 1 Numbers Aplenty - Esthetic numbers Geeks for Geeks - Stepping numbers
#Lua
Lua
function to(n, b) local BASE = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"   if n == 0 then return "0" end   local ss = "" while n > 0 do local idx = (n % b) + 1 n = math.floor(n / b) ss = ss .. BASE:sub(idx, idx) end return string.reverse(ss) end   function isEsthetic(n, b) function uabs(a, b) if a < b then return b - a end return a - b end   if n == 0 then return false end local i = n % b n = math.floor(n / b) while n > 0 do local j = n % b if uabs(i, j) ~= 1 then return false end n = math.floor(n / b) i = j end return true end   function listEsths(n, n2, m, m2, perLine, all) local esths = {} function dfs(n, m, i) if i >= n and i <= m then table.insert(esths, i) end if i == 0 or i > m then return end local d = i % 10 local i1 = 10 * i + d - 1 local i2 = i1 + 2 if d == 0 then dfs(n, m, i2) elseif d == 9 then dfs(n, m, i1) else dfs(n, m, i1) dfs(n, m, i2) end end   for i=0,9 do dfs(n2, m2, i) end local le = #esths print(string.format("Base 10: %s esthetic numbers between %s and %s:", le, math.floor(n), math.floor(m))) if all then for c,esth in pairs(esths) do io.write(esth.." ") if c % perLine == 0 then print() end end print() else for i=1,perLine do io.write(esths[i] .. " ") end print("\n............") for i = le - perLine + 1, le do io.write(esths[i] .. " ") end print() end print() end   for b=2,16 do print(string.format("Base %d: %dth to %dth esthetic numbers:", b, 4 * b, 6 * b)) local n = 1 local c = 0 while c < 6 * b do if isEsthetic(n, b) then c = c + 1 if c >= 4 * b then io.write(to(n, b).." ") end end n = n + 1 end print() end print()   -- the following all use the obvious range limitations for the numbers in question listEsths(1000, 1010, 9999, 9898, 16, true) listEsths(1e8, 101010101, 13 * 1e7, 123456789, 9, true) listEsths(1e11, 101010101010, 13 * 1e10, 123456789898, 7, false) listEsths(1e14, 101010101010101, 13 * 1e13, 123456789898989, 5, false) listEsths(1e17, 101010101010101010, 13 * 1e16, 123456789898989898, 4, false)
http://rosettacode.org/wiki/Euler%27s_sum_of_powers_conjecture
Euler's sum of powers conjecture
There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin. Euler's (disproved) sum of powers   conjecture At least k positive kth powers are required to sum to a kth power, except for the trivial case of one kth power: yk = yk In 1966,   Leon J. Lander   and   Thomas R. Parkin   used a brute-force search on a   CDC 6600   computer restricting numbers to those less than 250. Task Write a program to search for an integer solution for: x05 + x15 + x25 + x35 == y5 Where all   xi's   and   y   are distinct integers between   0   and   250   (exclusive). Show an answer here. Related tasks   Pythagorean quadruples.   Pythagorean triples.
#C.2B.2B
C++
#include <algorithm> #include <iostream> #include <cmath> #include <set> #include <vector>   using namespace std;   bool find() { const auto MAX = 250; vector<double> pow5(MAX); for (auto i = 1; i < MAX; i++) pow5[i] = (double)i * i * i * i * i; for (auto x0 = 1; x0 < MAX; x0++) { for (auto x1 = 1; x1 < x0; x1++) { for (auto x2 = 1; x2 < x1; x2++) { for (auto x3 = 1; x3 < x2; x3++) { auto sum = pow5[x0] + pow5[x1] + pow5[x2] + pow5[x3]; if (binary_search(pow5.begin(), pow5.end(), sum)) { cout << x0 << " " << x1 << " " << x2 << " " << x3 << " " << pow(sum, 1.0 / 5.0) << endl; return true; } } } } } // not found return false; }   int main(void) { int tm = clock(); if (!find()) cout << "Nothing found!\n"; cout << "time=" << (int)((clock() - tm) * 1000 / CLOCKS_PER_SEC) << " milliseconds\r\n"; return 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
#Mirah
Mirah
def factorial_iterative(n:int) 2.upto(n-1) do |i| n *= i end n end   puts factorial_iterative 10
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.
#Arturo
Arturo
loop (neg 5)..5 [x][ if? even? x -> print [pad to :string x 4 ": even"] else -> print [pad to :string x 4 ": odd"] ]