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."
#ALGOL_W
ALGOL W
.
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.
#Pascal
Pascal
use constant PI => 3.14159; use constant MSG => "Hello World";
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.
#Perl
Perl
use constant PI => 3.14159; use constant MSG => "Hello World";
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.
#Phix
Phix
with javascript_semantics constant n = 1 constant s = {1,2,3} constant str = "immutable string"
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.
#PHP
PHP
define("PI", 3.14159265358); define("MSG", "Hello World");
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
#Clojure
Clojure
(defn entropy [s] (let [len (count s), log-2 (Math/log 2)] (->> (frequencies s) (map (fn [[_ v]] (let [rf (/ v len)] (-> (Math/log rf) (/ log-2) (* rf) Math/abs)))) (reduce +))))
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
#Clojure
Clojure
(defn halve [n] (bit-shift-right n 1))   (defn twice [n] ; 'double' is taken (bit-shift-left n 1))   (defn even [n] ; 'even?' is the standard fn (zero? (bit-and n 1)))   (defn emult [x y] (reduce + (map second (filter #(not (even (first %))) ; a.k.a. 'odd?' (take-while #(pos? (first %)) (map vector (iterate halve x) (iterate twice y)))))))   (defn emult2 [x y] (loop [a x, b y, r 0] (if (= a 1) (+ r b) (if (even a) (recur (halve a) (twice b) r) (recur (halve a) (twice b) (+ r b))))))
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.
#Icon_and_Unicon
Icon and Unicon
procedure main(arglist) L := if *arglist > 0 then arglist else [-7, 1, 5, 2, -4, 3, 0] # command line args or default every writes( "equilibrium indicies of [ " | (!L ||" ") | "] = " | (eqindex(L)||" ") | "\n" ) end   procedure eqindex(L) # generate equilibrium points in a list L or fail local s,l,i   every (s := 0, i := !L) do s +:= numeric(i) | fail # sum and validate   every (l := 0, i := 1 to *L) do { if l = (s-L[i])/2 then suspend i l +:= L[i] # sum of left side } 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
#Maple
Maple
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
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
Environment["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
#MATLAB_.2F_Octave
MATLAB / Octave
getenv('HOME') getenv('PATH') getenv('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
#Mercury
Mercury
:- module env_var. :- interface.   :- import_module io. :- pred main(io::di, io::uo) is det.   :- implementation. :- import_module maybe, string.   main(!IO) :- io.get_environment_var("HOME", MaybeValue, !IO), ( MaybeValue = yes(Value), io.write_string("HOME is " ++ Value ++ "\n", !IO)  ; MaybeValue = no, io.write_string("environment variable HOME not set\n", !IO) ).
http://rosettacode.org/wiki/Esthetic_numbers
Esthetic numbers
An esthetic number is a positive integer where every adjacent digit differs from its neighbour by 1. E.G. 12 is an esthetic number. One and two differ by 1. 5654 is an esthetic number. Each digit is exactly 1 away from its neighbour. 890 is not an esthetic number. Nine and zero differ by 9. These examples are nominally in base 10 but the concept extends easily to numbers in other bases. Traditionally, single digit numbers are included in esthetic numbers; zero may or may not be. For our purposes, for this task, do not include zero (0) as an esthetic number. Do not include numbers with leading zeros. Esthetic numbers are also sometimes referred to as stepping numbers. Task Write a routine (function, procedure, whatever) to find esthetic numbers in a given base. Use that routine to find esthetic numbers in bases 2 through 16 and display, here on this page, the esthectic numbers from index (base × 4) through index (base × 6), inclusive. (E.G. for base 2: 8th through 12th, for base 6: 24th through 36th, etc.) Find and display, here on this page, the base 10 esthetic numbers with a magnitude between 1000 and 9999. Stretch: Find and display, here on this page, the base 10 esthetic numbers with a magnitude between 1.0e8 and 1.3e8. Related task   numbers with equal rises and falls See also OEIS A033075 - Positive numbers n such that all pairs of consecutive decimal digits differ by 1 Numbers Aplenty - Esthetic numbers Geeks for Geeks - Stepping numbers
#Sidef
Sidef
func generate_esthetic(root, upto, callback, b=10) {   var v = root.digits2num(b)   return nil if (v > upto) callback(v)   var t = root.head   __FUNC__([t+1, root...], upto, callback, b) if (t+1 < b) __FUNC__([t-1, root...], upto, callback, b) if (t-1 >= 0) }   func between_esthetic(from, upto, b=10) { gather { for k in (1..^b) { generate_esthetic([k], upto, { take(_) if (_ >= from) }, b) } }.sort }   func first_n_esthetic(n, b=10) { for (var m = n**2; true ; m *= b) { var list = between_esthetic(1, m, b) return list.first(n) if (list.len >= n) } }   for b in (2..16) { say "\n#{b}-esthetic numbers with indices #{4*b}..#{6*b}: " say first_n_esthetic(6*b, b).last(6*b - 4*b + 1).map{.base(b)}.join(' ') }   say "\nBase 10 esthetic numbers between 1,000 and 9,999:" between_esthetic(1e3, 1e4).slices(20).each { .join(' ').say }   say "\nBase 10 esthetic numbers between 100,000,000 and 130,000,000:" between_esthetic(1e8, 13e7).slices(9).each { .join(' ').say }
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.
#FreeBASIC
FreeBASIC
' version 14-09-2015 ' compile with: fbc -s console   ' some constants calculated when the program is compiled   Const As UInteger max = 250 Const As ULongInt pow5_max = CULngInt(max) * max * max * max * max ' limit x1, x2, x3 Const As UInteger limit_x1 = (pow5_max / 4) ^ 0.2 Const As UInteger limit_x2 = (pow5_max / 3) ^ 0.2 Const As UInteger limit_x3 = (pow5_max / 2) ^ 0.2   ' ------=< MAIN >=------   Dim As ULongInt pow5(max), ans1, ans2, ans3 Dim As UInteger x1, x2, x3, x4, x5 , m1, m2   Cls : Print   For x1 = 1 To max pow5(x1) = CULngInt(x1) * x1 * x1 * x1 * x1 Next x1   For x1 = 1 To limit_x1 For x2 = x1 +1 To limit_x2 m1 = x1 + x2 ans1 = pow5(x1) + pow5(x2) If ans1 > pow5_max Then Exit For For x3 = x2 +1 To limit_x3 ans2 = ans1 + pow5(x3) If ans2 > pow5_max Then Exit For m2 = (m1 + x3) Mod 30 If m2 = 0 Then m2 = 30 For x4 = x3 +1 To max -1 ans3 = ans2 + pow5(x4) If ans3 > pow5_max Then Exit For For x5 = x4 + m2 To max Step 30 If ans3 < pow5(x5) Then Exit For If ans3 = pow5(x5) Then Print x1; "^5 + "; x2; "^5 + "; x3; "^5 + "; _ x4; "^5 = "; x5; "^5" Exit For, For EndIf Next x5 Next x4 Next x3 Next x2 Next x1   Print Print "done"   ' empty keyboard buffer While Inkey <> "" : Wend Print : Print "hit any key to end program" Sleep 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
#Nim
Nim
  import math let i:int = fac(x)  
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.
#Clojure
Clojure
(if (even? some-var) (do-even-stuff)) (if (odd? some-var) (do-odd-stuff))
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.
#Ring
Ring
  decimals(3) see euler("return -0.07*(y-20)", 100, 0, 100, 2) + nl see euler("return -0.07*(y-20)", 100, 0, 100, 5) + nl see euler("return -0.07*(y-20)", 100, 0, 100, 10) + nl   func euler df, y, a, b, s t = a while t <= b see "" + t + " " + y + nl y += s * eval(df) t += s end return y
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.
#Ruby
Ruby
def euler(y, a, b, h) a.step(b,h) do |t| puts "%7.3f %7.3f" % [t,y] y += h * yield(t,y) end end   [10, 5, 2].each do |step| puts "Step = #{step}" euler(100,0,100,step) {|time, temp| -0.07 * (temp - 20) } puts end
http://rosettacode.org/wiki/Evaluate_binomial_coefficients
Evaluate binomial coefficients
This programming task, is to calculate ANY binomial coefficient. However, it has to be able to output   ( 5 3 ) {\displaystyle {\binom {5}{3}}} ,   which is   10. This formula is recommended: ( n k ) = n ! ( n − k ) ! k ! = n ( n − 1 ) ( n − 2 ) … ( n − k + 1 ) k ( k − 1 ) ( k − 2 ) … 1 {\displaystyle {\binom {n}{k}}={\frac {n!}{(n-k)!k!}}={\frac {n(n-1)(n-2)\ldots (n-k+1)}{k(k-1)(k-2)\ldots 1}}} See Also: Combinations and permutations Pascal's triangle The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#Julia
Julia
@show binomial(5, 3)
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
#K
K
{[n;k]_(*/(k-1)_1+!n)%(*/1+!k)} . 5 3 10
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).
#AWK
AWK
  function is_prime(n, p) { if (!(n%2) || !(n%3)) { return 0 } p = 1 while(p*p < n) if (n%(p += 4) == 0 || n%(p += 2) == 0) { return 0 } return 1 }   function reverse(n, r) { r = 0 for (r = 0; int(n) != 0; n /= 10) r = r*10 + int(n%10); return r }   function is_emirp(n, r) { r = reverse(n) return ((r != n) && is_prime(n) && is_prime(r)) ? 1 : 0 }   BEGIN { c = 0 for (x = 11; c < 20; x += 2) { if (is_emirp(x)) { printf(" %i,", x); ++c } } printf("\n") for (x = 7701; x < 8000; x += 2) { if (is_emirp(x)) { printf(" %i,", x); ++c } } printf("\n") c = 0 for (x = 11; ; x += 2) if (is_emirp(x) && ++c == 10000) { printf(" %i", x); break; } printf("\n") }  
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).
#Java
Java
import static java.lang.Math.*; import java.util.Locale;   public class Test {   public static void main(String[] args) { Pt a = Pt.fromY(1); Pt b = Pt.fromY(2); System.out.printf("a = %s%n", a); System.out.printf("b = %s%n", b); Pt c = a.plus(b); System.out.printf("c = a + b = %s%n", c); Pt d = c.neg(); System.out.printf("d = -c = %s%n", d); System.out.printf("c + d = %s%n", c.plus(d)); System.out.printf("a + b + d = %s%n", a.plus(b).plus(d)); System.out.printf("a * 12345 = %s%n", a.mult(12345)); } }   class Pt { final static int bCoeff = 7;   double x, y;   Pt(double x, double y) { this.x = x; this.y = y; }   static Pt zero() { return new Pt(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY); }   boolean isZero() { return this.x > 1e20 || this.x < -1e20; }   static Pt fromY(double y) { return new Pt(cbrt(pow(y, 2) - bCoeff), y); }   Pt dbl() { if (isZero()) return this; double L = (3 * this.x * this.x) / (2 * this.y); double x2 = pow(L, 2) - 2 * this.x; return new Pt(x2, L * (this.x - x2) - this.y); }   Pt neg() { return new Pt(this.x, -this.y); }   Pt plus(Pt q) { if (this.x == q.x && this.y == q.y) return dbl();   if (isZero()) return q;   if (q.isZero()) return this;   double L = (q.y - this.y) / (q.x - this.x); double xx = pow(L, 2) - this.x - q.x; return new Pt(xx, L * (this.x - xx) - this.y); }   Pt mult(int n) { Pt r = Pt.zero(); Pt p = this; for (int i = 1; i <= n; i <<= 1) { if ((i & n) != 0) r = r.plus(p); p = p.dbl(); } return r; }   @Override public String toString() { if (isZero()) return "Zero"; return String.format(Locale.US, "(%.3f,%.3f)", this.x, this.y); } }
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#JSON
JSON
{"fruits" : { "apple" : null, "banana" : null, "cherry" : null } {"fruits" : { "apple" : 0, "banana" : 1, "cherry" : 2 }
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#Julia
Julia
  @enum Fruits APPLE BANANA CHERRY  
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#Kotlin
Kotlin
// version 1.0.5-2   enum class Animals { CAT, DOG, ZEBRA }   enum class Dogs(val id: Int) { BULLDOG(1), TERRIER(2), WOLFHOUND(4) }   fun main(args: Array<String>) { for (value in Animals.values()) println("${value.name.padEnd(5)} : ${value.ordinal}") println() for (value in Dogs.values()) println("${value.name.padEnd(9)} : ${value.id}") }
http://rosettacode.org/wiki/Elementary_cellular_automaton/Random_Number_Generator
Elementary cellular automaton/Random Number Generator
Rule 30 is considered to be chaotic enough to generate good pseudo-random numbers. As a matter of fact, rule 30 is used by the Mathematica software for its default random number generator. Steven Wolfram's recommendation for random number generation from rule 30 consists in extracting successive bits in a fixed position in the array of cells, as the automaton changes state. The purpose of this task is to demonstrate this. With the code written in the parent task, which you don't need to re-write here, show the ten first bytes that emerge from this recommendation. To be precise, you will start with a state of all cells but one equal to zero, and you'll follow the evolution of the particular cell whose state was initially one. Then you'll regroup those bits by packets of eight, reconstituting bytes with the first bit being the most significant. You can pick which ever length you want for the initial array but it should be visible in the code so that your output can be reproduced with an other language. For extra-credits, you will make this algorithm run as fast as possible in your language, for instance with an extensive use of bitwise logic. Reference Cellular automata: Is Rule 30 random? (PDF).
#Perl
Perl
package Automaton { sub new { my $class = shift; my $rule = [ reverse split //, sprintf "%08b", shift ]; return bless { rule => $rule, cells => [ @_ ] }, $class; } sub next { my $this = shift; my @previous = @{$this->{cells}}; $this->{cells} = [ @{$this->{rule}}[ map { 4*$previous[($_ - 1) % @previous] + 2*$previous[$_] + $previous[($_ + 1) % @previous] } 0 .. @previous - 1 ] ]; return $this; } use overload q{""} => sub { my $this = shift; join '', map { $_ ? '#' : ' ' } @{$this->{cells}} }; }   my $a = Automaton->new(30, 1, map 0, 1 .. 100);   for my $n (1 .. 10) { my $sum = 0; for my $b (1 .. 8) { $sum = $sum * 2 + $a->{cells}[0]; $a->next; } print $sum, $n == 10 ? "\n" : " "; }
http://rosettacode.org/wiki/Empty_string
Empty string
Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Arturo
Arturo
s: ""   if empty? s -> print "the string is empty" if 0 = size s -> print "yes, the string is empty"   s: "hello world"   if not? empty? s -> print "the string is not empty" if 0 < size s -> print "no, the string is not empty"
http://rosettacode.org/wiki/Empty_string
Empty string
Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Asymptote
Asymptote
string c; //implicitly assigned an empty string if (length(c) == 0) { write("Empty string"); } else { write("Non empty string"); }   string s = ""; //explicitly assigned an empty string if (s == "") { write("Empty string"); } if (s != "") { write("Non empty string"); }   string t = "not empty"; if (t != "") { write("Non empty string"); } else { write("Empty string"); }
http://rosettacode.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm
Elliptic Curve Digital Signature Algorithm
Elliptic curves. An elliptic curve E over ℤp (p ≥ 5) is defined by an equation of the form y^2 = x^3 + ax + b, where a, b ∈ ℤp and the discriminant ≢ 0 (mod p), together with a special point 𝒪 called the point at infinity. The set E(ℤp) consists of all points (x, y), with x, y ∈ ℤp, which satisfy the above defining equation, together with 𝒪. There is a rule for adding two points on an elliptic curve to give a third point. This addition operation and the set of points E(ℤp) form a group with identity 𝒪. It is this group that is used in the construction of elliptic curve cryptosystems. The addition rule — which can be explained geometrically — is summarized as follows: 1. P + 𝒪 = 𝒪 + P = P for all P ∈ E(ℤp). 2. If P = (x, y) ∈ E(ℤp), then inverse -P = (x,-y), and P + (-P) = 𝒪. 3. Let P = (xP, yP) and Q = (xQ, yQ), both ∈ E(ℤp), where P ≠ -Q. Then R = P + Q = (xR, yR), where xR = λ^2 - xP - xQ yR = λ·(xP - xR) - yP, with λ = (yP - yQ) / (xP - xQ) if P ≠ Q, (3·xP·xP + a) / 2·yP if P = Q (point doubling). Remark: there already is a task page requesting “a simplified (without modular arithmetic) version of the elliptic curve arithmetic”. Here we do add modulo operations. If also the domain is changed from reals to rationals, the elliptic curves are no longer continuous but break up into a finite number of distinct points. In that form we use them to implement ECDSA: Elliptic curve digital signature algorithm. A digital signature is the electronic analogue of a hand-written signature that convinces the recipient that a message has been sent intact by the presumed sender. Anyone with access to the public key of the signer may verify this signature. Changing even a single bit of a signed message will cause the verification procedure to fail. ECDSA key generation. Party A does the following: 1. Select an elliptic curve E defined over ℤp.  The number of points in E(ℤp) should be divisible by a large prime r. 2. Select a base point G ∈ E(ℤp) of order r (which means that rG = 𝒪). 3. Select a random integer s in the interval [1, r - 1]. 4. Compute W = sG.  The public key is (E, G, r, W), the private key is s. ECDSA signature computation. To sign a message m, A does the following: 1. Compute message representative f = H(m), using a cryptographic hash function.  Note that f can be greater than r but not longer (measuring bits). 2. Select a random integer u in the interval [1, r - 1]. 3. Compute V = uG = (xV, yV) and c ≡ xV mod r  (goto (2) if c = 0). 4. Compute d ≡ u^-1·(f + s·c) mod r  (goto (2) if d = 0).  The signature for the message m is the pair of integers (c, d). ECDSA signature verification. To verify A's signature, B should do the following: 1. Obtain an authentic copy of A's public key (E, G, r, W).  Verify that c and d are integers in the interval [1, r - 1]. 2. Compute f = H(m) and h ≡ d^-1 mod r. 3. Compute h1 ≡ f·h mod r and h2 ≡ c·h mod r. 4. Compute h1G + h2W = (x1, y1) and c1 ≡ x1 mod r.  Accept the signature if and only if c1 = c. To be cryptographically useful, the parameter r should have at least 250 bits. The basis for the security of elliptic curve cryptosystems is the intractability of the elliptic curve discrete logarithm problem (ECDLP) in a group of this size: given two points G, W ∈ E(ℤp), where W lies in the subgroup of order r generated by G, determine an integer k such that W = kG and 0 ≤ k < r. Task. The task is to write a toy version of the ECDSA, quasi the equal of a real-world implementation, but utilizing parameters that fit into standard arithmetic types. To keep things simple there's no need for key export or a hash function (just a sample hash value and a way to tamper with it). The program should be lenient where possible (for example: if it accepts a composite modulus N it will either function as expected, or demonstrate the principle of elliptic curve factorization) — but strict where required (a point G that is not on E will always cause failure). Toy ECDSA is of course completely useless for its cryptographic purpose. If this bothers you, please add a multiple-precision version. Reference. Elliptic curves are in the IEEE Std 1363-2000 (Standard Specifications for Public-Key Cryptography), see: 7. Primitives based on the elliptic curve discrete logarithm problem (p. 27ff.) 7.1 The EC setting 7.1.2 EC domain parameters 7.1.3 EC key pairs 7.2 Primitives 7.2.7 ECSP-DSA (p. 35) 7.2.8 ECVP-DSA (p. 36) Annex A. Number-theoretic background A.9 Elliptic curves: overview (p. 115) A.10 Elliptic curves: algorithms (p. 121)
#Wren
Wren
import "/dynamic" for Struct import "/big" for BigInt import "/fmt" for Fmt import "/math" for Boolean import "random" for Random   var rand = Random.new()   // rational ec point: x and y are BigInts var Epnt = Struct.create("Epnt", ["x", "y"])   // elliptic curve parameters: N is a BigInt, G is an Epnt, rest are integral Nums var Curve = Struct.create("Curve", ["a", "b", "N", "G", "r"])   // signature pair: a and b are integral Nums var Pair = Struct.create("Pair", ["a", "b"])   // maximum modulus var mxN = 1073741789   // max order G = mxN + 65536 var mxr = 1073807325   // symbolic infinity var inf = BigInt.new(-2147483647)   // single global curve var e = Curve.new(0, 0, BigInt.zero, Epnt.new(inf, BigInt.zero), 0)   // impossible inverse mod N var inverr = false   // return mod(v^-1, u) var exgcd = Fn.new { |v, u| var r = 0 var s = 1 if (v < 0) v = v + u while (v != 0) { var q = (u / v).truncate var t = u - q * v u = v v = t t = r - q * s r = s s = t } if (u != 1) { System.print(" impossible inverse mod N, gcd = %(u)") inverr = true } return r }   // returns mod(a, N), a is a BigInt var modn = Fn.new { |a| var b = a.copy() b = b % e.N if (b < 0) b = b + e.N return b }   // returns mod(a, r), a is a BigInt var modr = Fn.new { |a| var b = a.copy() b = b % e.r if (b < 0) b = b + e.r return b }   // returns the discriminant of E var disc = Fn.new { var a = BigInt.new(e.a) var b = BigInt.new(e.b) var c = modn.call(a * modn.call(a * a)) * 4 return modn.call((c + modn.call(b * b) * 27) * (-16)).toSmall }   // return true if P is 'zero' point (at inf, 0) var isZero = Fn.new { |p| p.x == inf && p.y == 0 }   // return true if P is on curve E var isOn = Fn.new { |p| var r = 0 var s = 0 if (!isZero.call(p)) { r = modn.call(p.x * modn.call(p.x * p.x + e.a) + e.b).toSmall s = modn.call(p.y * p.y).toSmall } return r == s }   // full ec point addition var padd = Fn.new { |p, q| var la = BigInt.zero var t = BigInt.zero if (isZero.call(p)) return Epnt.new(q.x, q.y) if (isZero.call(q)) return Epnt.new(p.x, p.y) if (p.x != q.x) { // R = P + Q t = p.y - q.y la = modn.call(t * exgcd.call((p.x - q.x).toSmall, e.N.toSmall)) } else { // P = Q, R = 2P if (p.y == q.y && p.y != 0) { t = modn.call(modn.call(p.x * p.x) * 3 + e.a) la = modn.call(t * exgcd.call((p.y * 2).toSmall, e.N.toSmall)) } else { return Epnt.new(inf, BigInt.zero) // P = -Q, R = O } } if (inverr) return Epnt.new(inf, BigInt.zero) t = modn.call(la * la - p.x - q.x) return Epnt.new(t, modn.call(la * (p.x - t) - p.y)) }   // R = multiple kP var pmul = Fn.new { |p, k| var s = Epnt.new(inf, BigInt.zero) var q = Epnt.new(p.x, p.y) while (k != 0) { if (k % 2 == 1) s = padd.call(s, q) if (inverr) { s.x = inf s.y = BigInt.zero break } q = padd.call(q, q) k = (k/2).floor } return s }   // print point P with prefix f var pprint = Fn.new { |f, p| var y = p.y if (isZero.call(p)) { Fmt.print("$s (0)", f) } else { if (y > e.N - y) y = y - e.N Fmt.print("$s ($i, $i)", f, p.x, y) } }   // initialize elliptic curve var ellinit = Fn.new { |i| var a = BigInt.new(i[0]) var b = BigInt.new(i[1]) e.N = BigInt.new(i[2]) inverr = false if (e.N < 5 || e.N > mxN) return false e.a = modn.call(a).toSmall e.b = modn.call(b).toSmall e.G.x = modn.call(BigInt.new(i[3])) e.G.y = modn.call(BigInt.new(i[4])) e.r = i[5] if (e.r < 5 || e.r > mxr) return false Fmt.write("\nE: y^2 = x^3 + $ix + $i", a, b) Fmt.print(" (mod $i)", e.N) pprint.call("base point G", e.G) Fmt.print("order(G, E) = $d", e.r) return true }   // signature primitive var signature = Fn.new { |s, f| var c var d var u var u1 var sg = Pair.new(0, 0) var V System.print("\nsignature computation") while (true) { while (true) { u = 1 + (rand.float() * (e.r - 1)).truncate V = pmul.call(e.G, u) c = modr.call(V.x).toSmall if (c != 0) break } u1 = exgcd.call(u, e.r) d = modr.call((modr.call(s * c) + f) * u1).toSmall if (d != 0) break } Fmt.print("one-time u = $d", u) pprint.call("V = uG", V) sg.a = c sg.b = d return sg }   // verification primitive var verify = Fn.new { |W, f, sg| var c = sg.a var d = sg.b   // domain check var t = (c > 0) && (c < e.r) t = Boolean.and(t, d > 0 && d < e.r) if (!t) return false System.print("\nsignature verification") var h = BigInt.new(exgcd.call(d, e.r)) var h1 = modr.call(h * f).toSmall var h2 = modr.call(h * c).toSmall Fmt.print ("h1, h2 = $d, $d", h1, h2) var V = pmul.call(e.G, h1) var V2 = pmul.call(W, h2) pprint.call("h1G", V) pprint.call("h2W", V2) V = padd.call(V, V2) pprint.call("+ =", V) if (isZero.call(V)) return false var c1 = modr.call(V.x).toSmall Fmt.print("c' = $d", c1) return c1 == c }   var errmsg = Fn.new { System.print("invalid parameter set") System.print("_____________________") }   // digital signature on message hash f, error bit d var ec_dsa = Fn.new { |f, d| // parameter check var t = disc.call() == 0 t = Boolean.or(t, isZero.call(e.G)) var W = pmul.call(e.G, e.r) t = Boolean.or(t, !isZero.call(W)) t = Boolean.or(t, !isOn.call(e.G)) if (t) { errmsg.call() return } System.print("\nkey generation") var s = 1 + (rand.float() * (e.r - 1)).truncate W = pmul.call(e.G, s) Fmt.print("private key s = $d\n", s) pprint.call("public key W = sG", W)   // next highest power of 2 - 1 t = e.r var i = 1 while (i < 32) { t = t | (t >> i) i = i << 1 } while (f > t) f = f >> 1 Fmt.print("\naligned hash $x", f) var sg = signature.call(BigInt.new(s), f) if (inverr) { errmsg.call() return } Fmt.print("signature c, d = $d, $d", sg.a, sg.b) if (d > 0) { while (d > t) d = d >> 1 f = f ^ d Fmt.print("\ncorrupted hash $x", f) } t = verify.call(W, f, sg) if (inverr) { errmsg.call() return } if (t) { System.print("Valid\n_____") } else { System.print("invalid\n_______") } }   // Test vectors: elliptic curve domain parameters, // short Weierstrass model y^2 = x^3 + ax + b (mod N) var sets = [ // a, b, modulus N, base point G, order(G, E), cofactor [355, 671, 1073741789, 13693, 10088, 1073807281], [ 0, 7, 67096021, 6580, 779, 16769911], // 4 [ -3, 1, 877073, 0, 1, 878159], [ 0, 14, 22651, 63, 30, 151], // 151 [ 3, 2, 5, 2, 1, 5],   // ecdsa may fail if... // the base point is of composite order [ 0, 7, 67096021, 2402, 6067, 33539822], // 2 // the given order is a multiple of the true order [ 0, 7, 67096021, 6580, 779, 67079644], // 1 // the modulus is not prime (deceptive example) [ 0, 7, 877069, 3, 97123, 877069], // fails if the modulus divides the discriminant [ 39, 387, 22651, 95, 27, 22651] ] // Digital signature on message hash f, // set d > 0 to simulate corrupted data var f = 0x789abcde var d = 0   for (s in sets) { if (ellinit.call(s)) { ec_dsa.call(f, d) } else { break } }
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.
#Elixir
Elixir
path = hd(System.argv) IO.puts File.dir?(path) and Enum.empty?( File.ls!(path) )
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.
#Erlang
Erlang
3> {ok, []} = file:list_dir_all("/usr"). ** exception error: no match of right hand side value {ok,["X11R6","X11","standalone","share","sbin","local", "libexec","lib","bin"]} 4> {ok, []} = file:list_dir_all("/asd"). ** exception error: no match of right hand side value {error,enoent} 5> {ok, []} = file:list_dir_all("./empty"). {ok,[]}
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.
#F.23
F#
open System.IO let isEmptyDirectory x = (Directory.GetFiles x).Length = 0 && (Directory.GetDirectories x).Length = 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.
#Factor
Factor
USE: io.directories : empty-directory? ( path -- ? ) directory-entries empty? ;
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#AmigaE
AmigaE
PROC main() ENDPROC
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#AppleScript
AppleScript
return
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.
#PicoLisp
PicoLisp
: (de pi () 4) -> pi   : (pi) -> 4
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.
#PL.2FI
PL/I
*process source attributes xref; constants: Proc Options(main); Dcl three Bin Fixed(15) Value(3); Put Skip List(1/three); Put Skip List(1/3); End;
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.
#PowerBASIC
PowerBASIC
$me = "myname" %age = 35
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.
#PureBasic
PureBasic
#i_Const1 = 11 #i_Const2 = 3.1415 #i_Const3 = "A'm a string"
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
#CLU
CLU
% NOTE: when compiling with Portable CLU, % this program needs to be merged with 'useful.lib' to get log() % % pclu -merge $CLUHOME/lib/useful.lib -compile entropy.clu   shannon = proc (s: string) returns (real)  % find the frequency of each character freq: array[int] := array[int]$fill(0, 256, 0) for c: char in string$chars(s) do i: int := char$c2i(c) freq[i] := freq[i] + 1 end    % calculate the component for each character h: real := 0.0 rlen: real := real$i2r(string$size(s)) for i: int in array[int]$indexes(freq) do if freq[i] ~= 0 then f: real := real$i2r(freq[i]) / rlen h := h - f * log(f) / log(2.0) end end return (h) end shannon   start_up = proc () po: stream := stream$primary_output() stream$putl(po, f_form(shannon("1223334444"), 1, 6)) end start_up
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
#CoffeeScript
CoffeeScript
entropy = (s) -> freq = (s) -> result = {} for ch in s.split "" result[ch] ?= 0 result[ch]++ return result   frq = freq s n = s.length ((frq[f]/n for f of frq).reduce ((e, p) -> e - p * Math.log(p)), 0) * Math.LOG2E   console.log "The entropy of the string '1223334444' is #{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
#CLU
CLU
halve = proc (n: int) returns (int) return(n/2) end halve   double = proc (n: int) returns (int) return(n*2) end double   even = proc (n: int) returns (bool) return(n//2 = 0) end even   e_mul = proc (a, b: int) returns (int) total: int := 0   while (a > 0) do if ~even(a) then total := total + b end a := halve(a) b := double(b) end   return(total) end e_mul   start_up = proc () po: stream := stream$primary_output() stream$putl(po, int$unparse(e_mul(17, 34))) end start_up
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.
#J
J
equilidx=: +/\ I.@:= +/\.
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.
#Java
Java
  public class Equlibrium { public static void main(String[] args) { int[] sequence = {-7, 1, 5, 2, -4, 3, 0}; equlibrium_indices(sequence); }   public static void equlibrium_indices(int[] sequence){ //find total sum int totalSum = 0; for (int n : sequence) { totalSum += n; } //compare running sum to remaining sum to find equlibrium indices int runningSum = 0; for (int i = 0; i < sequence.length; i++) { int n = sequence[i]; if (totalSum - runningSum - n == runningSum) { System.out.println(i); } 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
#min
min
$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
#Modula-3
Modula-3
MODULE EnvVars EXPORTS Main;   IMPORT IO, Env;   VAR k, v: TEXT;   BEGIN IO.Put(Env.Get("HOME") & "\n");   FOR i := 0 TO Env.Count - 1 DO Env.GetNth(i, k, v); IO.Put(k & " = " & v & "\n") END END EnvVars.
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
#MUMPS
MUMPS
Set X=$ZF(-1,"show logical") Set X=$ZF(-1,"show symbol")
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
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   runSample(arg) return   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method sysEnvironment(vn = '') public static if vn.length > 0 then do envName = vn envValu = System.getenv(envName) if envValu = null then envValu = '' say envName '=' envValu end else do envVars = System.getenv() key = String loop key over envVars.keySet() envName = key envValu = String envVars.get(key) say envName '=' envValu end key end return   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method sysProperties(vn = '') public static if vn.length > 0 then do propName = vn propValu = System.getProperty(propName) if propValu = null then propValu = '' say propName '=' propValu end else do sysProps = System.getProperties() key = String loop key over sysProps.keySet() propName = key propValu = sysProps.getProperty(key) say propName '=' propValu end key end return   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method runSample(arg) public static parse arg ev pv . if ev = '' then ev = 'CLASSPATH' if pv = '' then pv = 'java.class.path' say '-'.left(80, '-').overlay(' Environment "'ev'" ', 5) sysEnvironment(ev) say '-'.left(80, '-').overlay(' Properties "'pv'" ', 5) sysProperties(pv) say say '-'.left(80, '-').overlay(' Environment ', 5) sysEnvironment() say '-'.left(80, '-').overlay(' Properties ', 5) sysProperties() say return  
http://rosettacode.org/wiki/Esthetic_numbers
Esthetic numbers
An esthetic number is a positive integer where every adjacent digit differs from its neighbour by 1. E.G. 12 is an esthetic number. One and two differ by 1. 5654 is an esthetic number. Each digit is exactly 1 away from its neighbour. 890 is not an esthetic number. Nine and zero differ by 9. These examples are nominally in base 10 but the concept extends easily to numbers in other bases. Traditionally, single digit numbers are included in esthetic numbers; zero may or may not be. For our purposes, for this task, do not include zero (0) as an esthetic number. Do not include numbers with leading zeros. Esthetic numbers are also sometimes referred to as stepping numbers. Task Write a routine (function, procedure, whatever) to find esthetic numbers in a given base. Use that routine to find esthetic numbers in bases 2 through 16 and display, here on this page, the esthectic numbers from index (base × 4) through index (base × 6), inclusive. (E.G. for base 2: 8th through 12th, for base 6: 24th through 36th, etc.) Find and display, here on this page, the base 10 esthetic numbers with a magnitude between 1000 and 9999. Stretch: Find and display, here on this page, the base 10 esthetic numbers with a magnitude between 1.0e8 and 1.3e8. Related task   numbers with equal rises and falls See also OEIS A033075 - Positive numbers n such that all pairs of consecutive decimal digits differ by 1 Numbers Aplenty - Esthetic numbers Geeks for Geeks - Stepping numbers
#Swift
Swift
extension Sequence { func take(_ n: Int) -> [Element] { var res = [Element]()   for el in self { guard res.count != n else { return res }   res.append(el) }   return res } }   extension String { func isEsthetic(base: Int = 10) -> Bool { zip(dropFirst(0), dropFirst()) .lazy .allSatisfy({ abs(Int(String($0.0), radix: base)! - Int(String($0.1), radix: base)!) == 1 }) } }   func getEsthetics(from: Int, to: Int, base: Int = 10) -> [String] { guard base >= 2, to >= from else { return [] }   var start = "" var end = ""   repeat { if start.count & 1 == 1 { start += "0" } else { start += "1" } } while Int(start, radix: base)! < from   let digiMax = String(base - 1, radix: base) let lessThanDigiMax = String(base - 2, radix: base) var count = 0   repeat { if count != base - 1 { end += String(count + 1, radix: base) count += 1 } else { if String(end.last!) == digiMax { end += lessThanDigiMax } else { end += digiMax } } } while Int(end, radix: base)! < to   if Int(start, radix: base)! >= Int(end, radix: base)! { return [] }   var esthetics = [Int]()   func shimmer(_ n: Int, _ m: Int, _ i: Int) { if (n...m).contains(i) { esthetics.append(i) } else if i == 0 || i > m { return }   let d = i % base let i1 = i &* base &+ d &- 1 let i2 = i1 &+ 2   if (i1 < i || i2 < i) { // overflow return }   switch d { case 0: shimmer(n, m, i2) case base-1: shimmer(n, m, i1) case _: shimmer(n, m, i1) shimmer(n, m, i2) } }   for digit in 0..<base { shimmer(Int(start, radix: base)!, Int(end, radix: base)!, digit) }   return esthetics.filter({ $0 <= to }).map({ String($0, radix: base) }) }   for base in 2...16 { let esthetics = (0...) .lazy .map({ String($0, radix: base) }) .filter({ $0.isEsthetic(base: base) }) .dropFirst(base * 4) .take((base * 6) - (base * 4) + 1)   print("Base \(base) esthetics from \(base * 4) to \(base * 6)") print(esthetics) print() }   let base10Esthetics = (1000...9999).filter({ String($0).isEsthetic() })   print("\(base10Esthetics.count) esthetics between 1000 and 9999:") print(base10Esthetics) print()   func printSlice(of array: [String]) { print(array.take(5)) print("...") print(Array(array.lazy.reversed().take(5).reversed())) print("\(array.count) total\n") }   print("Esthetics between \(Int(1e8)) and \(13 * Int(1e7)):") printSlice(of: getEsthetics(from: Int(1e8), to: 13 * Int(1e7)))   print("Esthetics between \(Int(1e11)) and \(13 * Int(1e10))") printSlice(of: getEsthetics(from: Int(1e11), to: 13 * Int(1e10)))   print("Esthetics between \(Int(1e14)) and \(13 * Int(1e13)):") printSlice(of: getEsthetics(from: Int(1e14), to: 13 * Int(1e13)))   print("Esthetics between \(Int(1e17)) and \(13 * Int(1e16)):") printSlice(of: getEsthetics(from: Int(1e17), to: 13 * Int(1e16)))
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.
#Go
Go
package main   import ( "fmt" "log" )   func main() { fmt.Println(eulerSum()) }   func eulerSum() (x0, x1, x2, x3, y int) { var pow5 [250]int for i := range pow5 { pow5[i] = i * i * i * i * i } for x0 = 4; x0 < len(pow5); x0++ { for x1 = 3; x1 < x0; x1++ { for x2 = 2; x2 < x1; x2++ { for x3 = 1; x3 < x2; x3++ { sum := pow5[x0] + pow5[x1] + pow5[x2] + pow5[x3] for y = x0 + 1; y < len(pow5); y++ { if sum == pow5[y] { return } } } } } } log.Fatal("no solution") return }
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#Niue
Niue
[ dup 1 > [ dup 1 - factorial * ] when ] 'factorial ;   ( test ) 4 factorial . ( => 24 ) 10 factorial . ( => 3628800 )
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.
#COBOL
COBOL
IF FUNCTION REM(Num, 2) = 0 DISPLAY Num " is even." ELSE DISPLAY Num " is odd." END-IF
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.
#CoffeeScript
CoffeeScript
isEven = (x) -> !(x%2)
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.
#Rust
Rust
fn header() { print!(" Time: "); for t in (0..100).step_by(10) { print!(" {:7}", t); } println!(); }   fn analytic() { print!("Analytic: "); for t in (0..=100).step_by(10) { print!(" {:7.3}", 20.0 + 80.0 * (-0.07 * f64::from(t)).exp()); } println!(); }   fn euler<F: Fn(f64) -> f64>(f: F, mut y: f64, step: usize, end: usize) { print!(" Step {:2}: ", step); for t in (0..=end).step_by(step) { if t % 10 == 0 { print!(" {:7.3}", y); } y += step as f64 * f(y); } println!(); }   fn main() { header(); analytic(); for &i in &[2, 5, 10] { euler(|temp| -0.07 * (temp - 20.0), 100.0, i, 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.
#Scala
Scala
  object App{   def main(args : Array[String]) = {   def cooling( step : Int ) = { eulerStep( (step , y) => {-0.07 * (y - 20)} , 100.0,0,100,step) } cooling(10) cooling(5) cooling(2) } def eulerStep( func : (Int,Double) => Double,y0 : Double, begin : Int, end : Int , step : Int) = {   println("Step size: %s".format(step))   var current : Int = begin var y : Double = y0 while( current <= end){ println( "%d %.5f".format(current,y)) current += step y += step * func(current,y) }   println("DONE") }   }  
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
#Kotlin
Kotlin
// version 2.0   fun binomial(n: Int, k: Int) = when { n < 0 || k < 0 -> throw IllegalArgumentException("negative numbers not allowed") n == k -> 1L else -> { val kReduced = min(k, n - k) // minimize number of steps var result = 1L var numerator = n var denominator = 1 while (denominator <= kReduced) result = result * numerator-- / denominator++ result } }   fun main(args: Array<String>) { for (n in 0..14) { for (k in 0..n) print("%4d ".format(binomial(n, k))) println() } }
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).
#C
C
#include <stdio.h>   typedef unsigned uint; int is_prime(uint n) { if (!(n%2) || !(n%3)) return 0; uint p = 1; while(p*p < n) if (n%(p += 4) == 0 || n%(p += 2) == 0) return 0; return 1; }   uint reverse(uint n) { uint r; for (r = 0; n; n /= 10) r = r*10 + (n%10); return r; }   int is_emirp(uint n) { uint r = reverse(n); return r != n && is_prime(n) && is_prime(r); }   int main(int argc, char **argv) { uint x, c = 0; switch(argc) { // advanced args parsing case 1: for (x = 11; c < 20; x += 2) if (is_emirp(x)) printf(" %u", x), ++c; break;   case 2: for (x = 7701; x < 8000; x += 2) if (is_emirp(x)) printf(" %u", x); break;   default: for (x = 11; ; x += 2) if (is_emirp(x) && ++c == 10000) { printf("%u", x); break; } }   putchar('\n'); return 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).
#Julia
Julia
struct Point{T<:AbstractFloat} x::T y::T end Point{T}() where T<:AbstractFloat = Point{T}(Inf, Inf) Point() = Point{Float64}()   Base.show(io::IO, p::Point{T}) where T = iszero(p) ? print(io, "Zero{$T}") : @printf(io, "{%s}(%.3f, %.3f)", T, p.x, p.y) Base.copy(p::Point) = Point(p.x, p.y) Base.iszero(p::Point{T}) where T = p.x in (-Inf, Inf) Base.:-(p::Point) = Point(p.x, -p.y)   function dbl(p::Point{T}) where T iszero(p) && return p   L = 3p.x ^ 2 / 2p.y x = L ^ 2 - 2p.x y = L * (p.x - x) - p.y return Point{T}(x, y) end Base.:(==)(a::Point{T}, C::Point{T}) where T = a.x == C.x && a.y == C.y   function Base.:+(p::Point{T}, q::Point{T}) where T p == q && return dbl(p) iszero(p) && return q iszero(q) && return p   L = (q.y - p.y) / (q.x - p.x) x = L ^ 2 - p.x - q.x y = L * (p.x - x) - p.y return Point{T}(x, y) end function Base.:*(p::Point, n::Integer) r = Point() i = 1 while i ≤ n if i & n != 0 r += p end p = dbl(p) i <<= 1 end return r end Base.:*(n::Integer, p::Point) = p * n   const C = 7 function Point(y::AbstractFloat) n = y ^ 2 - C x = n ≥ 0 ? n ^ (1 / 3) : -((-n) ^ (1 / 3)) return Point{typeof(y)}(x, y) end   a = Point(1.0) b = Point(2.0) @show a b @show c = a + b @show d = -c @show c + d @show a + b + d @show 12345a
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).
#Kotlin
Kotlin
// version 1.1.4   const val C = 7   class Pt(val x: Double, val y: Double) { val zero get() = Pt(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY)   val isZero get() = x > 1e20 || x < -1e20   fun dbl(): Pt { if (isZero) return this val l = 3.0 * x * x / (2.0 * y) val t = l * l - 2.0 * x return Pt(t, l * (x - t) - y) }   operator fun unaryMinus() = Pt(x, -y)   operator fun plus(other: Pt): Pt { if (x == other.x && y == other.y) return dbl() if (isZero) return other if (other.isZero) return this val l = (other.y - y) / (other.x - x) val t = l * l - x - other.x return Pt(t, l * (x - t) - y) }   operator fun times(n: Int): Pt { var r: Pt = zero var p = this var i = 1 while (i <= n) { if ((i and n) != 0) r += p p = p.dbl() i = i shl 1 } return r }   override fun toString() = if (isZero) "Zero" else "(${"%.3f".format(x)}, ${"%.3f".format(y)})" }   fun Double.toPt() = Pt(Math.cbrt(this * this - C), this)   fun main(args: Array<String>) { val a = 1.0.toPt() val b = 2.0.toPt() val c = a + b val d = -c println("a = $a") println("b = $b") println("c = a + b = $c") println("d = -c = $d") println("c + d = ${c + d}") println("a + b + d = ${a + b + d}") println("a * 12345 = ${a * 12345}") }
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#Lingo
Lingo
-- parent script "Enumeration"   property ancestor   on new (me) data = [:] repeat with i = 2 to the paramCount data[param(i)] = i-1 end repeat me.ancestor = data return me end   on setAt (me) -- do nothing end   on setProp (me) -- do nothing end   on deleteAt (me) -- do nothing end   on deleteProp (me) -- do nothing end   on addProp (me) -- do nothing end
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#Lua
Lua
  local fruit = {apple = 0, banana = 1, cherry = 2}  
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#M2000_Interpreter
M2000 Interpreter
  Module Checkit { \\ need revision 15, version 9.4 Enum Fruit {apple, banana, cherry} Enum Fruit2 {apple2=10, banana2=20, cherry2=30} Print apple, banana, cherry Print apple2, banana2, cherry2 Print Len(apple)=0 Print Len(banana)=1 Print Len(cherry)=2 Print Len(cherry2)=2, Cherry2=30, Type$(Cherry2)="Fruit2"   k=each(Fruit) While k { \\ name of variable, value, length from first (0, 1, 2) Print Eval$(k), Eval(k), k^ } m=apple Print Eval$(m)="apple" Print Eval(m)=m m++ Print Eval$(m)="banana" Try { \\ error, m is an object m=100 } Try { \\ error not the same type m=apple2 } Try { \\ read only can't change apple2++ } m++ Print Eval$(m)="cherry", m k=Each(Fruit2 end to start) While k { Print Eval$(k), Eval(k) , k^ CheckByValue(Eval(k)) } m2=apple2 Print "-------------------------" CheckByValue(m2) CheckByReference(&m2) Print m2   Sub CheckByValue(z as Fruit2) Print Eval$(z), z End Sub   Sub CheckByReference(&z as Fruit2) z++ Print Eval$(z), z End Sub } Checkit  
http://rosettacode.org/wiki/Elementary_cellular_automaton/Random_Number_Generator
Elementary cellular automaton/Random Number Generator
Rule 30 is considered to be chaotic enough to generate good pseudo-random numbers. As a matter of fact, rule 30 is used by the Mathematica software for its default random number generator. Steven Wolfram's recommendation for random number generation from rule 30 consists in extracting successive bits in a fixed position in the array of cells, as the automaton changes state. The purpose of this task is to demonstrate this. With the code written in the parent task, which you don't need to re-write here, show the ten first bytes that emerge from this recommendation. To be precise, you will start with a state of all cells but one equal to zero, and you'll follow the evolution of the particular cell whose state was initially one. Then you'll regroup those bits by packets of eight, reconstituting bytes with the first bit being the most significant. You can pick which ever length you want for the initial array but it should be visible in the code so that your output can be reproduced with an other language. For extra-credits, you will make this algorithm run as fast as possible in your language, for instance with an extensive use of bitwise logic. Reference Cellular automata: Is Rule 30 random? (PDF).
#Phix
Phix
with javascript_semantics --string s = ".........#.........", --(original) string s = "...............................#"& "................................", --string s = "#"&repeat('.',100), -- [2] t=s, r = "........" integer rule = 30, k, l = length(s), w = 0 for i=1 to 8 do r[i] = iff(mod(rule,2)?'#':'.') rule = floor(rule/2) end for sequence res = {} for i=0 to 80 do w = w*2 + (s[32]='#') -- w = w*2 + (s[1]='#') -- [2] if mod(i+1,8)=0 then res&=w w=0 end if for j=1 to l do k = (s[iff(j=1?l:j-1)]='#')*4 + (s[ j ]='#')*2 + (s[iff(j=l?1:j+1)]='#')+1 t[j] = r[k] end for s = t end for pp(res)
http://rosettacode.org/wiki/Elementary_cellular_automaton/Random_Number_Generator
Elementary cellular automaton/Random Number Generator
Rule 30 is considered to be chaotic enough to generate good pseudo-random numbers. As a matter of fact, rule 30 is used by the Mathematica software for its default random number generator. Steven Wolfram's recommendation for random number generation from rule 30 consists in extracting successive bits in a fixed position in the array of cells, as the automaton changes state. The purpose of this task is to demonstrate this. With the code written in the parent task, which you don't need to re-write here, show the ten first bytes that emerge from this recommendation. To be precise, you will start with a state of all cells but one equal to zero, and you'll follow the evolution of the particular cell whose state was initially one. Then you'll regroup those bits by packets of eight, reconstituting bytes with the first bit being the most significant. You can pick which ever length you want for the initial array but it should be visible in the code so that your output can be reproduced with an other language. For extra-credits, you will make this algorithm run as fast as possible in your language, for instance with an extensive use of bitwise logic. Reference Cellular automata: Is Rule 30 random? (PDF).
#Python
Python
from elementary_cellular_automaton import eca, eca_wrap   def rule30bytes(lencells=100): cells = '1' + '0' * (lencells - 1) gen = eca(cells, 30) while True: yield int(''.join(next(gen)[0] for i in range(8)), 2)   if __name__ == '__main__': print([b for i,b in zip(range(10), rule30bytes())])
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
#AutoHotkey
AutoHotkey
;; Traditional ; Assign an empty string: var = ; Check that a string is empty: If var = MsgBox the var is empty ; Check that a string is not empty If var != Msgbox the var is not empty     ;; Expression mode: ; Assign an empty string: var := "" ; Check that a string is empty: If (var = "") MsgBox the var is empty ; Check that a string is not empty If (var != "") Msgbox the var is not empty
http://rosettacode.org/wiki/Empty_string
Empty string
Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Avail
Avail
emptyStringVar : string := ""; Assert: emptyStringVar = ""; Assert: emptyStringVar = <>; Assert: emptyStringVar is empty; Assert: |emptyStringVar| = 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.
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   #Include "dir.bi"   Function IsDirEmpty(dirPath As String) As Boolean Err = 0 ' check dirPath is a valid directory Dim As String fileName = Dir(dirPath, fbDirectory) If Len(fileName) = 0 Then Err = 1000 ' dirPath is not a valid path Return False End If ' now check if there are any files/subdirectories in it other than . and .. Dim fileSpec As String = dirPath + "\*.*" Const attribMask = fbNormal Or fbHidden Or fbSystem Or fbDirectory Dim outAttrib As UInteger fileName = Dir(fileSpec, attribMask, outAttrib) ' get first file Do If fileName <> ".." AndAlso fileName <> "." Then If Len(fileName) = 0 Then Return True Exit Do End If fileName = Dir ' get next file Loop Return False End Function   Dim outAttrib As UInteger Dim dirPath As String = "c:\freebasic\docs" ' known to be empty Dim empty As Boolean = IsDirEmpty(dirPath) Dim e As Long = Err If e = 1000 Then Print "'"; dirPath; "' is not a valid directory" End End If If empty Then Print "'"; dirPath; "' is empty" Else Print "'"; dirPath; "' is not empty" End If Print Print "Press any key to quit" Sleep
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.
#Gambas
Gambas
Public Sub Main() Dim sFolder As String = User.home &/ "Rosetta" Dim sDir As String[] = Dir(sFolder) Dim sTemp As String Dim sOutput As String = sfolder & " is NOT empty"   Try sTemp = sDir[0] If Error Then sOutput = sfolder & " is empty"   Print sOutput   End
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Argile
Argile
 
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#ARM_Assembly
ARM Assembly
.text .global _start _start: mov r0, #0 mov r7, #1 svc #0
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.
#Python
Python
>>> s = "Hello" >>> s[0] = "h"   Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> s[0] = "h" TypeError: 'str' object does not support item assignment
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.
#Racket
Racket
(struct coordinate (x y)) ; immutable struct
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.
#Raku
Raku
constant $pi = 3.14159; constant $msg = "Hello World";   constant @arr = (1, 2, 3, 4, 5);
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.
#REXX
REXX
/*REXX program emulates immutable variables (as a post-computational check). */ call immutable '$=1' /* ◄─── assigns an immutable variable. */ call immutable ' pi = 3.14159' /* ◄─── " " " " */ call immutable 'radius= 2*pi/4 ' /* ◄─── " " " " */ call immutable ' r=13/2 ' /* ◄─── " " " " */ call immutable ' d=0002 * r' /* ◄─── " " " " */ call immutable ' f.1 = 12**2 ' /* ◄─── " " " " */   say ' $ =' $ /*show the variable, just to be sure. */ say ' pi =' pi /* " " " " " " " */ say ' radius =' radius /* " " " " " " " */ say ' r =' r /* " " " " " " " */ say ' d =' d /* " " " " " " " */   do radius=10 to -10 by -1 /*perform some faux important stuff. */ circum=$*pi*2*radius /*some kind of impressive calculation. */ end /*k*/ /* [↑] that should do it, by gum. */ call immutable /* ◄═══ see if immutable variables OK. */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ immutable: if symbol('immutable.0')=='LIT' then immutable.0= /*1st time see immutable? */ if arg()==0 then do /* [↓] chk all immutables*/ do __=1 for words(immutable.0); _=word(immutable.0,__) if value(_)==value('IMMUTABLE.!'_) then iterate /*same?*/ call ser -12, 'immutable variable ' _ " compromised." end /*__*/ /* [↑] Error? ERRmsg, exit*/ return 0 /*return and indicate A-OK.*/ end /* [↓] immutable must have =*/ if pos('=',arg(1))==0 then call ser -4, "no equal sign in assignment:" arg(1) parse arg _ '=' __; upper _; _=space(_) /*purify variable name.*/ if symbol("_")=='BAD' then call ser -8,_ "isn't a valid variable symbol." immutable.0=immutable.0 _ /*add immutable var to list.*/ interpret '__='__; call value _,__ /*assign value to a variable*/ call value 'IMMUTABLE.!'_,__ /*assign value to bkup var. */ return words(immutable.0) /*return number immutables. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ ser: say; say '***error***' arg(2); say; exit arg(1) /*error msg.*/
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
#Common_Lisp
Common Lisp
(defun entropy (string) (let ((table (make-hash-table :test 'equal)) (entropy 0)) (mapc (lambda (c) (setf (gethash c table) (+ (gethash c table 0) 1))) (coerce string 'list)) (maphash (lambda (k v) (decf entropy (* (/ v (length input-string)) (log (/ v (length input-string)) 2)))) 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
#COBOL
COBOL
*>* Ethiopian multiplication   IDENTIFICATION DIVISION. PROGRAM-ID. ethiopian-multiplication. DATA DIVISION. LOCAL-STORAGE SECTION. 01 l PICTURE 9(10) VALUE 17. 01 r PICTURE 9(10) VALUE 34. 01 ethiopian-multiply PICTURE 9(20). 01 product PICTURE 9(20). PROCEDURE DIVISION. CALL "ethiopian-multiply" USING BY CONTENT l, BY CONTENT r, BY REFERENCE ethiopian-multiply END-CALL DISPLAY ethiopian-multiply END-DISPLAY MULTIPLY l BY r GIVING product END-MULTIPLY DISPLAY product END-DISPLAY STOP RUN. END PROGRAM ethiopian-multiplication.   IDENTIFICATION DIVISION. PROGRAM-ID. ethiopian-multiply. DATA DIVISION. LOCAL-STORAGE SECTION. 01 evenp PICTURE 9. 88 even VALUE 1. 88 odd VALUE 0. LINKAGE SECTION. 01 l PICTURE 9(10). 01 r PICTURE 9(10). 01 product PICTURE 9(20) VALUE ZERO. PROCEDURE DIVISION using l, r, product. MOVE ZEROES TO product PERFORM UNTIL l EQUAL ZERO CALL "evenp" USING BY CONTENT l, BY REFERENCE evenp END-CALL IF odd ADD r TO product GIVING product END-ADD END-IF CALL "halve" USING BY CONTENT l, BY REFERENCE l END-CALL CALL "twice" USING BY CONTENT r, BY REFERENCE r END-CALL END-PERFORM GOBACK. END PROGRAM ethiopian-multiply.   IDENTIFICATION DIVISION. PROGRAM-ID. halve. DATA DIVISION. LOCAL-STORAGE SECTION. LINKAGE SECTION. 01 n PICTURE 9(10). 01 m PICTURE 9(10). PROCEDURE DIVISION USING n, m. DIVIDE n BY 2 GIVING m END-DIVIDE GOBACK. END PROGRAM halve.   IDENTIFICATION DIVISION. PROGRAM-ID. twice. DATA DIVISION. LOCAL-STORAGE SECTION. LINKAGE SECTION. 01 n PICTURE 9(10). 01 m PICTURE 9(10). PROCEDURE DIVISION USING n, m. MULTIPLY n by 2 GIVING m END-MULTIPLY GOBACK. END PROGRAM twice.   IDENTIFICATION DIVISION. PROGRAM-ID. evenp. DATA DIVISION. LOCAL-STORAGE SECTION. 01 q PICTURE 9(10). LINKAGE SECTION. 01 n PICTURE 9(10). 01 m PICTURE 9(1). 88 even VALUE 1. 88 odd VALUE 0. PROCEDURE DIVISION USING n, m. DIVIDE n BY 2 GIVING q REMAINDER m END-DIVIDE SUBTRACT m FROM 1 GIVING m END-SUBTRACT GOBACK. END PROGRAM evenp.
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.
#JavaScript
JavaScript
function equilibrium(a) { var N = a.length, i, l = [], r = [], e = [] for (l[0] = a[0], r[N - 1] = a[N - 1], i = 1; i<N; i++) l[i] = l[i - 1] + a[i], r[N - i - 1] = r[N - i] + a[N - i - 1] for (i = 0; i < N; i++) if (l[i] === r[i]) e.push(i) return e }   // test & output [ [-7, 1, 5, 2, -4, 3, 0], // 3, 6 [2, 4, 6], // empty [2, 9, 2], // 1 [1, -1, 1, -1, 1, -1, 1], // 0,1,2,3,4,5,6 [1], // 0 [] // empty ].forEach(function(x) { console.log(equilibrium(x)) });
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
#NewLISP
NewLISP
> (env "SHELL") "/bin/zsh" > (env "TERM") "xterm"
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
#Nim
Nim
import os echo 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
#NSIS
NSIS
ExpandEnvStrings $0 "%PATH%" ; Retrieve PATH and place it in builtin register 0. ExpandEnvStrings $1 "%USERPROFILE%" ; Retrieve the user's profile location and place it in builtin register 1. ExpandEnvStrings $2 "%USERNAME%" ; Retrieve the user's account name and place it in builtin register 2.
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
#Objective-C
Objective-C
[[[NSProcessInfo processInfo] environment] objectForKey:@"HOME"]
http://rosettacode.org/wiki/Esthetic_numbers
Esthetic numbers
An esthetic number is a positive integer where every adjacent digit differs from its neighbour by 1. E.G. 12 is an esthetic number. One and two differ by 1. 5654 is an esthetic number. Each digit is exactly 1 away from its neighbour. 890 is not an esthetic number. Nine and zero differ by 9. These examples are nominally in base 10 but the concept extends easily to numbers in other bases. Traditionally, single digit numbers are included in esthetic numbers; zero may or may not be. For our purposes, for this task, do not include zero (0) as an esthetic number. Do not include numbers with leading zeros. Esthetic numbers are also sometimes referred to as stepping numbers. Task Write a routine (function, procedure, whatever) to find esthetic numbers in a given base. Use that routine to find esthetic numbers in bases 2 through 16 and display, here on this page, the esthectic numbers from index (base × 4) through index (base × 6), inclusive. (E.G. for base 2: 8th through 12th, for base 6: 24th through 36th, etc.) Find and display, here on this page, the base 10 esthetic numbers with a magnitude between 1000 and 9999. Stretch: Find and display, here on this page, the base 10 esthetic numbers with a magnitude between 1.0e8 and 1.3e8. Related task   numbers with equal rises and falls See also OEIS A033075 - Positive numbers n such that all pairs of consecutive decimal digits differ by 1 Numbers Aplenty - Esthetic numbers Geeks for Geeks - Stepping numbers
#Wren
Wren
import "./fmt" for Conv, Fmt   var isEsthetic = Fn.new { |n, b| if (n == 0) return false var i = n % b n = (n/b).floor while (n > 0) { var j = n % b if ((i - j).abs != 1) return false n = (n/b).floor i = j } return true }   var esths = []   var dfs // recursive function dfs = Fn.new { |n, m, i| if (i >= n && i <= m) esths.add(i) if (i == 0 || i > m) return var d = i % 10 var i1 = i*10 + d - 1 var i2 = i1 + 2 if (d == 0) { dfs.call(n, m, i2) } else if (d == 9) { dfs.call(n, m, i1) } else { dfs.call(n, m, i1) dfs.call(n, m, i2) } }   var listEsths = Fn.new { |n, n2, m, m2, perLine, all| esths.clear() for (i in 0..9) dfs.call(n2, m2, i) var le = esths.count Fmt.print("Base 10: $,d esthetic numbers between $,d and $,d", le, n, m) if (all) { var c = 0 for (esth in esths) { System.write("%(esth) ") if ((c+1)%perLine == 0) System.print() c = c + 1 } } else { for (i in 0...perLine) System.write("%(Conv.dec(esths[i])) ") System.print("\n............\n") for (i in le-perLine...le) System.write("%(Conv.dec(esths[i])) ") } System.print("\n") }   for (b in 2..16) { System.print("Base %(b): %(4*b)th to %(6*b)th esthetic numbers:") var n = 1 var c = 0 while (c < 6*b) { if (isEsthetic.call(n, b)) { c = c + 1 if (c >= 4*b) System.write("%(Conv.itoa(n, b)) ") } n = n + 1 } System.print("\n") }   // the following all use the obvious range limitations for the numbers in question listEsths.call(1000, 1010, 9999, 9898, 16, true) listEsths.call(1e8, 101010101, 13*1e7, 123456789, 9, true) listEsths.call(1e11, 101010101010, 13*1e10, 123456789898, 7, false) listEsths.call(1e14, 101010101010101, 13*1e13, 123456789898989, 5, false)
http://rosettacode.org/wiki/Euler%27s_sum_of_powers_conjecture
Euler's sum of powers conjecture
There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin. Euler's (disproved) sum of powers   conjecture At least k positive kth powers are required to sum to a kth power, except for the trivial case of one kth power: yk = yk In 1966,   Leon J. Lander   and   Thomas R. Parkin   used a brute-force search on a   CDC 6600   computer restricting numbers to those less than 250. Task Write a program to search for an integer solution for: x05 + x15 + x25 + x35 == y5 Where all   xi's   and   y   are distinct integers between   0   and   250   (exclusive). Show an answer here. Related tasks   Pythagorean quadruples.   Pythagorean triples.
#Groovy
Groovy
class EulerSumOfPowers { static final int MAX_NUMBER = 250   static void main(String[] args) { boolean found = false long[] fifth = new long[MAX_NUMBER]   for (int i = 1; i <= MAX_NUMBER; i++) { long i2 = i * i fifth[i - 1] = i2 * i2 * i }   for (int a = 0; a < MAX_NUMBER && !found; a++) { for (int b = a; b < MAX_NUMBER && !found; b++) { for (int c = b; c < MAX_NUMBER && !found; c++) { for (int d = c; d < MAX_NUMBER && !found; d++) { long sum = fifth[a] + fifth[b] + fifth[c] + fifth[d] int e = Arrays.binarySearch(fifth, sum) found = (e >= 0) if (found) { println("${a + 1}^5 + ${b + 1}^5 + ${c + 1}^5 + ${d + 1}^5 + ${e + 1}^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
#Nyquist
Nyquist
(defun factorial (n) (do ((x n (* x n))) ((= n 1) x) (setq n (1- n))))
http://rosettacode.org/wiki/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd. Use modular congruences: i ≡ 0 (mod 2) iff i is even. i ≡ 1 (mod 2) iff i is odd.
#ColdFusion
ColdFusion
  function f(numeric n) { return n mod 2?"odd":"even" }  
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.
#Common_Lisp
Common Lisp
(if (evenp some-var) (do-even-stuff)) (if (oddp some-other-var) (do-odd-stuff))
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.
#SequenceL
SequenceL
import <Utilities/Conversion.sl>; import <Utilities/Sequence.sl>;   T0 := 100.0; TR := 20.0; k := 0.07;   main(args(2)) := let results[i] := euler(newtonCooling, T0, 100, stringToInt(args[i]), 0, "delta_t = " ++ args[i]); in delimit(results, '\n');   newtonCooling(t) := -k * (t - TR);   euler: (float -> float) * float * int * int * int * char(1) -> char(1); euler(f, y, n, h, x, output(1)) := let newOutput := output ++ "\n\t" ++ intToString(x) ++ "\t" ++ floatToString(y, 3); newY := y + h * f(y); newX := x + h; in output when x > n else euler(f, newY, n, h, newX, newOutput);
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.
#Sidef
Sidef
func euler_method(t0, t1, k, step_size) { var results = [[0, t0]] for s in (step_size..100 -> by(step_size)) { t0 -= ((t0 - t1) * k * step_size) results << [s, t0] } return results; }   func analytical(t0, t1, k, time) { (t0 - t1) * exp(-time * k) + t1 }   var (T0, T1, k) = (100, 20, .07) var r2 = euler_method(T0, T1, k, 2).grep { _[0] %% 10 } var r5 = euler_method(T0, T1, k, 5).grep { _[0] %% 10 } var r10 = euler_method(T0, T1, k, 10).grep { _[0] %% 10 }   say "Time\t 2 err(%) 5 err(%) 10 err(%) Analytic" say "-"*76   r2.range.each { |i| var an = analytical(T0, T1, k, r2[i][0]) printf("%4d\t#{'%9.3f' * 7}\n", r2[i][0], r2[i][1], ( r2[i][1] / an) * 100 - 100, r5[i][1], ( r5[i][1] / an) * 100 - 100, r10[i][1], (r10[i][1] / an) * 100 - 100, an) }
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
#Lambdatalk
Lambdatalk
    {def C {lambda {:n :p} {/ {* {S.serie :n {- :n :p -1} -1}} {* {S.serie :p 1 -1}}}}} -> C   {C 16 8} -> 12870   1{S.map {lambda {:n} {br}1 {S.map {C :n} {S.serie 1 {- :n 1}}} 1} {S.serie 2 16}} -> 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 1 7 21 35 35 21 7 1 1 8 28 56 70 56 28 8 1 1 9 36 84 126 126 84 36 9 1 1 10 45 120 210 252 210 120 45 10 1 1 11 55 165 330 462 462 330 165 55 11 1 1 12 66 220 495 792 924 792 495 220 66 12 1 1 13 78 286 715 1287 1716 1716 1287 715 286 78 13 1 1 14 91 364 1001 2002 3003 3432 3003 2002 1001 364 91 14 1 1 15 105 455 1365 3003 5005 6435 6435 5005 3003 1365 455 105 15 1 1 16 120 560 1820 4368 8008 11440 12870 11440 8008 4368 1820 560 120 16 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).
#C.23
C#
using static System.Console; using System; using System.Linq; using System.Collections.Generic;   public class Program { public static void Main() { const int limit = 1_000_000; WriteLine("First 20:"); WriteLine(FindEmirpPrimes(limit).Take(20).Delimit()); WriteLine();   WriteLine("Between 7700 and 8000:"); WriteLine(FindEmirpPrimes(limit).SkipWhile(p => p < 7700).TakeWhile(p => p < 8000).Delimit()); WriteLine();   WriteLine("10000th:"); WriteLine(FindEmirpPrimes(limit).ElementAt(9999)); }   private static IEnumerable<int> FindEmirpPrimes(int limit) { var primes = Primes(limit).ToHashSet();   foreach (int prime in primes) { int reverse = prime.Reverse(); if (reverse != prime && primes.Contains(reverse)) yield return prime; } }   private static IEnumerable<int> Primes(int bound) { if (bound < 2) yield break; yield return 2;   BitArray composite = new BitArray((bound - 1) / 2); int limit = ((int)(Math.Sqrt(bound)) - 1) / 2; for (int i = 0; i < limit; i++) { if (composite[i]) continue; int prime = 2 * i + 3; yield return prime;   for (int j = (prime * prime - 2) / 2; j < composite.Count; j += prime) composite[j] = true; } for (int i = limit; i < composite.Count; i++) if (!composite[i]) yield return 2 * i + 3; } }   public static class Extensions { public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source) => new HashSet<T>(source);   private const string defaultSeparator = " "; public static string Delimit<T>(this IEnumerable<T> source, string separator = defaultSeparator) => string.Join(separator ?? defaultSeparator, source);   public static int Reverse(this int number) { if (number < 0) return -Reverse(-number); if (number < 10) return number; int reverse = 0; while (number > 0) { reverse = reverse * 10 + number % 10; number /= 10; } return reverse; } }
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).
#Nim
Nim
import math, strformat   const B = 7   type Point = tuple[x, y: float]   #---------------------------------------------------------------------------------------------------   template zero(): Point = (Inf, Inf)   #---------------------------------------------------------------------------------------------------   func isZero(pt: Point): bool {.inline.} = pt.x > 1e20 or pt.x < -1e20   #---------------------------------------------------------------------------------------------------   func `-`(pt: Point): Point {.inline.} = (pt.x, -pt.y)   #---------------------------------------------------------------------------------------------------   func double(pt: Point): Point =   if pt.isZero: return pt   let t = (3 * pt.x * pt.x) / (2 * pt.y) result.x = t * t - 2 * pt.x result.y = t * (pt.x - result.x) - pt.y   #---------------------------------------------------------------------------------------------------   func `+`(pt1, pt2: Point): Point =   if pt1.x == pt2.x and pt1.y == pt2.y: return double(pt1) if pt1.isZero: return pt2 if pt2.isZero: return pt1   let t = (pt2.y - pt1.y) / (pt2.x - pt1.x) result.x = t * t - pt1.x - pt2.x result.y = t * (pt1.x - result.x) - pt1.y   #---------------------------------------------------------------------------------------------------   func `*`(pt: Point; n: int): Point =   result = zero() var pt = pt var i = 1   while i <= n: if (i and n) != 0: result = result + pt pt = double(pt) i = i shl 1   #---------------------------------------------------------------------------------------------------   func `$`(pt: Point): string = if pt.isZero: "Zero" else: fmt"({pt.x:.3f}, {pt.y:.3f})"   #---------------------------------------------------------------------------------------------------   func fromY(y: float): Point {.inline.} = (cbrt(y * y - B), y)   #———————————————————————————————————————————————————————————————————————————————————————————————————   when isMainModule: let a = fromY(1) let b = fromY(2)   echo "a = ", a echo "b = ", b let c = a + b echo "c = a + b = ", c let d = -c echo "d = -c = ", d echo "c + d = ", c + d echo "a + b + d = ", a + b + d echo "a * 12345 = ", a * 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).
#OCaml
OCaml
  (* Task : Elliptic_curve_arithmetic *)   (* Using the secp256k1 elliptic curve (a=0, b=7), define the addition operation on points on the curve. Extra credit: define the full elliptic curve arithmetic (still not modular, though) by defining a "multiply" function. *)   (*** Helpers ***)   type ec_point = Point of float * float | Inf   type ec_curve = { a : float; b : float }   (* By default, cube root doesn't work for negative bases *) let cube_root : float -> float = let third = 1. /. 3. in let f x = if x > 0. then x ** third else ~-. (~-. x ** third) in f   (* Finds the left-most x on this curve *) let ec_minx ({a; b} : ec_curve) : float = let factor = ~-. b *. 0.5 in let discr = (factor ** 2.) +. (a ** 3. /. 27.) in if discr <= 0. then failwith "Not a simple curve" else let root = sqrt discr in cube_root (factor +. root) +. cube_root (factor -. root)   (* Negates the point by negating y coord *) let ec_neg : ec_point -> ec_point = function | Inf -> Inf | Point (x, y) -> Point (x, ~-. y)   (*** Actual task at hand ***)   (* Generates a random point in the vicinity of x=0 *) let ec_random ({a; b} as c : ec_curve) : ec_point = let minx = ec_minx c in let x = Random.float (~-. minx *. 2.) +. minx in let rhs = x ** 3. +. a *. x +. b in Point (x, sqrt rhs)   (* Verifies that the point is on curve. Due to rounding errors, sometimes these calculations aren't perfect. *) let on_curve ?(debug : bool = false) ({a; b} : ec_curve) : ec_point -> bool = function | Inf -> true | Point (x, y) -> let lhs = y *. y in let rhs = x ** 3. +. a *. x +. b in let delta = abs_float (lhs -. rhs) in ( if debug then Printf.printf "Delta = %.8f" delta; delta < 0.000001 )   (* Doubles a point on the curve (adds a point to itself) *) let ec_double ({a; b} as c : ec_curve) : ec_point -> ec_point = function | Inf -> Inf | Point (x, y) as p -> if not (on_curve c p) then failwith "Point not on this curve." else if y = 0. then Inf else let s = (3. *. x *. x +. a) /. (2. *. y) in let x' = s *. s -. 2. *. x in let y' = y +. s *. (x' -. x) in Point (x', -. y')   (* Adds any two points on the curve *) let ec_add ({a; b} as c : ec_curve) (p : ec_point) (q : ec_point) : ec_point = match p, q with | Inf, x | x, Inf -> x | Point (px, py), Point (qx, qy) -> if not (on_curve c p) || not (on_curve c q) then failwith "Point not on this curve." else if abs_float (px -. qx) < 0.000001 then begin if abs_float (py +. qy) < 0.000001 then Inf else (* py must equal qy here, otherwise something goes real bad *) ec_double c p |> ec_neg end else let s = (py -. qy) /. (px -. qx) in let rx = s *. s -. px -. qx in let ry = py +. s *. (rx -. px) in Point (rx, -. ry)   (* Extra credit : multiplies a point by a scalar *) let ec_mul ({a; b} as c : ec_curve) (p : ec_point) (n : int) : ec_point = let rec helper n curPow acc = if n = 0 then acc else let doubled = ec_double c curPow in if n mod 2 = 0 then helper (n / 2) doubled acc else helper (n / 2) doubled (ec_add c acc curPow) in helper n p Inf   (*** Output ***)   let string_of_point : ec_point -> string = function | Inf -> "Zero" | Point (x, y) -> Printf.sprintf "(%.4f, %.4f)" x y   let print_output () = let c = { a = 0.; b = 7. } in let p = ec_random c in let q = ec_random c in let r = ec_add c p q in let t = ec_neg r in Printf.printf "p = %s\n" (string_of_point p); Printf.printf "q = %s\n" (string_of_point q); Printf.printf "r = p + q = %s\n" (string_of_point r); Printf.printf "t = -r = %s\n" (string_of_point t); Printf.printf "r + t = %s\n" (ec_add c r t |> string_of_point); Printf.printf "p + (q + t) = %s\n" (ec_add c q t |> ec_add c p |> string_of_point); Printf.printf "p * 12345 = %s\n" (ec_mul c p 12345 |> string_of_point)   let _ = print_output (); print_output ()  
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#M4
M4
define(`enums', `define(`$2',$1)`'ifelse(eval($#>2),1,`enums(incr($1),shift(shift($@)))')') define(`enum', `enums(1,$@)') enum(a,b,c,d) `c='c
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
MapIndexed[Set, {A, B, F, G}] ->{{1}, {2}, {3}, {4}}   A ->{1}   B ->{2}   G ->{4}
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#MATLAB_.2F_Octave
MATLAB / Octave
stuff = {'apple', [1 2 3], 'cherry',1+2i}   stuff =   'apple' [1x3 double] 'cherry' [1.000000000000000 + 2.000000000000000i]
http://rosettacode.org/wiki/Elementary_cellular_automaton/Random_Number_Generator
Elementary cellular automaton/Random Number Generator
Rule 30 is considered to be chaotic enough to generate good pseudo-random numbers. As a matter of fact, rule 30 is used by the Mathematica software for its default random number generator. Steven Wolfram's recommendation for random number generation from rule 30 consists in extracting successive bits in a fixed position in the array of cells, as the automaton changes state. The purpose of this task is to demonstrate this. With the code written in the parent task, which you don't need to re-write here, show the ten first bytes that emerge from this recommendation. To be precise, you will start with a state of all cells but one equal to zero, and you'll follow the evolution of the particular cell whose state was initially one. Then you'll regroup those bits by packets of eight, reconstituting bytes with the first bit being the most significant. You can pick which ever length you want for the initial array but it should be visible in the code so that your output can be reproduced with an other language. For extra-credits, you will make this algorithm run as fast as possible in your language, for instance with an extensive use of bitwise logic. Reference Cellular automata: Is Rule 30 random? (PDF).
#Racket
Racket
#lang racket ;; below is the code from the parent task (require "Elementary_cellular_automata.rkt") (require racket/fixnum)   ;; This is the RNG automaton (define (CA30-random-generator #:rule [rule 30] ; rule 30 is random, maybe you're interested in using others  ;; width of the CA... this is implemented as a number of words plus,  ;; maybe, another word containing the spare bits #:bits [bits 256]) (define-values [full-words more-bits] (quotient/remainder bits usable-bits/fixnum)) (define wrap-rule (and (positive? more-bits) (wrap-rule-truncate-left-word more-bits))) (define next-gen (CA-next-generation 30 #:wrap-rule wrap-rule)) (define v (make-fxvector (+ full-words (if more-bits 1 0)))) (fxvector-set! v 0 1) ; this bit will always have significance   (define (next-word) (define-values [v+ o] (next-gen v 0)) (begin0 (fxvector-ref v 0) (set! v v+)))   (lambda (bits) (for/fold ([acc 0]) ([_ (in-range bits)])  ;; the CA is fixnum, but this function returns integers of arbitrary width (bitwise-ior (arithmetic-shift acc 1) (bitwise-and (next-word) 1)))))   (module+ main  ;; To match the other examples on this page, the automaton is 30+30+4 bits long  ;; (i.e. 64 bits) (define C30-rand-64 (CA30-random-generator #:bits 64))  ;; this should be the list from "C" (for/list ([i 10]) (C30-rand-64 8))    ; we also do big numbers... (number->string (C30-rand-64 256) 16) (number->string (C30-rand-64 256) 16) (number->string (C30-rand-64 256) 16) (number->string (C30-rand-64 256) 16))
http://rosettacode.org/wiki/Elementary_cellular_automaton/Random_Number_Generator
Elementary cellular automaton/Random Number Generator
Rule 30 is considered to be chaotic enough to generate good pseudo-random numbers. As a matter of fact, rule 30 is used by the Mathematica software for its default random number generator. Steven Wolfram's recommendation for random number generation from rule 30 consists in extracting successive bits in a fixed position in the array of cells, as the automaton changes state. The purpose of this task is to demonstrate this. With the code written in the parent task, which you don't need to re-write here, show the ten first bytes that emerge from this recommendation. To be precise, you will start with a state of all cells but one equal to zero, and you'll follow the evolution of the particular cell whose state was initially one. Then you'll regroup those bits by packets of eight, reconstituting bytes with the first bit being the most significant. You can pick which ever length you want for the initial array but it should be visible in the code so that your output can be reproduced with an other language. For extra-credits, you will make this algorithm run as fast as possible in your language, for instance with an extensive use of bitwise logic. Reference Cellular automata: Is Rule 30 random? (PDF).
#Raku
Raku
class Automaton { has $.rule; has @.cells; has @.code = $!rule.fmt('%08b').flip.comb».Int;   method gist { "|{ @!cells.map({+$_ ?? '#' !! ' '}).join }|" }   method succ { self.new: :$!rule, :@!code, :cells( @!code[ 4 «*« @!cells.rotate(-1)  »+« 2 «*« @!cells  »+«  @!cells.rotate(1) ] ) } }   my Automaton $a .= new: :rule(30), :cells( flat 1, 0 xx 100 );   say :2[$a++.cells[0] xx 8] xx 10;
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
#AWK
AWK
#!/usr/bin/awk -f BEGIN { # Demonstrate how to assign an empty string to a variable. a=""; b="XYZ"; print "a = ",a; print "b = ",b; print "length(a)=",length(a); print "length(b)=",length(b); # Demonstrate how to check that a string is empty. print "Is a empty ?",length(a)==0; print "Is a not empty ?",length(a)!=0; # Demonstrate how to check that a string is not empty. print "Is b empty ?",length(b)==0; print "Is b not empty ?",length(b)!=0; }
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
#Axe
Axe
""→Str1 !If length(Str1) Disp "EMPTY",i Else Disp "NOT EMPTY",i 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.
#Go
Go
package main   import ( "fmt" "io/ioutil" "log" )   func main() { empty, err := IsEmptyDir("/tmp") if err != nil { log.Fatalln(err) } if empty { fmt.Printf("/tmp is empty\n") } else { fmt.Printf("/tmp is not empty\n") } }   func IsEmptyDir(name string) (bool, error) { entries, err := ioutil.ReadDir(name) if err != nil { return false, err } return len(entries) == 0, nil }