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/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.
#Sidef
Sidef
func eq_index(nums) { var (i, sum, sums) = (0, 0, Hash.new); nums.each { |n| sums{2*sum + n} := [] -> append(i++); sum += n; } sums{sum} \\ []; }
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.
#Swift
Swift
extension Collection where Element: Numeric { func equilibriumIndexes() -> [Index] { guard !isEmpty else { return [] }   let sumAll = reduce(0, +) var ret = [Index]() var sumLeft: Element = 0 var sumRight: Element   for i in indices { sumRight = sumAll - sumLeft - self[i]   if sumLeft == sumRight { ret.append(i) }   sumLeft += self[i] }   return ret } }   let arr = [-7, 1, 5, 2, -4, 3, 0]   print("Equilibrium indexes of \(arr): \(arr.equilibriumIndexes())")
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.
#PowerShell
PowerShell
# EULER.PS1 $max = 250   $powers = New-Object System.Collections.ArrayList for ($i = 0; $i -lt $max; $i++) { $tmp = $powers.Add([Math]::Pow($i, 5)) }   for ($x0 = 1; $x0 -lt $max; $x0++) { for ($x1 = 1; $x1 -lt $x0; $x1++) { for ($x2 = 1; $x2 -lt $x1; $x2++) { for ($x3 = 1; $x3 -lt $x2; $x3++) { $sum = $powers[$x0] + $powers[$x1] + $powers[$x2] + $powers[$x3] $S1 = [int][Math]::pow($sum,0.2)   if ($sum -eq $powers[$S1]) { Write-host "$x0^5 + $x1^5 + $x2^5 + $x3^5 = $S1^5" 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
#PL.2FI
PL/I
factorial: procedure (N) returns (fixed decimal (30)); declare N fixed binary nonassignable; declare i fixed decimal (10); declare F fixed decimal (30);   if N < 0 then signal error; F = 1; do i = 2 to N; F = F * i; end; return (F); end factorial;
http://rosettacode.org/wiki/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd. Use modular congruences: i ≡ 0 (mod 2) iff i is even. i ≡ 1 (mod 2) iff i is odd.
#J
J
2 | 2 3 5 7 0 1 1 1 2|2 3 5 7 + (2^89x)-1 1 0 0 0
http://rosettacode.org/wiki/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd. Use modular congruences: i ≡ 0 (mod 2) iff i is even. i ≡ 1 (mod 2) iff i is odd.
#Java
Java
public static boolean isEven(int i){ return (i & 1) == 0; }
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
#Seed7
Seed7
$ include "seed7_05.s7i";   const proc: main is func local var integer: n is 0; var integer: k is 0; begin for n range 0 to 66 do for k range 0 to n do write(n ! k <& " "); end for; writeln; end for; end func;
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
#SequenceL
SequenceL
  choose(n, k) := product(k + 1 ... n) / product(1 ... n - k);  
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).
#Nim
Nim
import math   # Increments to find the next divisor when testing primality. const Incr = [4, 2, 4, 2, 4, 6, 2, 6]   #---------------------------------------------------------------------------------------------------   func reversed(n: int): int = ## Return the reversed number in base 10 representation. var n = n while true: result = 10 * result + n mod 10 n = n div 10 if n == 0: break   #---------------------------------------------------------------------------------------------------   func isPrime(n: int): bool = ## Check if a number is prime. ## We are already sure that "n" is not a multiple of 2, 3 or 5, ## so we don’t check the modulo. var k = 7 var i = 0 while k <= int(sqrt(n.toFloat)): if n mod k == 0: return false inc k, Incr[i] i = if i == Incr.high: 0 else: i + 1 result = true   #---------------------------------------------------------------------------------------------------   iterator emirps(): int = ## Yield the emirps. var n = 13 var i = 2 # Current index in the increment array. while true: # We find the reversed number first as it allows to eliminate candidates. let r = reversed(n) if r != n and r mod 10 in [1, 3, 7, 9] and n.isPrime and r.isPrime: yield n inc n, Incr[i] i = if i == Incr.high: 0 else: i + 1   #———————————————————————————————————————————————————————————————————————————————————————————————————   stdout.write "First 20 emirps:" var count = 0 for n in emirps(): stdout.write ' ', n inc count if count == 20: echo "" break   stdout.write "Emirps between 7700 and 8000:" for n in emirps(): if n in 7700..8000: stdout.write ' ', n elif n > 8000: echo "" break   stdout.write "The 10000th emirp: " count = 0 for n in emirps(): inc count if count == 10000: echo n break
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).
#Oforth
Oforth
: isEmirp(n) n isPrime ifFalse: [ false return ] n asString reverse asInteger dup n == ifTrue: [ drop false ] else: [ isPrime ] ;   : main(min, max, length) | l | ListBuffer new ->l min while(l size length < ) [ dup max > ifTrue: [ break ] dup isEmirp ifTrue: [ dup l add ] 1 + ] drop l ;
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
#Gambas
Gambas
Public Sub Main() Dim sString As String[] = ["", "Hello", "world", "", "Today", "Tomorrow", "", "", "End!"] Dim sTemp As String Dim siCount As Short   For Each sTemp In sString If sString[siCount] Then Print "String " & siCount & " = " & sString[siCount] Else Print "String " & siCount & " is empty" End If Inc siCount Next   End
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
#Go
Go
// define and initialize an empty string var s string s2 := ""   // assign an empty string to a variable s = ""   // check that a string is empty, any of: s == "" len(s) == 0   // check that a string is not empty, any of: s != "" len(s) != 0 // or > 0
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Erlang
Erlang
-module(empty).
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#ERRE
ERRE
  PROGRAM EMPTY BEGIN END PROGRAM  
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#eSQL
eSQL
CREATE COMPUTE MODULE ESQL_Compute CREATE FUNCTION Main() RETURNS BOOLEAN BEGIN RETURN TRUE; END; END MODULE;
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
#Lua
Lua
function log2 (x) return math.log(x) / math.log(2) end   function entropy (X) local N, count, sum, i = X:len(), {}, 0 for char = 1, N do i = X:sub(char, char) if count[i] then count[i] = count[i] + 1 else count[i] = 1 end end for n_i, count_i in pairs(count) do sum = sum + count_i / N * log2(count_i / N) end return -sum end   print(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
#F.C5.8Drmul.C3.A6
Fōrmulæ
package main   import "fmt"   func halve(i int) int { return i/2 }   func double(i int) int { return i*2 }   func isEven(i int) bool { return i%2 == 0 }   func ethMulti(i, j int) (r int) { for ; i > 0; i, j = halve(i), double(j) { if !isEven(i) { r += j } } return }   func main() { fmt.Printf("17 ethiopian 34 = %d\n", ethMulti(17, 34)) }
http://rosettacode.org/wiki/Equilibrium_index
Equilibrium index
An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices. For example, in a sequence   A {\displaystyle A} :   A 0 = − 7 {\displaystyle A_{0}=-7}   A 1 = 1 {\displaystyle A_{1}=1}   A 2 = 5 {\displaystyle A_{2}=5}   A 3 = 2 {\displaystyle A_{3}=2}   A 4 = − 4 {\displaystyle A_{4}=-4}   A 5 = 3 {\displaystyle A_{5}=3}   A 6 = 0 {\displaystyle A_{6}=0} 3   is an equilibrium index, because:   A 0 + A 1 + A 2 = A 4 + A 5 + A 6 {\displaystyle A_{0}+A_{1}+A_{2}=A_{4}+A_{5}+A_{6}} 6   is also an equilibrium index, because:   A 0 + A 1 + A 2 + A 3 + A 4 + A 5 = 0 {\displaystyle A_{0}+A_{1}+A_{2}+A_{3}+A_{4}+A_{5}=0} (sum of zero elements is zero) 7   is not an equilibrium index, because it is not a valid index of sequence A {\displaystyle A} . Task; Write a function that, given a sequence, returns its equilibrium indices (if any). Assume that the sequence may be very long.
#Tcl
Tcl
proc listEquilibria {list} { set after 0 foreach item $list {incr after $item} set result {} set idx 0 set before 0 foreach item $list { incr after [expr {-$item}] if {$after == $before} { lappend result $idx } incr before $item incr idx } return $result }
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.
#Ursala
Ursala
#import std #import int   edex = num@yK33ySPtK33xtS2px; ~&nS+ *~ ==+ ~~r sum:-0   #cast %nL   example = edex <-7,1,5,2,-4,3,0>
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.
#Prolog
Prolog
  makepowers :- retractall(pow5(_, _)), between(1, 249, X), Y is X * X * X * X * X, assert(pow5(X, Y)), fail. makepowers.   within(A, Bx, N) :- % like between but with an exclusive upper bound succ(B, Bx), between(A, B, N).   solution(X0, X1, X2, X3, Y) :- makepowers, within(4, 250, X0), pow5(X0, X0_5th), within(3, X0, X1), pow5(X1, X1_5th), within(2, X1, X2), pow5(X2, X2_5th), within(1, X2, X3), pow5(X3, X3_5th), Y_5th is X0_5th + X1_5th + X2_5th + X3_5th, pow5(Y, Y_5th).  
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
#PL.2FSQL
PL/SQL
  DECLARE /*==================================================================================================== -- For  : https://rosettacode.org/ -- -- -- Task  : Factorial -- Method  : iterative -- Language: PL/SQL -- -- 2020-12-30 by alvalongo ====================================================================================================*/ -- FUNCTION fnuFactorial(inuValue INTEGER) RETURN NUMBER IS nuFactorial NUMBER; BEGIN IF inuValue IS NOT NULL THEN nuFactorial:=1; -- IF inuValue>=1 THEN -- FOR nuI IN 1..inuValue LOOP nuFactorial:=nuFactorial*nuI; END LOOP; -- END IF; -- END IF; -- RETURN(nuFactorial); END fnuFactorial; BEGIN FOR nuJ IN 0..100 LOOP DBMS_OUTPUT.Put_Line('Factorial('||nuJ||')='||fnuFactorial(nuJ)); END LOOP; END;  
http://rosettacode.org/wiki/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd. Use modular congruences: i ≡ 0 (mod 2) iff i is even. i ≡ 1 (mod 2) iff i is odd.
#JavaScript
JavaScript
function isEven( i ) { return (i & 1) === 0; }  
http://rosettacode.org/wiki/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd. Use modular congruences: i ≡ 0 (mod 2) iff i is even. i ≡ 1 (mod 2) iff i is odd.
#jq
jq
def is_even: type == "number" and floor == 0 and . % 2 == 0;
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
#Sidef
Sidef
func binomial(n,k) { n! / ((n-k)! * k!) }   say binomial(400, 200)
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
#Smalltalk
Smalltalk
Transcript showCR: (5 binco:3). Transcript showCR: (400 binco:200)
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).
#PARI.2FGP
PARI/GP
rev(n)=subst(Polrev(digits(n)),'x,10); emirp(n)=my(r=rev(n)); isprime(r) && isprime(n) && n!=r select(emirp, primes(100))[1..20] select(emirp, primes([7700,8000])) s=10000; forprime(p=2,,if(emirp(p) && s--==0, return(p)))
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
#Groovy
Groovy
def s = '' // or "" if you wish assert s.empty   s = '1 is the loneliest number' assert !s.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
#GW-BASIC
GW-BASIC
10 DIM S1$ 'implicitly defined empty string 20 S2$ = "" 'explicitly defined empty string 30 S3$ = "Foo bar baz" 40 S$=S1$ : GOSUB 200 50 S$=S2$ : GOSUB 200 60 S$=S3$ : GOSUB 200 70 END 200 IF LEN(S$)=0 THEN PRINT "Empty string" ELSE PRINT "Non-empty string" 210 RETURN
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Euphoria
Euphoria
 
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#F.23
F#
 
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Factor
Factor
 
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
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
shE[s_String] := -Plus @@ ((# Log[2., #]) & /@ ((Length /@ Gather[#])/ Length[#]) &[Characters[s]])
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
#MATLAB_.2F_Octave
MATLAB / Octave
function E = entropy(d) if ischar(d), d=abs(d); end; [Y,I,J] = unique(d); H = sparse(J,1,1); p = full(H(H>0))/length(d); E = -sum(p.*log2(p)); end;
http://rosettacode.org/wiki/Ethiopian_multiplication
Ethiopian multiplication
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last in the same column, until you write a value of 1. In the right-hand column repeatedly double the last number and write the result below. stop when you add a result in the same row as where the left hand column shows 1. Examine the table produced and discard any row where the value in the left column is even. Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together For example:   17 × 34 17 34 Halving the first column: 17 34 8 4 2 1 Doubling the second column: 17 34 8 68 4 136 2 272 1 544 Strike-out rows whose first cell is even: 17 34 8 68 4 136 2 272 1 544 Sum the remaining numbers in the right-hand column: 17 34 8 -- 4 --- 2 --- 1 544 ==== 578 So 17 multiplied by 34, by the Ethiopian method is 578. Task The task is to define three named functions/methods/procedures/subroutines: one to halve an integer, one to double an integer, and one to state if an integer is even. Use these functions to create a function that does Ethiopian multiplication. References Ethiopian multiplication explained (BBC Video clip) A Night Of Numbers - Go Forth And Multiply (Video) Russian Peasant Multiplication Programming Praxis: Russian Peasant Multiplication
#Go
Go
package main   import "fmt"   func halve(i int) int { return i/2 }   func double(i int) int { return i*2 }   func isEven(i int) bool { return i%2 == 0 }   func ethMulti(i, j int) (r int) { for ; i > 0; i, j = halve(i), double(j) { if !isEven(i) { r += j } } return }   func main() { fmt.Printf("17 ethiopian 34 = %d\n", ethMulti(17, 34)) }
http://rosettacode.org/wiki/Equilibrium_index
Equilibrium index
An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices. For example, in a sequence   A {\displaystyle A} :   A 0 = − 7 {\displaystyle A_{0}=-7}   A 1 = 1 {\displaystyle A_{1}=1}   A 2 = 5 {\displaystyle A_{2}=5}   A 3 = 2 {\displaystyle A_{3}=2}   A 4 = − 4 {\displaystyle A_{4}=-4}   A 5 = 3 {\displaystyle A_{5}=3}   A 6 = 0 {\displaystyle A_{6}=0} 3   is an equilibrium index, because:   A 0 + A 1 + A 2 = A 4 + A 5 + A 6 {\displaystyle A_{0}+A_{1}+A_{2}=A_{4}+A_{5}+A_{6}} 6   is also an equilibrium index, because:   A 0 + A 1 + A 2 + A 3 + A 4 + A 5 = 0 {\displaystyle A_{0}+A_{1}+A_{2}+A_{3}+A_{4}+A_{5}=0} (sum of zero elements is zero) 7   is not an equilibrium index, because it is not a valid index of sequence A {\displaystyle A} . Task; Write a function that, given a sequence, returns its equilibrium indices (if any). Assume that the sequence may be very long.
#VBScript
VBScript
arr = Array(-7,1,5,2,-4,3,0) WScript.StdOut.Write equilibrium(arr,UBound(arr)) WScript.StdOut.WriteLine   Function equilibrium(arr,n) sum = 0 leftsum = 0 'find the sum of the whole array For i = 0 To UBound(arr) sum = sum + arr(i) Next For i = 0 To UBound(arr) sum = sum - arr(i) If leftsum = sum Then equilibrium = equilibrium & i & ", " End If leftsum = leftsum + arr(i) Next End Function
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.
#Wren
Wren
import "/fmt" for Fmt   var equilibrium = Fn.new { |a| var len = a.count var equi = [] if (len == 0) return equi // sequence has no indices at all var rsum = a.reduce { |acc, x| acc + x } var lsum = 0 for (i in 0...len) { rsum = rsum - a[i] if (rsum == lsum) equi.add(i) lsum = lsum + a[i] } return equi }   var tests = [ [-7, 1, 5, 2, -4, 3, 0], [2, 4, 6], [2, 9, 2], [1, -1, 1, -1, 1, -1, 1], [1], [] ]   System.print("The equilibrium indices for the following sequences are:\n") for (test in tests) { System.print("%(Fmt.s(24, test)) -> %(equilibrium.call(test))") }
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.
#PureBasic
PureBasic
  EnableExplicit   ; assumes an array of non-decreasing positive integers Procedure.q BinarySearch(Array a.q(1), Target.q) Protected l = 0, r = ArraySize(a()), m Repeat If l > r : ProcedureReturn 0 : EndIf; no match found m = (l + r) / 2 If a(m) < target l = m + 1 ElseIf a(m) > target r = m - 1 Else ProcedureReturn m ; match found EndIf ForEver EndProcedure   Define i, x0, x1, x2, x3, y Define.q sum Define Dim p5.q(249)   For i = 1 To 249 p5(i) = i * i * i * i * i Next   If OpenConsole() For x0 = 1 To 249 For x1 = 1 To x0 - 1 For x2 = 1 To x1 - 1 For x3 = 1 To x2 - 1 sum = p5(x0) + p5(x1) + p5(x2) + p5(x3) y = BinarySearch(p5(), sum) If y > 0 PrintN(Str(x0) + "^5 + " + Str(x1) + "^5 + " + Str(x2) + "^5 + " + Str(x3) + "^5 = " + Str(y) + "^5") Goto finish EndIf Next x3 Next x2 Next x1 Next x0   PrintN("No solution was found") finish: PrintN("") PrintN("Press any key to close the console") Repeat: Delay(10) : Until Inkey() <> "" CloseConsole() EndIf  
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
#PostScript
PostScript
/fact { dup 0 eq  % check for the argument being 0 { pop 1  % if so, the result is 1 } { dup 1 sub fact  % call recursively with n - 1 mul  % multiply the result with n } ifelse } def
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.
#Jsish
Jsish
#!/usr/bin/env jsish /* Even or Odd, in Jsish */ function isEven(n:number):boolean { return (n & 1) === 0; }   provide('isEven', 1);   if (Interp.conf('unitTest')) { ; isEven(0); ; isEven(1); ; isEven(2); ; isEven(-13); }   /* =!EXPECTSTART!= isEven(0) ==> true isEven(1) ==> false isEven(2) ==> true isEven(-13) ==> false =!EXPECTEND!= */
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
#Stata
Stata
. display comb(5,3) 10
http://rosettacode.org/wiki/Evaluate_binomial_coefficients
Evaluate binomial coefficients
This programming task, is to calculate ANY binomial coefficient. However, it has to be able to output   ( 5 3 ) {\displaystyle {\binom {5}{3}}} ,   which is   10. This formula is recommended: ( n k ) = n ! ( n − k ) ! k ! = n ( n − 1 ) ( n − 2 ) … ( n − k + 1 ) k ( k − 1 ) ( k − 2 ) … 1 {\displaystyle {\binom {n}{k}}={\frac {n!}{(n-k)!k!}}={\frac {n(n-1)(n-2)\ldots (n-k+1)}{k(k-1)(k-2)\ldots 1}}} See Also: Combinations and permutations Pascal's triangle The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#Swift
Swift
func factorial<T: BinaryInteger>(_ n: T) -> T { guard n != 0 else { return 1 }   return stride(from: n, to: 0, by: -1).reduce(1, *) }   func binomial<T: BinaryInteger>(_ x: (n: T, k: T)) -> T { let nFac = factorial(x.n) let kFac = factorial(x.k)   return nFac / (factorial(x.n - x.k) * kFac) }   print("binomial(\(5), \(3)) = \(binomial((5, 3)))") print("binomial(\(20), \(11)) = \(binomial((20, 11)))")
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).
#Pascal
Pascal
program Emirp; //palindrome prime 13 <-> 31 {$IFDEF FPC} {$MODE DELPHI} {$OPTIMIZATION ON} {$OPTIMIZATION REGVAR} {$OPTIMIZATION PEEPHOLE} {$OPTIMIZATION CSE} {$OPTIMIZATION ASMCSE} {$Smartlink ON} {$CODEALIGN proc=32} {$ELSE} {$APPLICATION CONSOLE} {$ENDIF} uses primtrial,sysutils; //IntToStr const helptext : array[0..5] of string = (' usage ', ' t -> test of functions', ' b l u -> Emirps betwenn l,u b 7700 8000', ' c n -> count of Emirps up to n c 99999', ' f n -> output n first Emirp f 20', ' n -> output the n.th Emirps 10000');   StepToNextPrimeEnd : Array[0..9] of byte = (1,0,3,0,7,7,7,0,9,0);   base = 10;   var s: AnsiString; pow, powLen : NativeUint;   procedure OutputHelp; var i : NativeUint; Begin For i := Low(helptext) to High(helptext) do writeln(helptext[i]); writeln; end;   function GetNumber(const s: string;var n:NativeUint):boolean; var ErrCode: Word; Begin val(s,n,Errcode); result := ErrCode = 0; end;   procedure RvsStr(var s: AnsiString); var i, j: NativeUint; swapChar : Ansichar; Begin i := 1; j := Length(s); While j>i do Begin swapChar:= s[i];s[i] := s[j];s[j] := swapChar; inc(i);dec(j) end; end;   function RvsNumL(var n: NativeUint):NativeUint; //reverse and last digit var q, c: NativeUint; Begin result := n; q := 0; repeat c:= result div Base; q := q*Base+(result-c*Base); result := c; until result < Base; n := q*Base+result;   end;   procedure InitP(var p: NativeUint); Begin powLen := 2; pow := Base; InitPrime; repeat p :=NextPrime until p >= 11; end;   function isEmirp(p: NativeUint):boolean; var rvsp: NativeUint; Begin s := IntToStr(p); result := StepToNextPrimeEnd[Ord(s[1])-48] = 0; IF result then Begin RvsStr(s); rvsp := StrToInt(s); result := false; IF rvsp<>p then result := isPrime(rvsp); end; end;   function NextEmirp:NativeUint; var r,Ldgt: NativeUint; Begin result:= NextPrime; repeat r := result; //reverse Ldgt := RvsNumL(r); Ldgt := StepToNextPrimeEnd[Ldgt]; IF Ldgt = 0 then Begin IF r<>result then IF isPrime(r) then EXIT; result:= NextPrime; end else Begin while actPrime > pow*Base do Begin inc(PowLen); pow := pow*base; end; result := Ldgt*pow; result := PrimeGELimit(result); end; until false; end;   function GetIthEmirp(i: NativeUint):NativeUint; var p : NativeUint; Begin InitP(p); Repeat dec(i); p:= NextEmirp; until i = 0; result := p; end;   procedure nFirstEmirp(n: NativeUint); var p : NativeUint;   Begin InitP(p); Writeln('the first ',n,' Emirp primE: '); Repeat dec(n); p:= NextEmirp; write(p,' '); until n = 0; Writeln; end;   function CntToLimit(n: NativeUint):NativeUint; var p,cnt : NativeUint; Begin cnt := 0; InitP(p); p:= NextEmirp; While p <= n do Begin inc(cnt); p:= NextEmirp; end; result := cnt; end;   procedure InRange(l,u:NativeUint); var p : NativeUint; b : boolean; Begin InitP(p); IF l > u then Begin p:=l;l:=u;u:=p end; Writeln('Emirp primes between ',l,' and ',u,' : '); p := PrimeGELimit(l);   b := IsEmirp(p); if b then write(p,' '); p:= NextEmirp; IF (p> u) AND NOT b then Writeln('none') else Begin while p < u do Begin write(p,' '); p:= NextEmirp; end; Writeln; end; end;   var i,u: NativeUint; select : char; Begin IF paramcount >= 1 then select := Lowercase(paramstr(1)[1]); case paramcount of 1: Begin if select='t' then Begin nFirstEmirp(20); InRange(7700,8000); Writeln('the ',10000,'.th Emirp prime: ',GetIthEmirp(10000)); writeln(CntToLimit(9999),' Emirp primes up to ',9999); // as a gag InRange(400000000,700000000); end else IF GetNumber(paramstr(1),i) then Writeln('the ',i,'.th Emirp prime: ',GetIthEmirp(i)) else OutPutHelp; end; 2: Begin case select of 'c': If GetNumber(paramstr(2),i) then writeln(CntToLimit(i),' Eemirp primes up to ',i) else OutPutHelp; 'f': If GetNumber(paramstr(2),i) then nFirstEmirp(i) else OutPutHelp; else OutPutHelp; end; end; 3: IF (select ='b') AND GetNumber(paramstr(2),i) AND GetNumber(paramstr(3),u) Then InRange(i,u) else OutPutHelp; else OutPutHelp; end; End.
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
#Harbour
Harbour
// in Harbour we have several functions to check emptiness of a string, f.e. hb_IsNull(), Len(), Empty() et.c., // we can also use comparison expressions like [cString == ""] and [cString != ""], yet the most convenient // of them is `Empty()` (but that depends on personal coding style). cString := "" ? Empty( cString ) // --> TRUE IF ! Empty( cString ) // --> FALSE ? cString ENDIF
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
#Haskell
Haskell
import Control.Monad   -- In Haskell strings are just lists (of characters), so we can use the function -- 'null', which applies to all lists. We don't want to use the length, since -- Haskell allows infinite lists.   main = do let s = "" when (null s) (putStrLn "Empty.") when (not $ null s) (putStrLn "Not empty.")
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Falcon
Falcon
>
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#FALSE
FALSE
 
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Fantom
Fantom
class Main { public static Void main () {} }
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
#MiniScript
MiniScript
entropy = function(s) count = {} for c in s if count.hasIndex(c) then count[c] = count[c]+1 else count[c] = 1 end for sum = 0 for x in count.values countOverN = x / s.len sum = sum + countOverN * log(countOverN, 2) end for return -sum end function   print entropy("1223334444")
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
#Modula-2
Modula-2
MODULE Entropy; FROM InOut IMPORT WriteString, WriteLn; FROM RealInOut IMPORT WriteReal; FROM Strings IMPORT Length; FROM MathLib IMPORT ln;   PROCEDURE entropy(s: ARRAY OF CHAR): REAL; VAR freq: ARRAY [0..255] OF CARDINAL; i, length: CARDINAL; h, f: REAL; BEGIN (* the entropy of the empty string is zero *) length := Length(s); IF length = 0 THEN RETURN 0.0; END;   (* find the frequency of each character *) FOR i := 0 TO 255 DO freq[i] := 0; END; FOR i := 0 TO length-1 DO INC(freq[ORD(s[i])]); END;   (* calculate the component for each character *) h := 0.0; FOR i := 0 TO 255 DO IF freq[i] # 0 THEN f := FLOAT(freq[i]) / FLOAT(length); h := h - f * (ln(f) / ln(2.0)); END; END; RETURN h; END entropy;   BEGIN WriteReal(entropy("1223334444"), 14); WriteLn; END Entropy.
http://rosettacode.org/wiki/Ethiopian_multiplication
Ethiopian multiplication
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last in the same column, until you write a value of 1. In the right-hand column repeatedly double the last number and write the result below. stop when you add a result in the same row as where the left hand column shows 1. Examine the table produced and discard any row where the value in the left column is even. Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together For example:   17 × 34 17 34 Halving the first column: 17 34 8 4 2 1 Doubling the second column: 17 34 8 68 4 136 2 272 1 544 Strike-out rows whose first cell is even: 17 34 8 68 4 136 2 272 1 544 Sum the remaining numbers in the right-hand column: 17 34 8 -- 4 --- 2 --- 1 544 ==== 578 So 17 multiplied by 34, by the Ethiopian method is 578. Task The task is to define three named functions/methods/procedures/subroutines: one to halve an integer, one to double an integer, and one to state if an integer is even. Use these functions to create a function that does Ethiopian multiplication. References Ethiopian multiplication explained (BBC Video clip) A Night Of Numbers - Go Forth And Multiply (Video) Russian Peasant Multiplication Programming Praxis: Russian Peasant Multiplication
#Haskell
Haskell
import Prelude hiding (odd) import Control.Monad (join)   halve :: Int -> Int halve = (`div` 2)   double :: Int -> Int double = join (+)   odd :: Int -> Bool odd = (== 1) . (`mod` 2)   ethiopicmult :: Int -> Int -> Int ethiopicmult a b = sum $ map snd $ filter (odd . fst) $ zip (takeWhile (>= 1) $ iterate halve a) (iterate double b)   main :: IO () main = print $ ethiopicmult 17 34 == 17 * 34
http://rosettacode.org/wiki/Equilibrium_index
Equilibrium index
An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices. For example, in a sequence   A {\displaystyle A} :   A 0 = − 7 {\displaystyle A_{0}=-7}   A 1 = 1 {\displaystyle A_{1}=1}   A 2 = 5 {\displaystyle A_{2}=5}   A 3 = 2 {\displaystyle A_{3}=2}   A 4 = − 4 {\displaystyle A_{4}=-4}   A 5 = 3 {\displaystyle A_{5}=3}   A 6 = 0 {\displaystyle A_{6}=0} 3   is an equilibrium index, because:   A 0 + A 1 + A 2 = A 4 + A 5 + A 6 {\displaystyle A_{0}+A_{1}+A_{2}=A_{4}+A_{5}+A_{6}} 6   is also an equilibrium index, because:   A 0 + A 1 + A 2 + A 3 + A 4 + A 5 = 0 {\displaystyle A_{0}+A_{1}+A_{2}+A_{3}+A_{4}+A_{5}=0} (sum of zero elements is zero) 7   is not an equilibrium index, because it is not a valid index of sequence A {\displaystyle A} . Task; Write a function that, given a sequence, returns its equilibrium indices (if any). Assume that the sequence may be very long.
#XPL0
XPL0
code Ran=1, ChOut=8, IntOut=11; def Size = 1_000_000; int I, S, A(Size), Hi(Size), Lo(Size); [for I:= 0 to Size-1 do A(I):= Ran(100) - 50; S:= 0; for I:= 0 to Size-1 do [S:= S+A(I); Lo(I):= S]; S:= 0; for I:= Size-1 downto 0 do [S:= S+A(I); Hi(I):= S]; for I:= 0 to Size-1 do if Lo(I) = Hi(I) then [IntOut(0, I); ChOut(0, ^ )]; ]
http://rosettacode.org/wiki/Equilibrium_index
Equilibrium index
An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices. For example, in a sequence   A {\displaystyle A} :   A 0 = − 7 {\displaystyle A_{0}=-7}   A 1 = 1 {\displaystyle A_{1}=1}   A 2 = 5 {\displaystyle A_{2}=5}   A 3 = 2 {\displaystyle A_{3}=2}   A 4 = − 4 {\displaystyle A_{4}=-4}   A 5 = 3 {\displaystyle A_{5}=3}   A 6 = 0 {\displaystyle A_{6}=0} 3   is an equilibrium index, because:   A 0 + A 1 + A 2 = A 4 + A 5 + A 6 {\displaystyle A_{0}+A_{1}+A_{2}=A_{4}+A_{5}+A_{6}} 6   is also an equilibrium index, because:   A 0 + A 1 + A 2 + A 3 + A 4 + A 5 = 0 {\displaystyle A_{0}+A_{1}+A_{2}+A_{3}+A_{4}+A_{5}=0} (sum of zero elements is zero) 7   is not an equilibrium index, because it is not a valid index of sequence A {\displaystyle A} . Task; Write a function that, given a sequence, returns its equilibrium indices (if any). Assume that the sequence may be very long.
#Yorick
Yorick
func equilibrium_indices(A) { return where(A(psum) == A(::-1)(psum)(::-1)); }
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.
#Python
Python
def eulers_sum_of_powers(): max_n = 250 pow_5 = [n**5 for n in range(max_n)] pow5_to_n = {n**5: n for n in range(max_n)} for x0 in range(1, max_n): for x1 in range(1, x0): for x2 in range(1, x1): for x3 in range(1, x2): pow_5_sum = sum(pow_5[i] for i in (x0, x1, x2, x3)) if pow_5_sum in pow5_to_n: y = pow5_to_n[pow_5_sum] return (x0, x1, x2, x3, y)   print("%i**5 + %i**5 + %i**5 + %i**5 == %i**5" % eulers_sum_of_powers())
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
#PowerBASIC
PowerBASIC
function fact1#(n%) local i%,r# r#=1 for i%=1 to n% r#=r#*i% next fact1#=r# end function   function fact2#(n%) if n%<=2 then fact2#=n% else fact2#=fact2#(n%-1)*n% end function   for i%=1 to 20 print i%,fact1#(i%),fact2#(i%) next
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.
#Julia
Julia
iseven(i), isodd(i)
http://rosettacode.org/wiki/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd. Use modular congruences: i ≡ 0 (mod 2) iff i is even. i ≡ 1 (mod 2) iff i is odd.
#K
K
  oddp: {:[x!2;1;0]} /Returns 1 if arg. is odd evenp: {~oddp[x]} /Returns 1 if arg. is even   Examples: oddp 32 0 evenp 32 1  
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
#Tcl
Tcl
package require Tcl 8.5 proc binom {n k} { # Compute the top half of the division; this is n!/(n-k)! set pTop 1 for {set i $n} {$i > $n - $k} {incr i -1} { set pTop [expr {$pTop * $i}] }   # Compute the bottom half of the division; this is k! set pBottom 1 for {set i $k} {$i > 1} {incr i -1} { set pBottom [expr {$pBottom * $i}] }   # Integer arithmetic divide is correct here; the factors always cancel out return [expr {$pTop / $pBottom}] }
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
#TI-83_BASIC
TI-83 BASIC
10 nCr 4
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).
#Perl
Perl
use feature 'say'; use ntheory qw(forprimes is_prime);   # Return the first $count emirps using expanding segments. # Can efficiently generate millions of emirps. sub emirp_list { my $count = shift; my($i, $inc, @n) = (13, 100+10*$count); while (@n < $count) { forprimes { push @n, $_ if is_prime(reverse $_) && $_ ne reverse($_); } $i, $i+$inc-1; ($i, $inc) = ($i+$inc, int($inc * 1.03) + 1000); } splice @n, $count; # Trim off excess emirps @n; }   say "First 20: ", join " ", emirp_list(20); print "Between 7700 and 8000:"; forprimes { print " $_" if is_prime(reverse $_) && $_ ne reverse($_) } 7700,8000; print "\n"; say "The 10_000'th emirp: ", (emirp_list(10000))[-1];
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
#HolyC
HolyC
/* assign an empty string */ U8 *str = StrNew(""); /* or */ U8 *str = "";   /* to test if string is empty */ if (StrLen(str) == 0) { ... } /* or compare to a known empty string. "== 0" means strings are equal */ if (StrCmp(str, "") == 0) { ... }   /* to test if string is not empty */ if (StrLen(str)) { ... }
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
#i
i
software { s = ""   // Can either compare the string to an empty string or // test if the length is zero. if s = "" or #s = 0 print("Empty string!") end   if s - "" or #s - 0 print("Not an empty string!") end }  
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#FBSL
FBSL
;
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Fermat
Fermat
;
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Fish
Fish
 
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
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref savelog symbols   runSample(Arg) return   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /* REXX *************************************************************** * 28.02.2013 Walter Pachl **********************************************************************/ method getShannonEntropy(s = "1223334444") public static --trace var occ c chars n cn i e p pl Numeric Digits 30 occ = 0 chars = '' n = 0 cn = 0 Loop i = 1 To s.length() c = s.substr(i, 1) If chars.pos(c) = 0 Then Do cn = cn + 1 chars = chars || c End occ[c] = occ[c] + 1 n = n + 1 End i p = '' Loop ci = 1 To cn c = chars.substr(ci, 1) p[c] = occ[c] / n End ci e = 0 Loop ci = 1 To cn c = chars.substr(ci, 1) pl = log2(p[c]) e = e + p[c] * pl End ci Return -e   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method log2(a = double) public static binary returns double return Math.log(a) / Math.log(2)   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method runSample(Arg) public static parse Arg sstr if sstr = '' then sstr = '1223334444' - '1223334444555555555' - '122333' - '1227774444' - 'aaBBcccDDDD' - '1234567890abcdefghijklmnopqrstuvwxyz' - 'Rosetta_Code' say 'Calculating Shannon''s entropy for the following list:' say '['(sstr.space(1, ',')).changestr(',', ', ')']' say entropies = 0 ssMax = 0 -- This crude sample substitutes a '_' character for a space in the input strings loop w_ = 1 to sstr.words() ss = sstr.word(w_) ssMax = ssMax.max(ss.length()) ss_ = ss.changestr('_', ' ') entropy = getShannonEntropy(ss_) entropies[ss] = entropy end w_ loop report = 1 to sstr.words() ss = sstr.word(report) ss_ = ss.changestr('_', ' ') Say 'Shannon entropy of' ('"'ss_'"').right(ssMax + 2)':' entropies[ss].format(null, 12) end report return  
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
#HicEst
HicEst
WRITE(Messagebox) ethiopian( 17, 34 ) END ! of "main"   FUNCTION ethiopian(x, y) ethiopian = 0 left = x right = y DO i = x, 1, -1 IF( isEven(left) == 0 ) ethiopian = ethiopian + right IF( left == 1 ) RETURN left = halve(left) right = double(right) ENDDO END   FUNCTION halve( x ) halve = INT( x/2 ) END   FUNCTION double( x ) double = 2 * x END   FUNCTION isEven( x ) isEven = MOD(x, 2) == 0 END
http://rosettacode.org/wiki/Equilibrium_index
Equilibrium index
An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices. For example, in a sequence   A {\displaystyle A} :   A 0 = − 7 {\displaystyle A_{0}=-7}   A 1 = 1 {\displaystyle A_{1}=1}   A 2 = 5 {\displaystyle A_{2}=5}   A 3 = 2 {\displaystyle A_{3}=2}   A 4 = − 4 {\displaystyle A_{4}=-4}   A 5 = 3 {\displaystyle A_{5}=3}   A 6 = 0 {\displaystyle A_{6}=0} 3   is an equilibrium index, because:   A 0 + A 1 + A 2 = A 4 + A 5 + A 6 {\displaystyle A_{0}+A_{1}+A_{2}=A_{4}+A_{5}+A_{6}} 6   is also an equilibrium index, because:   A 0 + A 1 + A 2 + A 3 + A 4 + A 5 = 0 {\displaystyle A_{0}+A_{1}+A_{2}+A_{3}+A_{4}+A_{5}=0} (sum of zero elements is zero) 7   is not an equilibrium index, because it is not a valid index of sequence A {\displaystyle A} . Task; Write a function that, given a sequence, returns its equilibrium indices (if any). Assume that the sequence may be very long.
#zkl
zkl
fcn equilibrium(lst){ // two pass reg acc=List(), left=0,right=lst.sum(0),i=0; foreach x in (lst){ right-=x; if(left==right) acc.write(i); i+=1; left+=x; } acc }
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.
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 DATA 7,-7,1,5,2,-4,3,0 20 READ n 30 DIM a(n): LET sum=0: LET leftsum=0: LET s$="" 40 FOR i=1 TO n: READ a(i): LET sum=sum+a(i): NEXT i 50 FOR i=1 TO n 60 LET sum=sum-a(i) 70 IF leftsum=sum THEN LET s$=s$+STR$ i+" " 80 LET leftsum=leftsum+a(i) 90 NEXT i 100 PRINT "Numbers: "; 110 FOR i=1 TO n: PRINT a(i);" ";: NEXT i 120 PRINT '"Indices: ";s$
http://rosettacode.org/wiki/Euler%27s_sum_of_powers_conjecture
Euler's sum of powers conjecture
There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin. Euler's (disproved) sum of powers   conjecture At least k positive kth powers are required to sum to a kth power, except for the trivial case of one kth power: yk = yk In 1966,   Leon J. Lander   and   Thomas R. Parkin   used a brute-force search on a   CDC 6600   computer restricting numbers to those less than 250. Task Write a program to search for an integer solution for: x05 + x15 + x25 + x35 == y5 Where all   xi's   and   y   are distinct integers between   0   and   250   (exclusive). Show an answer here. Related tasks   Pythagorean quadruples.   Pythagorean triples.
#QL_SuperBASIC
QL SuperBASIC
1 CLS 2 DIM i%(255,6) : DIM a%(6) : DIM c%(6) 3 DIM v%(255,6) : DIM b%(6) : DIM d%(29) 4 RESTORE 137 6 FOR m=0 TO 6 7 READ t% 8 FOR j=1 TO 255 11 LET i%(j,m)=j MOD t% 12 LET v%(j,m)=(i%(j,m) * i%(j,m))MOD t% 14 LET v%(j,m)=(v%(j,m) * v%(j,m))MOD t% 15 LET v%(j,m)=(v%(j,m) * i%(j,m))MOD t% 17 END FOR j : END FOR m 19 PRINT "Abaci ready" 21 FOR j=10 TO 29: d%(j)=210+ j 24 FOR j=0 TO 9: d%(j)=240+ j 25 LET t%=48 30 FOR w=6 TO 246 STEP 3 33 LET o=w 42 FOR x=4 TO 248 STEP 2 44 IF o<x THEN o=x 46 FOR m=1 TO 6: a%(m)=i%((v%(w,m)+v%(x,m)),m) 50 FOR y=10 TO 245 STEP 5 54 IF o<y THEN o=y 56 FOR m=1 TO 6: b%(m)=i%((a%(m)+v%(y,m)),m) 57 FOR z=14 TO 245 STEP 7 59 IF o<z THEN o=z 60 FOR m=1 TO 6: c%(m)=i%((b%(m)+v%(z,m)),m) 65 LET s$="" : FOR m=1 TO 6: s$=s$&CHR$(c%(m)+t%) 70 LET o=o+1 : j=d%(i%((i%(w,0)+i%(x,0)+i%(y,0)+i%(z,0)),0)) 75 IF j<o THEN NEXT z 80 FOR k=j TO o STEP -30 85 LET e$="" : FOR m=1 TO 6: e$=e$&CHR$(v%(k,m)+t%) 90 IF s$=e$ THEN PRINT w,x,y,z,k,s$,e$: STOP 95 END FOR k : END FOR z : END FOR y : END FOR x : END FOR w 137 DATA 30,97,113,121,125,127,128  
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
#PowerShell
PowerShell
function Get-Factorial ($x) { if ($x -eq 0) { return 1 } return $x * (Get-Factorial ($x - 1)) }
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.
#Klingphix
Klingphix
( -5 5 ) [ dup print " " print 2 mod ( ["Odd"] ["Even"] ) if print nl ] for   " " input
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.
#Kotlin
Kotlin
// version 1.0.5-2   fun main(args: Array<String>) { while (true) { print("Enter an integer or 0 to finish : ") val n = readLine()!!.toInt() when { n == 0 -> return n % 2 == 0 -> println("Your number is even") else -> println("Your number is odd") } } }
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
#TI-89_BASIC
TI-89 BASIC
nCr(n,k)
http://rosettacode.org/wiki/Evaluate_binomial_coefficients
Evaluate binomial coefficients
This programming task, is to calculate ANY binomial coefficient. However, it has to be able to output   ( 5 3 ) {\displaystyle {\binom {5}{3}}} ,   which is   10. This formula is recommended: ( n k ) = n ! ( n − k ) ! k ! = n ( n − 1 ) ( n − 2 ) … ( n − k + 1 ) k ( k − 1 ) ( k − 2 ) … 1 {\displaystyle {\binom {n}{k}}={\frac {n!}{(n-k)!k!}}={\frac {n(n-1)(n-2)\ldots (n-k+1)}{k(k-1)(k-2)\ldots 1}}} See Also: Combinations and permutations Pascal's triangle The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#TXR
TXR
$ txr -p '(n-choose-k 20 15)' 15504
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).
#Phix
Phix
with javascript_semantics sequence emirps = {} function rev(integer n) integer res = 0 while n do res = res*10+remainder(n,10) n = floor(n/10) end while return res end function function emirp(integer n) if is_prime(n) then integer r = rev(n) if r!=n and is_prime(r) then return true end if end if return false end function procedure usage() printf(1,"use a single command line argument, with no spaces, eg \"1-20\" (first 20), \n") printf(1,"\"7700..8000\" (between 7700 and 8000), or \"10000\" (the 10,000th).\n") {} = wait_key() abort(0) end procedure procedure main(string arg3) sequence args integer n,m if find('-',arg3) then -- nth to mth emirp range args = scanf(arg3,"%d-%d") if length(args)!=1 then usage() end if {{n,m}} = args integer k = 1 while length(emirps)<m do if emirp(k) then emirps &= k end if k += 1 end while printf(1,"emirps %d to %d: %v\n",{n,m,emirps[n..m]}) elsif match("..",arg3) then -- emirps between n amd m args = scanf(arg3,"%d..%d") if length(args)!=1 then usage() end if {{n,m}} = args integer k = 1 while length(emirps)=0 or emirps[$]<m do if emirp(k) then emirps &= k end if k += 1 end while sequence s = {} for i=1 to length(emirps) do if emirps[i]>n then for j=i to length(emirps) do if emirps[j]>m then printf(1,"emirps between %d and %d: %v\n",{n,m,emirps[i..j-1]}) exit end if end for exit end if end for else -- nth emirp args = scanf(arg3,"%d") if length(args)!=1 then usage() end if {{n}} = args integer k = 1 while length(emirps)<n do if emirp(k) then emirps &= k end if k += 1 end while printf(1,"emirp %d: %d\n",{n,emirps[n]}) end if end procedure sequence cl = command_line() if length(cl)=2 then main("1-20") main("7700..8000") main("10000") elsif length(cl)=3 then main(cl[3]) else usage() end if
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
#Icon_and_Unicon
Icon and Unicon
s := "" # null string s := string('A'--'A') # ... converted from cset difference s := char(0)[0:0] # ... by slicing   s1 == "" # lexical comparison, could convert s1 to string s1 === "" # comparison won't force conversion *s1 = 0 # zero length, however, *x is polymorphic *string(s1) = 0 # zero length string   s1 ~== "" # non null strings comparisons s1 ~=== "" *string(s1) ~= 0   s := &null # NOT a null string, null type /s # test for null type \s # test for non-null type
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
#J
J
variable=: '' 0=#variable 1 0<#variable 0
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Forth
Forth
 
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Fortran
Fortran
end
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#FreeBASIC
FreeBASIC
 
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
#Nim
Nim
import tables, math   proc entropy(s: string): float = var t = initCountTable[char]() for c in s: t.inc(c) for x in t.values: result -= x/s.len * log2(x/s.len)   echo entropy("1223334444")
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
#Objeck
Objeck
use Collection;   class Entropy { function : native : GetShannonEntropy(result : String) ~ Float { frequencies := IntMap->New();   each(i : result) { c := result->Get(i);   if(frequencies->Has(c)) { count := frequencies->Find(c)->As(IntHolder); count->Set(count->Get() + 1); } else { frequencies->Insert(c, IntHolder->New(1)); }; };   length := result->Size(); entropy := 0.0;   counts := frequencies->GetValues(); each(i : counts) { count := counts->Get(i)->As(IntHolder)->Get(); freq := count->As(Float) / length; entropy += freq * (freq->Log() / 2.0->Log()); };   return -1 * entropy; }   function : Main(args : String[]) ~ Nil { inputs := [ "1223334444", "1223334444555555555", "122333", "1227774444", "aaBBcccDDDD", "1234567890abcdefghijklmnopqrstuvwxyz", "Rosetta Code"];   each(i : inputs) { input := inputs[i]; "Shannon entropy of '{$input}': "->Print(); GetShannonEntropy(inputs[i])->PrintLine(); }; } }
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
#Icon_and_Unicon
Icon and Unicon
procedure main(arglist) while ethiopian(integer(get(arglist)),integer(get(arglist))) # multiply successive pairs of command line arguments end   procedure ethiopian(i,j) # recursive Ethiopian multiplication return ( if not even(i) then j # this exploits that icon control expressions return values else 0 ) + ( if i ~= 0 then ethiopian(halve(i),double(j)) else 0 ) end   procedure double(i) return i * 2 end   procedure halve(i) return i / 2 end   procedure even(i) return ( i % 2 = 0, i ) end
http://rosettacode.org/wiki/Euler%27s_sum_of_powers_conjecture
Euler's sum of powers conjecture
There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin. Euler's (disproved) sum of powers   conjecture At least k positive kth powers are required to sum to a kth power, except for the trivial case of one kth power: yk = yk In 1966,   Leon J. Lander   and   Thomas R. Parkin   used a brute-force search on a   CDC 6600   computer restricting numbers to those less than 250. Task Write a program to search for an integer solution for: x05 + x15 + x25 + x35 == y5 Where all   xi's   and   y   are distinct integers between   0   and   250   (exclusive). Show an answer here. Related tasks   Pythagorean quadruples.   Pythagorean triples.
#Racket
Racket
#lang racket (define MAX 250) (define pow5 (make-vector MAX)) (for ([i (in-range 1 MAX)]) (vector-set! pow5 i (expt i 5))) (define pow5s (list->set (vector->list pow5))) (let/ec break (for* ([x0 (in-range 1 MAX)] [x1 (in-range 1 x0)] [x2 (in-range 1 x1)] [x3 (in-range 1 x2)]) (define sum (+ (vector-ref pow5 x0) (vector-ref pow5 x1) (vector-ref pow5 x2) (vector-ref pow5 x3))) (when (set-member? pow5s sum) (displayln (list x0 x1 x2 x3 (inexact->exact (round (expt sum 1/5))))) (break))))
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
#Processing
Processing
  int fact(int n){ if(n <= 1){ return 1; } else{ return n*fact(n-1); } }  
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.
#Lambdatalk
Lambdatalk
  {def is_odd {lambda {:i} {= {% :i 2} 1}}} -> is_odd   {def is_even {lambda {:i} {= {% :i 2} 0}}} -> is_even   {is_odd 2} -> false   {is_even 2} -> true  
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
#UNIX_Shell
UNIX Shell
#!/bin/sh n=5; k=3; calculate_factorial(){ partial_factorial=1; for (( i=1; i<="$1"; i++ )) do factorial=$(expr $i \* $partial_factorial) partial_factorial=$factorial   done echo $factorial }   n_factorial=$(calculate_factorial $n) k_factorial=$(calculate_factorial $k) n_minus_k_factorial=$(calculate_factorial `expr $n - $k`) binomial_coefficient=$(expr $n_factorial \/ $k_factorial \* 1 \/ $n_minus_k_factorial )   echo "Binomial Coefficient ($n,$k) = $binomial_coefficient"
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
#Ursala
Ursala
#import nat   choose = ~&ar^?\1! quotient^\~&ar product^/~&al ^|R/~& predecessor~~
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).
#PHP
PHP
<?php   function is_prime($n) { if ($n <= 3) { return $n > 1; } elseif (($n % 2 == 0) or ($n % 3 == 0)) { return false; } $i = 5; while ($i * $i <= $n) { if ($n % $i == 0) { return false; } $i += 2; if ($n % $i == 0) { return false; } $i += 4; } return true; }   function is_emirp($n) { $r = (int) strrev((string) $n); return (($r != $n) and is_prime($r) and is_prime($n)); }   $c = $x = 0; $first20 = $between = ''; do { $x++; if (is_emirp($x)) { $c++; if ($c <= 20) { $first20 .= $x . ' '; } if (7700 <= $x and $x <= 8000) { $between .= $x . ' '; } } } while ($c < 10000);   echo 'First twenty emirps :', PHP_EOL, $first20, PHP_EOL, 'Emirps between 7,700 and 8,000 :', PHP_EOL, $between, PHP_EOL, 'The 10,000th emirp :', PHP_EOL, $x, PHP_EOL;
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
#Java
Java
String s = ""; if(s != null && s.isEmpty()){//optionally, instead of "s.isEmpty()": "s.length() == 0" or "s.equals("")" System.out.println("s is empty"); }else{ System.out.println("s 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
#JavaScript
JavaScript
var s = ""; var s = new String();
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#friendly_interactive_shell
friendly interactive shell
 
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Frink
Frink
 
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#FunL
FunL
 
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
#OCaml
OCaml
(* generic OCaml, using a mutable Hashtbl *)   (* pre-bake & return an inner-loop function to bin & assemble a character frequency map *) let get_fproc (m: (char, int) Hashtbl.t) :(char -> unit) = (fun (c:char) -> try Hashtbl.replace m c ( (Hashtbl.find m c) + 1) with Not_found -> Hashtbl.add m c 1)     (* pre-bake and return an inner-loop function to do the actual entropy calculation *) let get_calc (slen:int) :(float -> float) = let slen_float = float_of_int slen in let log_2 = log 2.0 in   (fun v -> let pt = v /. slen_float in pt *. ((log pt) /. log_2) )     (* main function, given a string argument it: builds a (mutable) frequency map (initial alphabet size of 255, but it's auto-expanding), extracts the relative probability values into a list, folds-in the basic entropy calculation and returns the result. *) let shannon (s:string) :float = let freq_hash = Hashtbl.create 255 in String.iter (get_fproc freq_hash) s;   let relative_probs = Hashtbl.fold (fun k v b -> (float v)::b) freq_hash [] in let calc = get_calc (String.length s) in   -1.0 *. List.fold_left (fun b x -> b +. calc x) 0.0 relative_probs  
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
#J
J
double =: 2&* halve =:  %&2 NB. or the primitive -: odd =: 2&|   ethiop =: +/@(odd@] # (double~ <@#)) (1>.<.@halve)^:a:
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.
#Raku
Raku
constant MAX = 250;   my %po5{Int}; my %sum2{Int};   (1..MAX).map: -> $i { %po5{$i**5} = $i; for 1..MAX -> $j { %sum2{$i**5 + $j**5} = ($i, $j); } }   my @sk = %sum2.keys.sort; %po5.keys.sort.race.map: -> $p { for @sk -> $s { next if $p <= $s; if %sum2{$p - $s} { say ((sort |%sum2{$s}[],|%sum2{$p-$s}[]) X~ '⁵').join(' + ') ~ " =  %po5{$p}" ~ "⁵"; exit; } } }
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
#Prolog
Prolog
fact(X, 1) :- X<2. fact(X, F) :- Y is X-1, fact(Y,Z), F is Z*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.
#L.2B.2B
L++
(defn bool isEven (int x) (return (% x 2)))
http://rosettacode.org/wiki/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd. Use modular congruences: i ≡ 0 (mod 2) iff i is even. i ≡ 1 (mod 2) iff i is odd.
#LabVIEW
LabVIEW
: even? 2 % not ; : odd? 2 % ; 1 even? . # 0 1 odd? . # 1