task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#AWK
AWK
1
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Axe
Axe
:.PRGMNAME :
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.
#Wren
Wren
class A { construct new(f) { _f = f // sets field _f to the argument f }   // getter property to allow access to _f f { _f }   // setter property to allow _f to be mutated f=(other) { _f = other } }   var a = A.new(6) System.print(a.f) a.f = 8 System.print(a.f)
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.
#Z80_Assembly
Z80 Assembly
List: byte 2,3,4,5,6 ;this could be either mutable or immutable, it depends on the hardware.
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.
#zkl
zkl
List(1,2,3).del(0) //--> L(2,3) ROList(1,2,3).del(0) //-->SyntaxError : Can't find del, which means you can't call it d:=Dictionary(); d.add("one",1) D(one:1) d.makeReadOnly(); d.add("2",2) //-->AccessError(This Dictionary is read only)
http://rosettacode.org/wiki/Entropy
Entropy
Task Calculate the Shannon entropy   H   of a given input string. Given the discrete random variable X {\displaystyle X} that is a string of N {\displaystyle N} "symbols" (total characters) consisting of n {\displaystyle n} different characters (n=2 for binary), the Shannon entropy of X in bits/symbol is : H 2 ( X ) = − ∑ i = 1 n c o u n t i N log 2 ⁡ ( c o u n t i N ) {\displaystyle H_{2}(X)=-\sum _{i=1}^{n}{\frac {count_{i}}{N}}\log _{2}\left({\frac {count_{i}}{N}}\right)} where c o u n t i {\displaystyle count_{i}} is the count of character n i {\displaystyle n_{i}} . For this task, use X="1223334444" as an example. The result should be 1.84644... bits/symbol. This assumes X was a random variable, which may not be the case, or it may depend on the observer. This coding problem calculates the "specific" or "intensive" entropy that finds its parallel in physics with "specific entropy" S0 which is entropy per kg or per mole, not like physical entropy S and therefore not the "information" content of a file. It comes from Boltzmann's H-theorem where S = k B N H {\displaystyle S=k_{B}NH} where N=number of molecules. Boltzmann's H is the same equation as Shannon's H, and it gives the specific entropy H on a "per molecule" basis. The "total", "absolute", or "extensive" information entropy is S = H 2 N {\displaystyle S=H_{2}N} bits This is not the entropy being coded here, but it is the closest to physical entropy and a measure of the information content of a string. But it does not look for any patterns that might be available for compression, so it is a very restricted, basic, and certain measure of "information". Every binary file with an equal number of 1's and 0's will have S=N bits. All hex files with equal symbol frequencies will have S = N log 2 ⁡ ( 16 ) {\displaystyle S=N\log _{2}(16)} bits of entropy. The total entropy in bits of the example above is S= 10*18.4644 = 18.4644 bits. The H function does not look for any patterns in data or check if X was a random variable. For example, X=000000111111 gives the same calculated entropy in all senses as Y=010011100101. For most purposes it is usually more relevant to divide the gzip length by the length of the original data to get an informal measure of how much "order" was in the data. Two other "entropies" are useful: Normalized specific entropy: H n = H 2 ∗ log ⁡ ( 2 ) log ⁡ ( n ) {\displaystyle H_{n}={\frac {H_{2}*\log(2)}{\log(n)}}} which varies from 0 to 1 and it has units of "entropy/symbol" or just 1/symbol. For this example, Hn<\sub>= 0.923. Normalized total (extensive) entropy: S n = H 2 N ∗ log ⁡ ( 2 ) log ⁡ ( n ) {\displaystyle S_{n}={\frac {H_{2}N*\log(2)}{\log(n)}}} which varies from 0 to N and does not have units. It is simply the "entropy", but it needs to be called "total normalized extensive entropy" so that it is not confused with Shannon's (specific) entropy or physical entropy. For this example, Sn<\sub>= 9.23. Shannon himself is the reason his "entropy/symbol" H function is very confusingly called "entropy". That's like calling a function that returns a speed a "meter". See section 1.7 of his classic A Mathematical Theory of Communication and search on "per symbol" and "units" to see he always stated his entropy H has units of "bits/symbol" or "entropy/symbol" or "information/symbol". So it is legitimate to say entropy NH is "information". In keeping with Landauer's limit, the physics entropy generated from erasing N bits is S = H 2 N k B ln ⁡ ( 2 ) {\displaystyle S=H_{2}Nk_{B}\ln(2)} if the bit storage device is perfectly efficient. This can be solved for H2*N to (arguably) get the number of bits of information that a physical entropy represents. Related tasks Fibonacci_word Entropy/Narcissist
#EchoLisp
EchoLisp
  (lib 'hash) ;; counter: hash-table[key]++ (define (count++ ht k ) (hash-set ht k (1+ (hash-ref! ht k 0))))   (define (hi count n ) (define pi (// count n)) (- (* pi (log2 pi))))   ;; (H [string|list]) → entropy (bits) (define (H info) (define S (if(string? info) (string->list info) info)) (define ht (make-hash)) (define n (length S))   (for ((s S)) (count++ ht s)) (for/sum ((s (make-set S))) (hi (hash-ref ht s) n)))    
http://rosettacode.org/wiki/Ethiopian_multiplication
Ethiopian multiplication
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last in the same column, until you write a value of 1. In the right-hand column repeatedly double the last number and write the result below. stop when you add a result in the same row as where the left hand column shows 1. Examine the table produced and discard any row where the value in the left column is even. Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together For example:   17 × 34 17 34 Halving the first column: 17 34 8 4 2 1 Doubling the second column: 17 34 8 68 4 136 2 272 1 544 Strike-out rows whose first cell is even: 17 34 8 68 4 136 2 272 1 544 Sum the remaining numbers in the right-hand column: 17 34 8 -- 4 --- 2 --- 1 544 ==== 578 So 17 multiplied by 34, by the Ethiopian method is 578. Task The task is to define three named functions/methods/procedures/subroutines: one to halve an integer, one to double an integer, and one to state if an integer is even. Use these functions to create a function that does Ethiopian multiplication. References Ethiopian multiplication explained (BBC Video clip) A Night Of Numbers - Go Forth And Multiply (Video) Russian Peasant Multiplication Programming Praxis: Russian Peasant Multiplication
#D
D
int ethiopian(int n1, int n2) pure nothrow @nogc in { assert(n1 >= 0, "Multiplier can't be negative"); } body { static enum doubleNum = (in int n) pure nothrow @nogc => n * 2; static enum halveNum = (in int n) pure nothrow @nogc => n / 2; static enum isEven = (in int n) pure nothrow @nogc => !(n & 1);   int result; while (n1 >= 1) { if (!isEven(n1)) result += n2; n1 = halveNum(n1); n2 = doubleNum(n2); }   return result; } unittest { assert(ethiopian(77, 54) == 77 * 54); assert(ethiopian(8, 923) == 8 * 923); assert(ethiopian(64, -4) == 64 * -4); }   void main() { import std.stdio;   writeln("17 ethiopian 34 is ", ethiopian(17, 34)); }
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.
#Logo
Logo
to equilibrium.iter :i :before :after :tail :ret if equal? :before :after [make "ret lput :i :ret] if empty? butfirst :tail [output :ret] output equilibrium.iter :i+1 (:before+first :tail) (:after-first butfirst :tail) (butfirst :tail) :ret end to equilibrium.index :list output equilibrium.iter 1 0 (apply "sum butfirst :list) :list [] end   show equilibrium_index [-7 1 5 2 -4 3 0]  ; [4 7]
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.
#Lua
Lua
  function array_sum(t) assert(type(t) == "table", "t must be a table!") local sum = 0 for i=1, #t do sum = sum + t[i] end return sum end   function equilibrium_index(t) assert(type(t) == "table", "t must be a table!") local left, right, ret = 0, array_sum(t), -1 for i,j in pairs(t) do right = right - j if left == right then ret = i break end left = left + j end return ret end   print(equilibrium_index({-7, 1, 5, 2, -4, 3, 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
#Python
Python
import os os.environ['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
#R
R
Sys.getenv("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
#Racket
Racket
  #lang racket (getenv "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
#Raku
Raku
say %*ENV<HOME>;
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.
#JavaScript
JavaScript
var eulers_sum_of_powers = function (iMaxN) {   var aPow5 = []; var oPow5ToN = {};   for (var iP = 0; iP <= iMaxN; iP++) { var iPow5 = Math.pow(iP, 5); aPow5.push(iPow5); oPow5ToN[iPow5] = iP; }   for (var i0 = 1; i0 <= iMaxN; i0++) { for (var i1 = 1; i1 <= i0; i1++) { for (var i2 = 1; i2 <= i1; i2++) { for (var i3 = 1; i3 <= i2; i3++) { var iPow5Sum = aPow5[i0] + aPow5[i1] + aPow5[i2] + aPow5[i3]; if (typeof oPow5ToN[iPow5Sum] != 'undefined') { return { i0: i0, i1: i1,l i2: i2, i3: i3, iSum: oPow5ToN[iPow5Sum] }; } } } } }   };   var oResult = eulers_sum_of_powers(250);   console.log(oResult.i0 + '^5 + ' + oResult.i1 + '^5 + ' + oResult.i2 + '^5 + ' + oResult.i3 + '^5 = ' + oResult.iSum + '^5');
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
#Octave
Octave
% built in factorial printf("%d\n", factorial(50));   % let's define our recursive... function fact = my_fact(n) if ( n <= 1 ) fact = 1; else fact = n * my_fact(n-1); endif endfunction   printf("%d\n", my_fact(50));   % let's define our iterative function fact = iter_fact(n) fact = 1; for i = 2:n fact = fact * i; endfor endfunction   printf("%d\n", iter_fact(50));
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.
#Delphi
Delphi
  program EvenOdd;   {$APPTYPE CONSOLE}   {$R *.res}   uses System.SysUtils;   procedure IsOdd(aValue: Integer); var Odd: Boolean; begin Odd := aValue and 1 <> 0; Write(Format('%d is ', [aValue])); if Odd then Writeln('odd') else Writeln('even'); end;   var i: Integer; begin for i := -5 to 10 do IsOdd(i);   Readln; 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.
#Vlang
Vlang
import math // Fdy is a type for fntion f used in Euler's method. type Fdy = fn(f64, f64) f64   // euler_step computes a single new value using Euler's method. // Note that step size h is a parameter, so a variable step size // could be used. fn euler_step(f Fdy, x f64, y f64, h f64) f64 { return y + h*f(x, y) }   // Definition of cooling rate. Note that this has general utility and // is not specific to use in Euler's method.   // new_cooling_rate returns a fntion that computes cooling rate // for a given cooling rate constant k. fn new_cooling_rate(k f64) fn(f64) f64 { return fn[k](delta_temp f64) f64 { return -k * delta_temp } }   // new_temp_func returns a fntion that computes the analytical solution // of cooling rate integrated over time. fn new_temp_func(k f64, ambient_temp f64, initial_temp f64) fn(f64) f64 { return fn[ambient_temp,initial_temp,k](time f64) f64 { return ambient_temp + (initial_temp-ambient_temp)*math.exp(-k*time) } }   // new_cooling_rate_dy returns a fntion of the kind needed for Euler's method. // That is, a fntion representing dy(x, y(x)). // // Parameters to new_cooling_rate_dy are cooling constant k and ambient // temperature. fn new_cooling_rate_dy(k f64, ambient_temp f64) Fdy { // note that result is dependent only on the object temperature. // there are no additional dependencies on time, so the x parameter // provided by euler_step is unused. return fn[k,ambient_temp](_ f64, object_temp f64) f64 { return new_cooling_rate(k)(object_temp - ambient_temp) } }   fn main() { k := .07 temp_room := 20.0 temp_object := 100.0 fcr := new_cooling_rate_dy(k, temp_room) analytic := new_temp_func(k, temp_room, temp_object) for delta_time in [2.0, 5, 10] { println("Step size = ${delta_time:.1f}") println(" Time Euler's Analytic") mut temp := temp_object for time := 0.0; time <= 100; time += delta_time { println("${time:5.1f} ${temp:7.3f} ${analytic(time):7.3f}") temp = euler_step(fcr, time, temp, delta_time) } println('') } }
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
#MATLAB_.2F_Octave
MATLAB / Octave
>> nchoosek(5,3) ans = 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
#Maxima
Maxima
binomial( 5, 3); /* 10 */ binomial(-5, 3); /* -35 */ binomial( 5, -3); /* 0 */ binomial(-5, -3); /* 0 */ binomial( 3, 5); /* 0 */   binomial(x, 3); /* ((x - 2)*(x - 1)*x)/6 */   binomial(3, 1/2); /* binomial(3, 1/2) */ makegamma(%); /* 32/(5*%pi) */   binomial(a, b); /* binomial(a, b) */ makegamma(%); /* gamma(a + 1)/(gamma(-b + a + 1)*gamma(b + 1)) */
http://rosettacode.org/wiki/Emirp_primes
Emirp primes
An   emirp   (prime spelled backwards)   are primes that when reversed   (in their decimal representation)   are a different prime. (This rules out palindromic primes.) Task   show the first   twenty   emirps   show all emirps between   7,700   and   8,000   show the   10,000th   emirp In each list, the numbers should be in order. Invoke the (same) program once per task requirement, this will show what limit is used as the upper bound for calculating surplus (regular) primes. The specific method of how to determine if a range or if specific values are to be shown will be left to the programmer. See also   Wikipedia, Emirp.   The Prime Pages, emirp.   Wolfram MathWorld™, Emirp.   The On‑Line Encyclopedia of Integer Sequences, emirps (A6567).
#D
D
bool isEmirp(uint n) pure nothrow @nogc { bool isPrime(in uint n) pure nothrow @nogc { if (n == 2 || n == 3) return true; else if (n < 2 || n % 2 == 0 || n % 3 == 0) return false; for (uint div = 5, inc = 2; div ^^ 2 <= n; div += inc, inc = 6 - inc) if (n % div == 0) return false;   return true; }   uint reverse(uint n) pure nothrow @nogc { uint r; for (r = 0; n; n /= 10) r = r * 10 + (n % 10); return r; }   immutable r = reverse(n); return r != n && isPrime(n) && isPrime(r); }   void main() { import std.stdio, std.algorithm, std.range;   auto uints = uint.max.iota; writeln("First 20:\n", uints.filter!isEmirp.take(20)); writeln("Between 7700 and 8000:\n", iota(7_700, 8_001).filter!isEmirp); writeln("10000th: ", uints.filter!isEmirp.drop(9_999).front); }
http://rosettacode.org/wiki/Elliptic_curve_arithmetic
Elliptic curve arithmetic
Elliptic curves   are sometimes used in   cryptography   as a way to perform   digital signatures. The purpose of this task is to implement a simplified (without modular arithmetic) version of the elliptic curve arithmetic which is required by the   elliptic curve DSA   protocol. In a nutshell, an elliptic curve is a bi-dimensional curve defined by the following relation between the x and y coordinates of any point on the curve:   y 2 = x 3 + a x + b {\displaystyle y^{2}=x^{3}+ax+b} a and b are arbitrary parameters that define the specific curve which is used. For this particular task, we'll use the following parameters:   a=0,   b=7 The most interesting thing about elliptic curves is the fact that it is possible to define a   group   structure on it. To do so we define an   internal composition   rule with an additive notation +,   such that for any three distinct points P, Q and R on the curve, whenever these points are aligned, we have:   P + Q + R = 0 Here   0   (zero)   is the infinity point,   for which the x and y values are not defined.   It's basically the same kind of point which defines the horizon in   projective geometry. We'll also assume here that this infinity point is unique and defines the   neutral element   of the addition. This was not the definition of the addition, but only its desired property.   For a more accurate definition, we proceed as such: Given any three aligned points P, Q and R,   we define the sum   S = P + Q   as the point (possibly the infinity point) such that   S, R   and the infinity point are aligned. Considering the symmetry of the curve around the x-axis, it's easy to convince oneself that two points S and R can be aligned with the infinity point if and only if S and R are symmetric of one another towards the x-axis   (because in that case there is no other candidate than the infinity point to complete the alignment triplet). S is thus defined as the symmetric of R towards the x axis. The task consists in defining the addition which, for any two points of the curve, returns the sum of these two points.   You will pick two random points on the curve, compute their sum and show that the symmetric of the sum is aligned with the two initial points. You will use the a and b parameters of secp256k1, i.e. respectively zero and seven. Hint:   You might need to define a "doubling" function, that returns P+P for any given point P. Extra credit:   define the full elliptic curve arithmetic (still not modular, though) by defining a "multiply" function that returns, for any point P and integer n,   the point P + P + ... + P     (n times).
#Racket
Racket
  #lang racket (define a 0) (define b 7) (define (ε? x) (<= (abs x) 1e-14)) (define (== p q) (for/and ([pi p] [qi q]) (ε? (- pi qi)))) (define zero #(0 0)) (define (zero? p) (== p zero)) (define (neg p) (match-define (vector x y) p) (vector x (- y))) (define (⊕ p q) (cond [(== q (neg p)) zero] [else (match-define (vector px py) p) (match-define (vector qx qy) q) (define (done λ px py qx) (define x (- (* λ λ) px qx)) (vector x (- (+ (* λ (- x px)) py)))) (cond [(and (== p q) (ε? py)) zero] [(or (== p q) (ε? (- px qx))) (done (/ (+ (* 3 px px) a) (* 2 py)) px py qx)] [(done (/ (- py qy) (- px qx)) px py qx)])])) (define (⊗ p n) (cond [(= n 0) zero] [(= n 1) p] [(= n 2) (⊕ p p)] [(negative? n) (neg (⊗ p (- n)))] [(even? n) (⊗ (⊗ p (/ n 2)) 2)] [(odd? n) (⊕ p (⊗ p (- n 1)))]))  
http://rosettacode.org/wiki/Elliptic_curve_arithmetic
Elliptic curve arithmetic
Elliptic curves   are sometimes used in   cryptography   as a way to perform   digital signatures. The purpose of this task is to implement a simplified (without modular arithmetic) version of the elliptic curve arithmetic which is required by the   elliptic curve DSA   protocol. In a nutshell, an elliptic curve is a bi-dimensional curve defined by the following relation between the x and y coordinates of any point on the curve:   y 2 = x 3 + a x + b {\displaystyle y^{2}=x^{3}+ax+b} a and b are arbitrary parameters that define the specific curve which is used. For this particular task, we'll use the following parameters:   a=0,   b=7 The most interesting thing about elliptic curves is the fact that it is possible to define a   group   structure on it. To do so we define an   internal composition   rule with an additive notation +,   such that for any three distinct points P, Q and R on the curve, whenever these points are aligned, we have:   P + Q + R = 0 Here   0   (zero)   is the infinity point,   for which the x and y values are not defined.   It's basically the same kind of point which defines the horizon in   projective geometry. We'll also assume here that this infinity point is unique and defines the   neutral element   of the addition. This was not the definition of the addition, but only its desired property.   For a more accurate definition, we proceed as such: Given any three aligned points P, Q and R,   we define the sum   S = P + Q   as the point (possibly the infinity point) such that   S, R   and the infinity point are aligned. Considering the symmetry of the curve around the x-axis, it's easy to convince oneself that two points S and R can be aligned with the infinity point if and only if S and R are symmetric of one another towards the x-axis   (because in that case there is no other candidate than the infinity point to complete the alignment triplet). S is thus defined as the symmetric of R towards the x axis. The task consists in defining the addition which, for any two points of the curve, returns the sum of these two points.   You will pick two random points on the curve, compute their sum and show that the symmetric of the sum is aligned with the two initial points. You will use the a and b parameters of secp256k1, i.e. respectively zero and seven. Hint:   You might need to define a "doubling" function, that returns P+P for any given point P. Extra credit:   define the full elliptic curve arithmetic (still not modular, though) by defining a "multiply" function that returns, for any point P and integer n,   the point P + P + ... + P     (n times).
#Raku
Raku
unit module EC; our ($A, $B) = (0, 7);   role Horizon { method gist { 'EC Point at horizon' } } class Point { has ($.x, $.y); multi method new( $x, $y where $y**2 ~~ $x**3 + $A*$x + $B ) { self.bless(:$x, :$y) } multi method new(Horizon $) { self.bless but Horizon } method gist { "EC Point at x=$.x, y=$.y" } }   multi prefix:<->(Point $p) { Point.new: x => $p.x, y => -$p.y } multi prefix:<->(Horizon $) { Horizon } multi infix:<->(Point $a, Point $b) { $a + -$b }   multi infix:<+>(Horizon $, Point $p) { $p } multi infix:<+>(Point $p, Horizon) { $p }   multi infix:<*>(Point $u, Int $n) { $n * $u } multi infix:<*>(Int $n, Horizon) { Horizon } multi infix:<*>(0, Point) { Horizon } multi infix:<*>(1, Point $p) { $p } multi infix:<*>(2, Point $p) { my $l = (3*$p.x**2 + $A) / (2 *$p.y); my $y = $l*($p.x - my $x = $l**2 - 2*$p.x) - $p.y; $p.bless(:$x, :$y); } multi infix:<*>(Int $n where $n > 2, Point $p) { 2 * ($n div 2 * $p) + $n % 2 * $p; }   multi infix:<+>(Point $p, Point $q) { if $p.x ~~ $q.x { return $p.y ~~ $q.y ?? 2 * $p !! Horizon; } else { my $slope = ($q.y - $p.y) / ($q.x - $p.x); my $y = $slope*($p.x - my $x = $slope**2 - $p.x - $q.x) - $p.y; return $p.new(:$x, :$y); } }   say my $p = Point.new: x => $_, y => sqrt(abs($_**3 + $A*$_ + $B)) given 1; say my $q = Point.new: x => $_, y => sqrt(abs($_**3 + $A*$_ + $B)) given 2; say my $s = $p + $q;   say "checking alignment: ", abs ($p.x - $q.x)*(-$s.y - $q.y) - ($p.y - $q.y)*($s.x - $q.x);
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#OxygenBasic
OxygenBasic
  enum fruits apple pear orange = 14 banana mango end enum   print banana '15   'fruits values: ' apple 0 ' pear 1 ' orange 14 ' banana 15 ' mango 16  
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#Oz
Oz
declare fun {IsFruit A} {Member A [apple banana cherry]} end in {Show {IsFruit banana}}
http://rosettacode.org/wiki/Empty_string
Empty string
Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#C
C
#include <string.h>   /* ... */   /* assign an empty string */ const char *str = "";   /* to test a null string */ if (str) { ... }   /* to test if string is empty */ if (str[0] == '\0') { ... }   /* or equivalently use strlen function strlen will seg fault on NULL pointer, so check first */ if ( (str == NULL) || (strlen(str) == 0)) { ... }   /* or compare to a known empty string, same thing. "== 0" means strings are equal */ if (strcmp(str, "") == 0) { ... }  
http://rosettacode.org/wiki/Empty_directory
Empty directory
Starting with a path to some directory, determine whether the directory is empty. An empty directory contains no files nor subdirectories. With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other entries.
#Liberty_BASIC
Liberty BASIC
  dim info$(10, 10) files "c:\", info$()   qtyFiles=val(info$(0,0)) n = qtyFiles+1 'begin directory info   folder$ = info$(n,0) 'path to first directory in c:   files folder$, info$() 're-fill array with data from sub folder   if val(info$(0,0)) + val(info$(0, 1)) <> 0 then print "Folder ";folder$;" is not empty." else print "Folder ";folder$;" is empty." end if  
http://rosettacode.org/wiki/Empty_directory
Empty directory
Starting with a path to some directory, determine whether the directory is empty. An empty directory contains no files nor subdirectories. With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other entries.
#Lingo
Lingo
on isDirEmpty (dir) return getNthFileNameInFolder(dir, 1) = EMPTY end
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#BASIC
BASIC
 
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Batch_File
Batch File
 
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#BaCon
BaCon
 
http://rosettacode.org/wiki/Entropy
Entropy
Task Calculate the Shannon entropy   H   of a given input string. Given the discrete random variable X {\displaystyle X} that is a string of N {\displaystyle N} "symbols" (total characters) consisting of n {\displaystyle n} different characters (n=2 for binary), the Shannon entropy of X in bits/symbol is : H 2 ( X ) = − ∑ i = 1 n c o u n t i N log 2 ⁡ ( c o u n t i N ) {\displaystyle H_{2}(X)=-\sum _{i=1}^{n}{\frac {count_{i}}{N}}\log _{2}\left({\frac {count_{i}}{N}}\right)} where c o u n t i {\displaystyle count_{i}} is the count of character n i {\displaystyle n_{i}} . For this task, use X="1223334444" as an example. The result should be 1.84644... bits/symbol. This assumes X was a random variable, which may not be the case, or it may depend on the observer. This coding problem calculates the "specific" or "intensive" entropy that finds its parallel in physics with "specific entropy" S0 which is entropy per kg or per mole, not like physical entropy S and therefore not the "information" content of a file. It comes from Boltzmann's H-theorem where S = k B N H {\displaystyle S=k_{B}NH} where N=number of molecules. Boltzmann's H is the same equation as Shannon's H, and it gives the specific entropy H on a "per molecule" basis. The "total", "absolute", or "extensive" information entropy is S = H 2 N {\displaystyle S=H_{2}N} bits This is not the entropy being coded here, but it is the closest to physical entropy and a measure of the information content of a string. But it does not look for any patterns that might be available for compression, so it is a very restricted, basic, and certain measure of "information". Every binary file with an equal number of 1's and 0's will have S=N bits. All hex files with equal symbol frequencies will have S = N log 2 ⁡ ( 16 ) {\displaystyle S=N\log _{2}(16)} bits of entropy. The total entropy in bits of the example above is S= 10*18.4644 = 18.4644 bits. The H function does not look for any patterns in data or check if X was a random variable. For example, X=000000111111 gives the same calculated entropy in all senses as Y=010011100101. For most purposes it is usually more relevant to divide the gzip length by the length of the original data to get an informal measure of how much "order" was in the data. Two other "entropies" are useful: Normalized specific entropy: H n = H 2 ∗ log ⁡ ( 2 ) log ⁡ ( n ) {\displaystyle H_{n}={\frac {H_{2}*\log(2)}{\log(n)}}} which varies from 0 to 1 and it has units of "entropy/symbol" or just 1/symbol. For this example, Hn<\sub>= 0.923. Normalized total (extensive) entropy: S n = H 2 N ∗ log ⁡ ( 2 ) log ⁡ ( n ) {\displaystyle S_{n}={\frac {H_{2}N*\log(2)}{\log(n)}}} which varies from 0 to N and does not have units. It is simply the "entropy", but it needs to be called "total normalized extensive entropy" so that it is not confused with Shannon's (specific) entropy or physical entropy. For this example, Sn<\sub>= 9.23. Shannon himself is the reason his "entropy/symbol" H function is very confusingly called "entropy". That's like calling a function that returns a speed a "meter". See section 1.7 of his classic A Mathematical Theory of Communication and search on "per symbol" and "units" to see he always stated his entropy H has units of "bits/symbol" or "entropy/symbol" or "information/symbol". So it is legitimate to say entropy NH is "information". In keeping with Landauer's limit, the physics entropy generated from erasing N bits is S = H 2 N k B ln ⁡ ( 2 ) {\displaystyle S=H_{2}Nk_{B}\ln(2)} if the bit storage device is perfectly efficient. This can be solved for H2*N to (arguably) get the number of bits of information that a physical entropy represents. Related tasks Fibonacci_word Entropy/Narcissist
#Elena
Elena
import system'math; import system'collections; import system'routines; import extensions;   extension op { logTwo() = self.ln() / 2.ln(); }   public program() { var input := console.readLine(); var infoC := 0.0r; var table := Dictionary.new();   input.forEach:(ch) { var n := table[ch]; if (nil == n) { table[ch] := 1 } else { table[ch] := n + 1 } };   var freq := 0; table.forEach:(letter) { freq := letter.toInt().realDiv(input.Length);   infoC += (freq * freq.logTwo()) };   infoC *= -1;   console.printLine("The Entropy of ", input, " is ", infoC) }
http://rosettacode.org/wiki/Entropy
Entropy
Task Calculate the Shannon entropy   H   of a given input string. Given the discrete random variable X {\displaystyle X} that is a string of N {\displaystyle N} "symbols" (total characters) consisting of n {\displaystyle n} different characters (n=2 for binary), the Shannon entropy of X in bits/symbol is : H 2 ( X ) = − ∑ i = 1 n c o u n t i N log 2 ⁡ ( c o u n t i N ) {\displaystyle H_{2}(X)=-\sum _{i=1}^{n}{\frac {count_{i}}{N}}\log _{2}\left({\frac {count_{i}}{N}}\right)} where c o u n t i {\displaystyle count_{i}} is the count of character n i {\displaystyle n_{i}} . For this task, use X="1223334444" as an example. The result should be 1.84644... bits/symbol. This assumes X was a random variable, which may not be the case, or it may depend on the observer. This coding problem calculates the "specific" or "intensive" entropy that finds its parallel in physics with "specific entropy" S0 which is entropy per kg or per mole, not like physical entropy S and therefore not the "information" content of a file. It comes from Boltzmann's H-theorem where S = k B N H {\displaystyle S=k_{B}NH} where N=number of molecules. Boltzmann's H is the same equation as Shannon's H, and it gives the specific entropy H on a "per molecule" basis. The "total", "absolute", or "extensive" information entropy is S = H 2 N {\displaystyle S=H_{2}N} bits This is not the entropy being coded here, but it is the closest to physical entropy and a measure of the information content of a string. But it does not look for any patterns that might be available for compression, so it is a very restricted, basic, and certain measure of "information". Every binary file with an equal number of 1's and 0's will have S=N bits. All hex files with equal symbol frequencies will have S = N log 2 ⁡ ( 16 ) {\displaystyle S=N\log _{2}(16)} bits of entropy. The total entropy in bits of the example above is S= 10*18.4644 = 18.4644 bits. The H function does not look for any patterns in data or check if X was a random variable. For example, X=000000111111 gives the same calculated entropy in all senses as Y=010011100101. For most purposes it is usually more relevant to divide the gzip length by the length of the original data to get an informal measure of how much "order" was in the data. Two other "entropies" are useful: Normalized specific entropy: H n = H 2 ∗ log ⁡ ( 2 ) log ⁡ ( n ) {\displaystyle H_{n}={\frac {H_{2}*\log(2)}{\log(n)}}} which varies from 0 to 1 and it has units of "entropy/symbol" or just 1/symbol. For this example, Hn<\sub>= 0.923. Normalized total (extensive) entropy: S n = H 2 N ∗ log ⁡ ( 2 ) log ⁡ ( n ) {\displaystyle S_{n}={\frac {H_{2}N*\log(2)}{\log(n)}}} which varies from 0 to N and does not have units. It is simply the "entropy", but it needs to be called "total normalized extensive entropy" so that it is not confused with Shannon's (specific) entropy or physical entropy. For this example, Sn<\sub>= 9.23. Shannon himself is the reason his "entropy/symbol" H function is very confusingly called "entropy". That's like calling a function that returns a speed a "meter". See section 1.7 of his classic A Mathematical Theory of Communication and search on "per symbol" and "units" to see he always stated his entropy H has units of "bits/symbol" or "entropy/symbol" or "information/symbol". So it is legitimate to say entropy NH is "information". In keeping with Landauer's limit, the physics entropy generated from erasing N bits is S = H 2 N k B ln ⁡ ( 2 ) {\displaystyle S=H_{2}Nk_{B}\ln(2)} if the bit storage device is perfectly efficient. This can be solved for H2*N to (arguably) get the number of bits of information that a physical entropy represents. Related tasks Fibonacci_word Entropy/Narcissist
#Elixir
Elixir
defmodule RC do def entropy(str) do leng = String.length(str) String.graphemes(str) |> 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) end end   IO.inspect RC.entropy("1223334444")
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
#dc
dc
0k [ Make sure we're doing integer division ]sx [ 2 / ] sH [ Define "halve" function in register H ]sx [ 2 * ] sD [ Define "double" function in register D ]sx [ 2 % 1 r - ] sE [ Define "even?" function in register E ]sx   [ Entry into the main Ethiopian multiplication function is register M ]sx [ Keeps running value for the product in register p ]sx [ 0 sp lLx lp ] sM   [ The body of the main loop is in register L ]sx   [ sb sa [ First thing we do is cheat and store the parameters in registers, which is safe because the only recursion is of the tail variety. This avoids tricky stack manipulations, which dc doesn't have good support for (unlike, say, Forth). ]sx   la lEx sr [ r = even?(a) ]sx lr 0 =S [ if r = 0 then call s]sx la lHx d [ a = halve(a)]sx lb lDx [ b = double(b)]sx r 0 !=L [ if a !=0 then recurse ] ] sL   [ Utility macro that just adds the current value of b to the total in p ]sx [ lp lb + sp ]sS   [ Demo by multiplying 17 and 34 ]sx 17 34 lMx p
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.
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
equilibriumIndex[data_]:=Reap[ Do[If[Total[data[[;; n - 1]]] == Total[data[[n + 1 ;;]]],Sow[n]], {n, Length[data]}]][[2, 1]]
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.
#MATLAB
MATLAB
function indicies = equilibriumIndex(list)   indicies = [];   for i = (1:numel(list)) if ( sum(-list(1:i)) == sum(-list(i:end)) ) indicies = [indicies i]; end end   end
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
#REBOL
REBOL
print get-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
#Retro
Retro
here "HOME" getEnv here puts
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
#REXX
REXX
/*REXX program shows how to get an environmental variable under Windows*/   x=value('TEMP',,'SYSTEM')
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
#Ring
Ring
  see get("path")  
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.
#jq
jq
# Search for y in 1 .. maxn (inclusive) for a solution to SIGMA (xi ^ 5) = y^5 # and for each solution with x0<=x1<=...<x3, print [x0, x1, x3, x3, y] # def sum_of_powers_conjecture(maxn): def p5: . as $in | (.*.) | ((.*.) * $in); def fifth: log / 5 | exp;   # return the fifth root if . is a power of 5 def integral_fifth_root: fifth | if . == floor then . else false end;   (maxn | p5) as $uber | range(1; maxn) as $x0 | ($x0 | p5) as $s0 | if $s0 < $uber then range($x0; ($uber - $s0 | fifth) + 1) as $x1 | ($s0 + ($x1 | p5)) as $s1 | if $s1 < $uber then range($x1; ($uber - $s1 | fifth) + 1) as $x2 | ($s1 + ($x2 | p5)) as $s2 | if $s2 < $uber then range($x2; ($uber - $s2 | fifth) + 1) as $x3 | ($s2 + ($x3 | p5)) as $sumx | ($sumx | integral_fifth_root) | if . then [$x0,$x1,$x2,$x3,.] else empty end else empty end else empty end else empty end ;
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
#Oforth
Oforth
: fact(n) n ifZero: [ 1 ] else: [ n n 1- fact * ] ;
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.
#DWScript
DWScript
var isOdd := Odd(i);
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.
#D.C3.A9j.C3.A0_Vu
Déjà Vu
even n: = 0 % n 2   odd: not even   !. odd 0 !. even 0 !. odd 7 !. even 7  
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.
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations   proc Euler(Step); \Display cooling temperatures using Euler's method int Step; int Time; real Temp; [Text(0, "Step "); IntOut(0, Step); Text(0, " "); Time:= 0; Temp:= 100.0; repeat if rem(Time/10) = 0 then RlOut(0, Temp); Temp:= Temp + float(Step) * (-0.07*(Temp-20.0)); Time:= Time + Step; until Time > 100; CrLf(0); ];   real Time, Temp; [Format(6,0); \display time heading Text(0, "Time "); Time:= 0.0; while Time <= 100.1 do \(.1 avoids possible rounding error) [RlOut(0, Time); Time:= Time + 10.0; ]; CrLf(0);   Format(3,2); \display cooling temps using differential eqn. Text(0, "Dif eq "); \ dTemp(time)/dtime = -k*�Temp Time:= 0.0; while Time <= 100.1 do [Temp:= 20.0 + (100.0-20.0) * Exp(-0.07*Time); RlOut(0, Temp); Time:= Time + 10.0; ]; CrLf(0);   Euler(2); \display cooling temps for various time steps Euler(5); Euler(10); ]
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.
#Wren
Wren
import "/fmt" for Fmt import "/trait" for Stepped   var euler = Fn.new { |f, y, step, end| Fmt.write(" Step $2d: ", step) for (t in Stepped.new(0..end, step)) { if (t%10 == 0) Fmt.write(" $7.3f", y) y = y + step * f.call(y) } System.print() }   var analytic = Fn.new { System.write(" Time: ") for (t in Stepped.new(0..100, 10)) Fmt.write(" $7d", t) System.write("\nAnalytic: ") for (t in Stepped.new(0..100, 10)) { Fmt.write(" $7.3f", 20 + 80 * (-0.07*t).exp) } System.print() } var cooling = Fn.new { |temp| -0.07 * (temp - 20) }   analytic.call() for (i in [2, 5, 10]) euler.call(cooling, 100, 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
#min
min
((dup 0 ==) 'succ (dup pred) '* linrec) :fact ('dup dip dup ((fact) () (- fact) (fact * div)) spread) :binomial   5 3 binomial puts!
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
#MINIL
MINIL
// Number of combinations nCr 00 0E Go: ENT R0 // n 01 1E ENT R1 // r 02 2C CLR R2 03 2A Loop: ADD1 R2 04 0D DEC R0 05 1D DEC R1 06 C3 JNZ Loop 07 3C CLR R3 // for result 08 3A ADD1 R3 09 0A Next: ADD1 R0 0A 1A ADD1 R1 0B 50 R5 = R0 0C 5D DEC R5 0D 63 R6 = R3 0E 46 Mult: R4 = R6 0F 3A Add: ADD1 R3 10 4D DEC R4 11 CF JNZ Add 12 5D DEC R5 13 CE JNZ Mult 14 61 Divide:R6 = R1 15 5A ADD1 R5 16 3D Sub: DEC R3 17 9B JZ Exact 18 6D DEC R6 19 D6 JNZ Sub 1A 94 JZ Divide 1B 35 Exact: R3 = R5 1C 2D DEC R2 1D C9 JNZ Next 1E 03 R0 = R3 1F 80 JZ Go // Display result
http://rosettacode.org/wiki/Emirp_primes
Emirp primes
An   emirp   (prime spelled backwards)   are primes that when reversed   (in their decimal representation)   are a different prime. (This rules out palindromic primes.) Task   show the first   twenty   emirps   show all emirps between   7,700   and   8,000   show the   10,000th   emirp In each list, the numbers should be in order. Invoke the (same) program once per task requirement, this will show what limit is used as the upper bound for calculating surplus (regular) primes. The specific method of how to determine if a range or if specific values are to be shown will be left to the programmer. See also   Wikipedia, Emirp.   The Prime Pages, emirp.   Wolfram MathWorld™, Emirp.   The On‑Line Encyclopedia of Integer Sequences, emirps (A6567).
#Delphi
Delphi
defmodule Emirp do defp prime?(2), do: true defp prime?(n) when n<2 or rem(n,2)==0, do: false defp prime?(n), do: prime?(n,3)   defp prime?(n,k) when n<k*k, do: true defp prime?(n,k) when rem(n,k)==0, do: false defp prime?(n,k), do: prime?(n,k+2)   def emirp?(n) do if prime?(n) do reverse = to_string(n) |> String.reverse |> String.to_integer n != reverse and prime?(reverse) end end   def task do emirps = Stream.iterate(1, &(&1+1)) |> Stream.filter(&emirp?/1) first = Enum.take(emirps,20) |> Enum.join(" ") IO.puts "First 20 emirps: #{first}" between = Enum.reduce_while(emirps, [], fn x,acc -> cond do x < 7700 -> {:cont, acc} x in 7700..8000 -> {:cont, [x | acc]} true -> {:halt, Enum.reverse(acc)} end end) |> Enum.join(" ") IO.puts "Emirps between 7,700 and 8,000: #{between}" IO.puts "10,000th emirp: #{Enum.at(emirps, 9999)}" end end   Emirp.task
http://rosettacode.org/wiki/Emirp_primes
Emirp primes
An   emirp   (prime spelled backwards)   are primes that when reversed   (in their decimal representation)   are a different prime. (This rules out palindromic primes.) Task   show the first   twenty   emirps   show all emirps between   7,700   and   8,000   show the   10,000th   emirp In each list, the numbers should be in order. Invoke the (same) program once per task requirement, this will show what limit is used as the upper bound for calculating surplus (regular) primes. The specific method of how to determine if a range or if specific values are to be shown will be left to the programmer. See also   Wikipedia, Emirp.   The Prime Pages, emirp.   Wolfram MathWorld™, Emirp.   The On‑Line Encyclopedia of Integer Sequences, emirps (A6567).
#Elixir
Elixir
defmodule Emirp do defp prime?(2), do: true defp prime?(n) when n<2 or rem(n,2)==0, do: false defp prime?(n), do: prime?(n,3)   defp prime?(n,k) when n<k*k, do: true defp prime?(n,k) when rem(n,k)==0, do: false defp prime?(n,k), do: prime?(n,k+2)   def emirp?(n) do if prime?(n) do reverse = to_string(n) |> String.reverse |> String.to_integer n != reverse and prime?(reverse) end end   def task do emirps = Stream.iterate(1, &(&1+1)) |> Stream.filter(&emirp?/1) first = Enum.take(emirps,20) |> Enum.join(" ") IO.puts "First 20 emirps: #{first}" between = Enum.reduce_while(emirps, [], fn x,acc -> cond do x < 7700 -> {:cont, acc} x in 7700..8000 -> {:cont, [x | acc]} true -> {:halt, Enum.reverse(acc)} end end) |> Enum.join(" ") IO.puts "Emirps between 7,700 and 8,000: #{between}" IO.puts "10,000th emirp: #{Enum.at(emirps, 9999)}" end end   Emirp.task
http://rosettacode.org/wiki/Elliptic_curve_arithmetic
Elliptic curve arithmetic
Elliptic curves   are sometimes used in   cryptography   as a way to perform   digital signatures. The purpose of this task is to implement a simplified (without modular arithmetic) version of the elliptic curve arithmetic which is required by the   elliptic curve DSA   protocol. In a nutshell, an elliptic curve is a bi-dimensional curve defined by the following relation between the x and y coordinates of any point on the curve:   y 2 = x 3 + a x + b {\displaystyle y^{2}=x^{3}+ax+b} a and b are arbitrary parameters that define the specific curve which is used. For this particular task, we'll use the following parameters:   a=0,   b=7 The most interesting thing about elliptic curves is the fact that it is possible to define a   group   structure on it. To do so we define an   internal composition   rule with an additive notation +,   such that for any three distinct points P, Q and R on the curve, whenever these points are aligned, we have:   P + Q + R = 0 Here   0   (zero)   is the infinity point,   for which the x and y values are not defined.   It's basically the same kind of point which defines the horizon in   projective geometry. We'll also assume here that this infinity point is unique and defines the   neutral element   of the addition. This was not the definition of the addition, but only its desired property.   For a more accurate definition, we proceed as such: Given any three aligned points P, Q and R,   we define the sum   S = P + Q   as the point (possibly the infinity point) such that   S, R   and the infinity point are aligned. Considering the symmetry of the curve around the x-axis, it's easy to convince oneself that two points S and R can be aligned with the infinity point if and only if S and R are symmetric of one another towards the x-axis   (because in that case there is no other candidate than the infinity point to complete the alignment triplet). S is thus defined as the symmetric of R towards the x axis. The task consists in defining the addition which, for any two points of the curve, returns the sum of these two points.   You will pick two random points on the curve, compute their sum and show that the symmetric of the sum is aligned with the two initial points. You will use the a and b parameters of secp256k1, i.e. respectively zero and seven. Hint:   You might need to define a "doubling" function, that returns P+P for any given point P. Extra credit:   define the full elliptic curve arithmetic (still not modular, though) by defining a "multiply" function that returns, for any point P and integer n,   the point P + P + ... + P     (n times).
#REXX
REXX
/*REXX program defines (for any 2 points on the curve), returns the sum of the 2 points.*/ numeric digits 100 /*try to ensure a min. of accuracy loss*/ a= func(1)  ; say ' a = ' show(a) b= func(2)  ; say ' b = ' show(b) c= add(a, b)  ; say ' c = (a+b) =' show(c) d= neg(c)  ; say ' d = -c =' show(d) e= add(c, d)  ; say ' e = (c+d) =' show(e) g= add(a, add(b, d))  ; say ' g = (a+b+d) =' show(g) exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ cbrt: procedure; parse arg x; return root(x,3) conv: procedure; arg z; if isZ(z) then return 'zero'; return left('',z>=0)format(z,,5)/1 root: procedure; parse arg x,y; if x=0 | y=1 then return x/1; d=5; return rootI()/1 rootG: parse value format(x,2,1,,0) 'E0' with  ? 'E' _ .; return (?/y'E'_ %y) + (x>1) func: procedure; parse arg y,k; if k=='' then k=7; return cbrt(y**2-k) y inf: return '1e' || (digits()%2) isZ: procedure; parse arg px . ; return abs(px) >= inf() neg: procedure; parse arg px py; return px (-py) show: procedure; parse arg x y ; return conv(x) conv(y) zero: return inf() inf() /*──────────────────────────────────────────────────────────────────────────────────────*/ add: procedure; parse arg px py, qx qy; if px=qx & py=qy then return dbl(px py) if isZ(px py) then return qx qy; if isZ(qx qy) then return px py z= qx - px; if z=0 then do; $= inf(); rx= inf(); end else do; $= (qy-py) / z; rx= $*$ - px - qx; end ry= $ * (px-rx) - py; return rx ry /*──────────────────────────────────────────────────────────────────────────────────────*/ dbl: procedure; parse arg px py; if isZ(px py) then return px py; z= py+py if z=0 then $= inf() else $= (3*px*py) / (py+py) rx= $*$ - px*px; ry= $ * (px-rx) - py; return rx ry /*──────────────────────────────────────────────────────────────────────────────────────*/ rootI: ox=x; oy=y; x=abs(x); y=abs(y); a=digits()+5; numeric form; g=rootG(); m=y-1 do until d==a; d=min(d+d,a); numeric digits d; o=0 do until o=g; o=g; g=format((m*g**y+x)/y/g**m,,d-2); end /*until o=g*/ end /*until d==a*/; _=g*sign(ox); if oy<0 then _=1/_; return _
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#Pascal
Pascal
type phase = (red, green, blue);
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#Perl
Perl
# Using an array my @fruits = qw(apple banana cherry);   # Using a hash my %fruits = ( apple => 0, banana => 1, cherry => 2 );
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#Phix
Phix
enum apple, banana, orange enum apple=5, banana=10, orange=
http://rosettacode.org/wiki/Empty_string
Empty string
Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#C.23
C#
using System;   class Program { static void Main (string[] args) { string example = string.Empty; if (string.IsNullOrEmpty(example)) { } if (!string.IsNullOrEmpty(example)) { } } }
http://rosettacode.org/wiki/Empty_directory
Empty directory
Starting with a path to some directory, determine whether the directory is empty. An empty directory contains no files nor subdirectories. With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other entries.
#Lua
Lua
  function scandir(directory) local i, t, popen = 0, {}, io.popen local pfile = popen('ls -a "'..directory..'"') for filename in pfile:lines() do if filename ~= '.' and filename ~= '..' then i = i + 1 t[i] = filename end end pfile:close() return t end   function isemptydir(directory) return #scandir(directory) == 0 end  
http://rosettacode.org/wiki/Empty_directory
Empty directory
Starting with a path to some directory, determine whether the directory is empty. An empty directory contains no files nor subdirectories. With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other entries.
#Maple
Maple
  emptydirectory := proc (dir) is(listdir(dir) = [".", ".."]); end proc;  
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#BASIC256
BASIC256
 
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#BBC_BASIC
BBC BASIC
 
http://rosettacode.org/wiki/Entropy
Entropy
Task Calculate the Shannon entropy   H   of a given input string. Given the discrete random variable X {\displaystyle X} that is a string of N {\displaystyle N} "symbols" (total characters) consisting of n {\displaystyle n} different characters (n=2 for binary), the Shannon entropy of X in bits/symbol is : H 2 ( X ) = − ∑ i = 1 n c o u n t i N log 2 ⁡ ( c o u n t i N ) {\displaystyle H_{2}(X)=-\sum _{i=1}^{n}{\frac {count_{i}}{N}}\log _{2}\left({\frac {count_{i}}{N}}\right)} where c o u n t i {\displaystyle count_{i}} is the count of character n i {\displaystyle n_{i}} . For this task, use X="1223334444" as an example. The result should be 1.84644... bits/symbol. This assumes X was a random variable, which may not be the case, or it may depend on the observer. This coding problem calculates the "specific" or "intensive" entropy that finds its parallel in physics with "specific entropy" S0 which is entropy per kg or per mole, not like physical entropy S and therefore not the "information" content of a file. It comes from Boltzmann's H-theorem where S = k B N H {\displaystyle S=k_{B}NH} where N=number of molecules. Boltzmann's H is the same equation as Shannon's H, and it gives the specific entropy H on a "per molecule" basis. The "total", "absolute", or "extensive" information entropy is S = H 2 N {\displaystyle S=H_{2}N} bits This is not the entropy being coded here, but it is the closest to physical entropy and a measure of the information content of a string. But it does not look for any patterns that might be available for compression, so it is a very restricted, basic, and certain measure of "information". Every binary file with an equal number of 1's and 0's will have S=N bits. All hex files with equal symbol frequencies will have S = N log 2 ⁡ ( 16 ) {\displaystyle S=N\log _{2}(16)} bits of entropy. The total entropy in bits of the example above is S= 10*18.4644 = 18.4644 bits. The H function does not look for any patterns in data or check if X was a random variable. For example, X=000000111111 gives the same calculated entropy in all senses as Y=010011100101. For most purposes it is usually more relevant to divide the gzip length by the length of the original data to get an informal measure of how much "order" was in the data. Two other "entropies" are useful: Normalized specific entropy: H n = H 2 ∗ log ⁡ ( 2 ) log ⁡ ( n ) {\displaystyle H_{n}={\frac {H_{2}*\log(2)}{\log(n)}}} which varies from 0 to 1 and it has units of "entropy/symbol" or just 1/symbol. For this example, Hn<\sub>= 0.923. Normalized total (extensive) entropy: S n = H 2 N ∗ log ⁡ ( 2 ) log ⁡ ( n ) {\displaystyle S_{n}={\frac {H_{2}N*\log(2)}{\log(n)}}} which varies from 0 to N and does not have units. It is simply the "entropy", but it needs to be called "total normalized extensive entropy" so that it is not confused with Shannon's (specific) entropy or physical entropy. For this example, Sn<\sub>= 9.23. Shannon himself is the reason his "entropy/symbol" H function is very confusingly called "entropy". That's like calling a function that returns a speed a "meter". See section 1.7 of his classic A Mathematical Theory of Communication and search on "per symbol" and "units" to see he always stated his entropy H has units of "bits/symbol" or "entropy/symbol" or "information/symbol". So it is legitimate to say entropy NH is "information". In keeping with Landauer's limit, the physics entropy generated from erasing N bits is S = H 2 N k B ln ⁡ ( 2 ) {\displaystyle S=H_{2}Nk_{B}\ln(2)} if the bit storage device is perfectly efficient. This can be solved for H2*N to (arguably) get the number of bits of information that a physical entropy represents. Related tasks Fibonacci_word Entropy/Narcissist
#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)))
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
#Delphi
Delphi
proc nonrec halve(word n) word: n >> 1 corp proc nonrec double(word n) word: n << 1 corp proc nonrec even(word n) bool: n & 1 = 0 corp   proc nonrec emul(word a, b) word: word total; total := 0; while a > 0 do if not even(a) then total := total + b fi; a := halve(a); b := double(b) od; total corp   proc nonrec main() void: writeln(emul(17, 34)) corp
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.
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   numeric digits 20 runSample(arg) return   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- @see http://www.geeksforgeeks.org/equilibrium-index-of-an-array/ method equilibriumIndex(sequence) private static es = '' loop ix = 1 to sequence.words() sum = 0 loop jx = 1 to sequence.words() if jx < ix then sum = sum + sequence.word(jx) if jx > ix then sum = sum - sequence.word(jx) end jx if sum = 0 then es = es ix end ix return es   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method runSample(arg) private static -- Note: A Rexx object based list of "words" starts at index 1 sequences = [ - '-7 1 5 2 -4 3 0', - -- 4 7 ' 2 4 6' , - -- (no equilibrium point) ' 0 2 4 0 6 0' , - -- 4 ' 2 9 2' , - -- 2 ' 1 -1 1 -1 1 -1 1' - -- 1 2 3 4 5 6 7 ] loop sequence over sequences say 'For sequence "'sequence.space(1, ',')'" the equilibrium indices are: \-' say '"'equilibriumIndex(sequence).space(1, ',')'"' end sequence return    
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
#Ruby
Ruby
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
#Run_BASIC
Run BASIC
' ------- Major environment variables ------------------------------------------- 'DefaultDir$ - The folder path where program files are read/written by default 'Platform$ - The operating system on which Run BASIC is being hosted 'UserInfo$ - This is information about the user's web browser 'UrlKeys$ - Contains informational parameters from the URL submitted when the user connected 'UserAddress$ - Contains the IP address of the user 'ProjectsRoot$ - The folder path where Run BASIC keeps programming projects 'ResourcesRoot$ - The folder path where Run BASIC keeps web-servable files 'Err$ - A description of the last runtime error 'Err - A numeric code for the last runtime error (errors that have no code use zero) 'EventKey$ - The id of the object that generated the last user event 'RowIndex - The numeric index of the table or database accessor link that generated the last user event     print "User Info is  : ";UserInfo$ print "Platform is  : ";Platform$ print "Url Keys is  : ";UrlKeys$ print "User Address is: ";UserAddress$ print "Event Key is  : ";EventKey$ print "Default Dir is : ";DefaultDir$
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
#Rust
Rust
use std::env;   fn main() { println!("{:?}", env::var("HOME")); println!(); for (k, v) in env::vars().filter(|(k, _)| k.starts_with('P')) { println!("{}: {}", k, v); } }  
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
#Scala
Scala
sys.env.get("HOME")
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.
#Julia
Julia
  const lim = 250 const pwr = 5 const p = [i^pwr for i in 1:lim]   x = zeros(Int, pwr-1) y = 0   for a in combinations(1:lim, pwr-1) b = searchsorted(p, sum(p[a])) 0 < length(b) || continue x = a y = b[1] break end   if y == 0 println("No solution found for power = ", pwr, " and limit = ", lim, ".") else s = [@sprintf("%d^%d", i, pwr) for i in x] s = join(s, " + ") println("A solution is ", s, " = ", @sprintf("%d^%d", y, pwr), ".") end  
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
#Order
Order
#include <order/interpreter.h>   #define ORDER_PP_DEF_8fac \ ORDER_PP_FN(8fn(8N, \ 8if(8less_eq(8N, 0), \ 1, \ 8mul(8N, 8fac(8dec(8N))))))   ORDER_PP(8to_lit(8fac(8))) // 40320
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.
#EDSAC_order_code
EDSAC order code
[ Even or odd ===========   A program for the EDSAC   Determines whether the number stored at address 15@ is even or odd, and prints 'E' or 'O' accordingly   Works with Initial Orders 2 ]   T56K [ load point ] GK [ base address ]   O11@ [ print letter shift ] T10@ [ clear accumulator ] H15@ [ multiplier := n ] C12@ [ acc +:= mult AND 1 ] S12@ [ acc -:= 1 ] G8@ [ branch on negative ] O14@ [ print 'O' ] ZF [ halt ] [ 8 ] O13@ [ print 'E' ] ZF [ halt ]   [ 10 ] P0F [ used to clear acc ] [ 11 ] *F [ letter shift character ] [ 12 ] P0D [ const: 1 ] [ 13 ] EF [ character 'E' ] [ 14 ] OF [ character 'O' ] [ 15 ] P18D [ number to test: 37 ]   EZPF [ branch to load point ]
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.
#Eiffel
Eiffel
--bit testing if i.bit_and (1) = 0 then -- i is even end   --built-in bit testing (uses bit_and) if i.bit_test (0) then -- i is odd end   --integer remainder (modulo) if i \\ 2 = 0 then -- i is even 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.
#zkl
zkl
const FMT=" %7.3f";   fcn ivp_euler(f,y,step,end_t){ print(" Step %2d: ".fmt(step)); foreach t in ([0..end_t,step]){ if (t % 10 == 0) print(FMT.fmt(y)); y += f(t,y) * step; } println(); }   fcn analytic{ print(" Time: "); foreach t in ([0..100,10]){ print(" %7g".fmt(t)) } print("\nAnalytic: "); foreach t in ([0..100,10]){ print(FMT.fmt(20.0 + 80.0 * (-0.07 * t).exp())) } println(); }   fcn cooling(_,temp){ return(-0.07 * (temp - 20)) }   analytic(); ivp_euler(cooling, 100.0, 2, 100); ivp_euler(cooling, 100.0, 5, 100); ivp_euler(cooling, 100.0, 10, 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.
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 LET d$="-0.07*(y-20)": LET y=100: LET a=0: LET b=100: LET s=10 20 LET t=a 30 IF t<=b THEN PRINT t;TAB 10;y: LET y=y+s*VAL d$: LET t=t+s: GO TO 30
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
#.D0.9C.D0.9A-61.2F52
МК-61/52
П1 <-> П0 ПП 22 П2 ИП1 ПП 22 П3 ИП0 ИП1 - ПП 22 ИП3 * П3 ИП2 ИП3 / С/П ВП П0 1 ИП0 * L0 25 В/О
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
#Nanoquery
Nanoquery
def binomialCoeff(n, k) result = 1 for i in range(1, k) result = result * (n-i+1) / i end return result end   if main println binomialCoeff(5,3) end
http://rosettacode.org/wiki/Emirp_primes
Emirp primes
An   emirp   (prime spelled backwards)   are primes that when reversed   (in their decimal representation)   are a different prime. (This rules out palindromic primes.) Task   show the first   twenty   emirps   show all emirps between   7,700   and   8,000   show the   10,000th   emirp In each list, the numbers should be in order. Invoke the (same) program once per task requirement, this will show what limit is used as the upper bound for calculating surplus (regular) primes. The specific method of how to determine if a range or if specific values are to be shown will be left to the programmer. See also   Wikipedia, Emirp.   The Prime Pages, emirp.   Wolfram MathWorld™, Emirp.   The On‑Line Encyclopedia of Integer Sequences, emirps (A6567).
#F.23
F#
  // Generate emirps. Nigel Galloway: November 19th., 2017 let emirp = let rec fN n g = match n with |0->g |_->fN (n/10) (g*10+n%10) let fG n g = n<>g && isPrime g primes32() |> Seq.filter (fun n -> fG n (fN n 0))  
http://rosettacode.org/wiki/Elliptic_curve_arithmetic
Elliptic curve arithmetic
Elliptic curves   are sometimes used in   cryptography   as a way to perform   digital signatures. The purpose of this task is to implement a simplified (without modular arithmetic) version of the elliptic curve arithmetic which is required by the   elliptic curve DSA   protocol. In a nutshell, an elliptic curve is a bi-dimensional curve defined by the following relation between the x and y coordinates of any point on the curve:   y 2 = x 3 + a x + b {\displaystyle y^{2}=x^{3}+ax+b} a and b are arbitrary parameters that define the specific curve which is used. For this particular task, we'll use the following parameters:   a=0,   b=7 The most interesting thing about elliptic curves is the fact that it is possible to define a   group   structure on it. To do so we define an   internal composition   rule with an additive notation +,   such that for any three distinct points P, Q and R on the curve, whenever these points are aligned, we have:   P + Q + R = 0 Here   0   (zero)   is the infinity point,   for which the x and y values are not defined.   It's basically the same kind of point which defines the horizon in   projective geometry. We'll also assume here that this infinity point is unique and defines the   neutral element   of the addition. This was not the definition of the addition, but only its desired property.   For a more accurate definition, we proceed as such: Given any three aligned points P, Q and R,   we define the sum   S = P + Q   as the point (possibly the infinity point) such that   S, R   and the infinity point are aligned. Considering the symmetry of the curve around the x-axis, it's easy to convince oneself that two points S and R can be aligned with the infinity point if and only if S and R are symmetric of one another towards the x-axis   (because in that case there is no other candidate than the infinity point to complete the alignment triplet). S is thus defined as the symmetric of R towards the x axis. The task consists in defining the addition which, for any two points of the curve, returns the sum of these two points.   You will pick two random points on the curve, compute their sum and show that the symmetric of the sum is aligned with the two initial points. You will use the a and b parameters of secp256k1, i.e. respectively zero and seven. Hint:   You might need to define a "doubling" function, that returns P+P for any given point P. Extra credit:   define the full elliptic curve arithmetic (still not modular, though) by defining a "multiply" function that returns, for any point P and integer n,   the point P + P + ... + P     (n times).
#Sage
Sage
Ellie = EllipticCurve(RR,[0,7]) # RR = field of real numbers   # a point (x,y) on Ellie, given y def point ( y) : x = var('x') x = (y^2 - 7 - x^3).roots(x,ring=RR,multiplicities = False)[0] P = Ellie([x,y]) return P   print(Ellie) P = point(1) print('P',P) Q = point(2) print('Q',Q) S = P+Q print('S = P + Q',S) print('P+Q-S', P+Q-S) print('P*12345' ,P*12345)
http://rosettacode.org/wiki/Elliptic_curve_arithmetic
Elliptic curve arithmetic
Elliptic curves   are sometimes used in   cryptography   as a way to perform   digital signatures. The purpose of this task is to implement a simplified (without modular arithmetic) version of the elliptic curve arithmetic which is required by the   elliptic curve DSA   protocol. In a nutshell, an elliptic curve is a bi-dimensional curve defined by the following relation between the x and y coordinates of any point on the curve:   y 2 = x 3 + a x + b {\displaystyle y^{2}=x^{3}+ax+b} a and b are arbitrary parameters that define the specific curve which is used. For this particular task, we'll use the following parameters:   a=0,   b=7 The most interesting thing about elliptic curves is the fact that it is possible to define a   group   structure on it. To do so we define an   internal composition   rule with an additive notation +,   such that for any three distinct points P, Q and R on the curve, whenever these points are aligned, we have:   P + Q + R = 0 Here   0   (zero)   is the infinity point,   for which the x and y values are not defined.   It's basically the same kind of point which defines the horizon in   projective geometry. We'll also assume here that this infinity point is unique and defines the   neutral element   of the addition. This was not the definition of the addition, but only its desired property.   For a more accurate definition, we proceed as such: Given any three aligned points P, Q and R,   we define the sum   S = P + Q   as the point (possibly the infinity point) such that   S, R   and the infinity point are aligned. Considering the symmetry of the curve around the x-axis, it's easy to convince oneself that two points S and R can be aligned with the infinity point if and only if S and R are symmetric of one another towards the x-axis   (because in that case there is no other candidate than the infinity point to complete the alignment triplet). S is thus defined as the symmetric of R towards the x axis. The task consists in defining the addition which, for any two points of the curve, returns the sum of these two points.   You will pick two random points on the curve, compute their sum and show that the symmetric of the sum is aligned with the two initial points. You will use the a and b parameters of secp256k1, i.e. respectively zero and seven. Hint:   You might need to define a "doubling" function, that returns P+P for any given point P. Extra credit:   define the full elliptic curve arithmetic (still not modular, though) by defining a "multiply" function that returns, for any point P and integer n,   the point P + P + ... + P     (n times).
#Sidef
Sidef
module EC {   var A = 0 var B = 7   class Horizon { method to_s { "EC Point at horizon" }   method *(_) { self }   method -(_) { self } }   class Point(Number x, Number y) { method to_s { "EC Point at x=#{x}, y=#{y}" }   method neg { Point(x, -y) }   method -(Point p) { self + -p }   method +(Point p) {   if (x == p.x) { return (y == p.y ? self*2 : Horizon()) } else { var slope = (p.y - y)/(p.x - x) var x2 = (slope**2 - x - p.x) var y2 = (slope * (x - x2) - y) Point(x2, y2) } }   method +(Horizon _) { self }   method *((0)) { Horizon() }   method *((1)) { self }   method *((2)) { var l = (3 * x**2 + A)/(2 * y) var x2 = (l**2 - 2*x) var y2 = (l * (x - x2) - y) Point(x2, y2) }   method *(Number n) { 2*(self * (n>>1)) + self*(n % 2) } }   class Horizon { method +(Point p) { p } }   class Number { method +(Point p) { p + self } method *(Point p) { p * self } method *(Horizon h) { h } method -(Point p) { -p + self } } }   say var p = with(1) {|v| EC::Point(v, sqrt(abs(1 - v**3 - EC::A*v - EC::B))) } say var q = with(2) {|v| EC::Point(v, sqrt(abs(1 - v**3 - EC::A*v - EC::B))) } say var s = (p + q)   say ("checking alignment: ", abs((p.x - q.x)*(-s.y - q.y) - (p.y - q.y)*(s.x - q.x)) < 1e-20)
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#PHP
PHP
// Using an array/hash $fruits = array( "apple", "banana", "cherry" ); $fruits = array( "apple" => 0, "banana" => 1, "cherry" => 2 );   // If you are inside a class scope class Fruit { const APPLE = 0; const BANANA = 1; const CHERRY = 2; }   // Then you can access them as such $value = Fruit::APPLE;   // Or, you can do it using define() define("FRUIT_APPLE", 0); define("FRUIT_BANANA", 1); define("FRUIT_CHERRY", 2);
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#Picat
Picat
fruit(apple,1). fruit(banana,2). fruit(cherry,4).   print_fruit_name(N) :- fruit(Name,N), printf("It is %w\nn", Name).
http://rosettacode.org/wiki/Empty_string
Empty string
Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#C.2B.2B
C++
#include <string>   // ...     // empty string declaration std::string str; // (default constructed) std::string str(); // (default constructor, no parameters) std::string str{}; // (default initialized) std::string str(""); // (const char[] conversion) std::string str{""}; // (const char[] initializer list)       if (str.empty()) { ... } // to test if string is empty   // we could also use the following if (str.length() == 0) { ... } if (str == "") { ... }   // make a std::string empty str.clear(); // (builtin clear function) str = ""; // replace contents with empty string str = {}; // swap contents with temp string (empty),then destruct temp   // swap with empty string std::string tmp{}; // temp empty string str.swap(tmp); // (builtin swap function) std::swap(str, tmp); // swap contents with tmp     // create an array of empty strings std::string s_array[100]; // 100 initialized to "" (fixed size) std::array<std::string, 100> arr; // 100 initialized to "" (fixed size) std::vector<std::string>(100,""); // 100 initialized to "" (variable size, 100 starting size)   // create empty string as default parameter void func( std::string& s = {} ); // {} generated default std:string instance  
http://rosettacode.org/wiki/Empty_directory
Empty directory
Starting with a path to some directory, determine whether the directory is empty. An empty directory contains no files nor subdirectories. With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other entries.
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
EmptyDirectoryQ[x_] := (SetDirectory[x]; If[FileNames[] == {}, True, False])   Example use: EmptyDirectoryQ["C:\\Program Files\\Wolfram Research\\Mathematica\\9"] ->True
http://rosettacode.org/wiki/Empty_directory
Empty directory
Starting with a path to some directory, determine whether the directory is empty. An empty directory contains no files nor subdirectories. With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other entries.
#MATLAB_.2F_Octave
MATLAB / Octave
  function x = isEmptyDirectory(p) if isdir(p) f = dir(p) x = length(f)>2; else error('Error: %s is not a directory'); end; end;  
http://rosettacode.org/wiki/Empty_directory
Empty directory
Starting with a path to some directory, determine whether the directory is empty. An empty directory contains no files nor subdirectories. With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other entries.
#min
min
(ls bool not) :empty-dir?
http://rosettacode.org/wiki/Empty_directory
Empty directory
Starting with a path to some directory, determine whether the directory is empty. An empty directory contains no files nor subdirectories. With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other entries.
#MS-DOS
MS-DOS
C:\>rd GAMES Unable to remove: GAMES.   C:\>
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#bc
bc
*
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Beeswax
Beeswax
*
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Befunge
Befunge
@
http://rosettacode.org/wiki/Entropy
Entropy
Task Calculate the Shannon entropy   H   of a given input string. Given the discrete random variable X {\displaystyle X} that is a string of N {\displaystyle N} "symbols" (total characters) consisting of n {\displaystyle n} different characters (n=2 for binary), the Shannon entropy of X in bits/symbol is : H 2 ( X ) = − ∑ i = 1 n c o u n t i N log 2 ⁡ ( c o u n t i N ) {\displaystyle H_{2}(X)=-\sum _{i=1}^{n}{\frac {count_{i}}{N}}\log _{2}\left({\frac {count_{i}}{N}}\right)} where c o u n t i {\displaystyle count_{i}} is the count of character n i {\displaystyle n_{i}} . For this task, use X="1223334444" as an example. The result should be 1.84644... bits/symbol. This assumes X was a random variable, which may not be the case, or it may depend on the observer. This coding problem calculates the "specific" or "intensive" entropy that finds its parallel in physics with "specific entropy" S0 which is entropy per kg or per mole, not like physical entropy S and therefore not the "information" content of a file. It comes from Boltzmann's H-theorem where S = k B N H {\displaystyle S=k_{B}NH} where N=number of molecules. Boltzmann's H is the same equation as Shannon's H, and it gives the specific entropy H on a "per molecule" basis. The "total", "absolute", or "extensive" information entropy is S = H 2 N {\displaystyle S=H_{2}N} bits This is not the entropy being coded here, but it is the closest to physical entropy and a measure of the information content of a string. But it does not look for any patterns that might be available for compression, so it is a very restricted, basic, and certain measure of "information". Every binary file with an equal number of 1's and 0's will have S=N bits. All hex files with equal symbol frequencies will have S = N log 2 ⁡ ( 16 ) {\displaystyle S=N\log _{2}(16)} bits of entropy. The total entropy in bits of the example above is S= 10*18.4644 = 18.4644 bits. The H function does not look for any patterns in data or check if X was a random variable. For example, X=000000111111 gives the same calculated entropy in all senses as Y=010011100101. For most purposes it is usually more relevant to divide the gzip length by the length of the original data to get an informal measure of how much "order" was in the data. Two other "entropies" are useful: Normalized specific entropy: H n = H 2 ∗ log ⁡ ( 2 ) log ⁡ ( n ) {\displaystyle H_{n}={\frac {H_{2}*\log(2)}{\log(n)}}} which varies from 0 to 1 and it has units of "entropy/symbol" or just 1/symbol. For this example, Hn<\sub>= 0.923. Normalized total (extensive) entropy: S n = H 2 N ∗ log ⁡ ( 2 ) log ⁡ ( n ) {\displaystyle S_{n}={\frac {H_{2}N*\log(2)}{\log(n)}}} which varies from 0 to N and does not have units. It is simply the "entropy", but it needs to be called "total normalized extensive entropy" so that it is not confused with Shannon's (specific) entropy or physical entropy. For this example, Sn<\sub>= 9.23. Shannon himself is the reason his "entropy/symbol" H function is very confusingly called "entropy". That's like calling a function that returns a speed a "meter". See section 1.7 of his classic A Mathematical Theory of Communication and search on "per symbol" and "units" to see he always stated his entropy H has units of "bits/symbol" or "entropy/symbol" or "information/symbol". So it is legitimate to say entropy NH is "information". In keeping with Landauer's limit, the physics entropy generated from erasing N bits is S = H 2 N k B ln ⁡ ( 2 ) {\displaystyle S=H_{2}Nk_{B}\ln(2)} if the bit storage device is perfectly efficient. This can be solved for H2*N to (arguably) get the number of bits of information that a physical entropy represents. Related tasks Fibonacci_word Entropy/Narcissist
#Erlang
Erlang
  -module( entropy ).   -export( [shannon/1, task/0] ).   shannon( String ) -> shannon_information_content( lists:foldl(fun count/2, dict:new(), String), erlang:length(String) ).   task() -> shannon( "1223334444" ).       count( Character, Dict ) -> dict:update_counter( Character, 1, Dict ).   shannon_information_content( Dict, String_length ) -> {_String_length, Acc} = dict:fold( fun shannon_information_content/3, {String_length, 0.0}, Dict ), Acc / math:log( 2 ).   shannon_information_content( _Character, How_many, {String_length, Acc} ) -> Frequency = How_many / String_length, {String_length, Acc - (Frequency * math:log(Frequency))}.  
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
#Draco
Draco
proc nonrec halve(word n) word: n >> 1 corp proc nonrec double(word n) word: n << 1 corp proc nonrec even(word n) bool: n & 1 = 0 corp   proc nonrec emul(word a, b) word: word total; total := 0; while a > 0 do if not even(a) then total := total + b fi; a := halve(a); b := double(b) od; total corp   proc nonrec main() void: writeln(emul(17, 34)) corp
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.
#Nim
Nim
import math, sequtils, strutils   iterator eqindex(data: openArray[int]): int = var suml, ddelayed = 0 var sumr = sum(data) for i,d in data: suml += ddelayed sumr -= d ddelayed = d if suml == sumr: yield i   const d = @[@[-7, 1, 5, 2, -4, 3, 0], @[2, 4, 6], @[2, 9, 2], @[1, -1, 1, -1, 1, -1, 1]]   for data in d: echo "d = [", data.join(", "), ']' echo "eqIndex(d) -> [", toSeq(eqindex(data)).join(", "), ']'
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.
#Objeck
Objeck
class Rosetta { function : Main(args : String[]) ~ Nil { sequence := [-7, 1, 5, 2, -4, 3, 0]; EqulibriumIndices(sequence); }   function : EqulibriumIndices(sequence : Int[]) ~ Nil { # find total sum totalSum := 0; each(i : sequence) { totalSum += sequence[i]; };   # compare running sum to remaining sum to find equlibrium indices runningSum := 0; each(i : sequence) { n := sequence[i]; if (totalSum - runningSum - n = runningSum) { i->PrintLine(); }; runningSum += n; }; } }
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
#Seed7
Seed7
$ include "seed7_05.s7i";   const proc: main is func begin writeln(getenv("HOME")); end func;
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
#Sidef
Sidef
say 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
#Slate
Slate
Environment variables at: 'PATH'. "==> '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games'"
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
#Smalltalk
Smalltalk
  OSProcess thisOSProcess environment at: #HOME. OSProcess thisOSProcess environment at: #PATH. OSProcess thisOSProcess environment at: #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
#SNOBOL4
SNOBOL4
output = host(4,'PATH') 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.
#Kotlin
Kotlin
fun main(args: Array<String>) { val p5 = LongArray(250){ it.toLong() * it * it * it * it } var sum: Long var y: Int var found = false loop@ for (x0 in 0 .. 249) for (x1 in 0 .. x0 - 1) for (x2 in 0 .. x1 - 1) for (x3 in 0 .. x2 - 1) { sum = p5[x0] + p5[x1] + p5[x2] + p5[x3] y = p5.binarySearch(sum) if (y >= 0) { println("$x0^5 + $x1^5 + $x2^5 + $x3^5 = $y^5") found = true break@loop } } if (!found) println("No solution was found") }
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
#Oz
Oz
fun {Fac1 N} {FoldL {List.number 1 N 1} Number.'*' 1} 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.
#Elixir
Elixir
defmodule RC do import Integer   def even_or_odd(n) when is_even(n), do: "#{n} is even" def even_or_odd(n) , do: "#{n} is odd" # In second "def", the guard clauses of "is_odd(n)" is unnecessary.   # Another definition way def even_or_odd2(n) do if is_even(n), do: "#{n} is even", else: "#{n} is odd" end end   Enum.each(-2..3, fn n -> IO.puts RC.even_or_odd(n) 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.
#Emacs_Lisp
Emacs Lisp
(require 'cl-lib)   (defun even-or-odd-p (n) (if (cl-evenp n) 'even 'odd))   (defun even-or-odd-p (n) (if (zerop (% n 2)) 'even 'odd))   (message "%d is %s" 3 (even-or-oddp 3)) (message "%d is %s" 2 (even-or-oddp 2))
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
#Nim
Nim
proc binomialCoeff(n, k: int): int = result = 1 for i in 1..k: result = result * (n-i+1) div i   echo binomialCoeff(5, 3)