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/Ackermann_function
Ackermann function
The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { n + 1 if  m = 0 A ( m − 1 , 1 ) if  m > 0  and  n = 0 A ( m − 1 , A ( m , n − 1 ) ) if  m > 0  and  n > 0. {\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}} Its arguments are never negative and it always terminates. Task Write a function which returns the value of A ( m , n ) {\displaystyle A(m,n)} . Arbitrary precision is preferred (since the function grows so quickly), but not required. See also Conway chained arrow notation for the Ackermann function.
#AppleScript
AppleScript
on ackermann(m, n) if m is equal to 0 then return n + 1 if n is equal to 0 then return ackermann(m - 1, 1) return ackermann(m - 1, ackermann(m, n - 1)) end ackermann
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications
Abundant, deficient and perfect number classifications
These define three classifications of positive integers based on their   proper divisors. Let   P(n)   be the sum of the proper divisors of   n   where the proper divisors are all positive divisors of   n   other than   n   itself. if P(n) < n then n is classed as deficient (OEIS A005100). if P(n) == n then n is classed as perfect (OEIS A000396). if P(n) > n then n is classed as abundant (OEIS A005101). Example 6   has proper divisors of   1,   2,   and   3. 1 + 2 + 3 = 6,   so   6   is classed as a perfect number. Task Calculate how many of the integers   1   to   20,000   (inclusive) are in each of the three classes. Show the results here. Related tasks   Aliquot sequence classifications.   (The whole series from which this task is a subset.)   Proper divisors   Amicable pairs
#C.23
C#
using System; using System.Linq;   public class Program { public static void Main() { int abundant, deficient, perfect; var sw = System.Diagnostics.Stopwatch.StartNew(); ClassifyNumbers.UsingSieve(20000, out abundant, out deficient, out perfect); sw.Stop(); Console.WriteLine($"Abundant: {abundant}, Deficient: {deficient}, Perfect: {perfect} {sw.Elapsed.TotalMilliseconds} ms"); sw.Restart(); ClassifyNumbers.UsingOptiDivision(20000, out abundant, out deficient, out perfect); Console.WriteLine($"Abundant: {abundant}, Deficient: {deficient}, Perfect: {perfect} {sw.Elapsed.TotalMilliseconds} ms"); sw.Restart(); ClassifyNumbers.UsingDivision(20000, out abundant, out deficient, out perfect); Console.WriteLine($"Abundant: {abundant}, Deficient: {deficient}, Perfect: {perfect} {sw.Elapsed.TotalMilliseconds} ms"); } }   public static class ClassifyNumbers { //Fastest way, but uses memory public static void UsingSieve(int bound, out int abundant, out int deficient, out int perfect) { abundant = perfect = 0; //For very large bounds, this array can get big. int[] sum = new int[bound + 1]; for (int divisor = 1; divisor <= bound >> 1; divisor++) for (int i = divisor << 1; i <= bound; i += divisor) sum[i] += divisor; for (int i = 1; i <= bound; i++) { if (sum[i] > i) abundant++; else if (sum[i] == i) perfect++; } deficient = bound - abundant - perfect; }   //Slower, optimized, but doesn't use storage public static void UsingOptiDivision(int bound, out int abundant, out int deficient, out int perfect) { abundant = perfect = 0; int sum = 0; for (int i = 2, d, r = 1; i <= bound; i++) { if ((d = r * r - i) < 0) r++; for (int x = 2; x < r; x++) if (i % x == 0) sum += x + i / x; if (d == 0) sum += r; switch (sum.CompareTo(i)) { case 0: perfect++; break; case 1: abundant++; break; } sum = 1; } deficient = bound - abundant - perfect; }   //Much slower, doesn't use storage and is un-optimized public static void UsingDivision(int bound, out int abundant, out int deficient, out int perfect) { abundant = perfect = 0; for (int i = 2; i <= bound; i++) { int sum = Enumerable.Range(1, (i + 1) / 2) .Where(div => i % div == 0).Sum(); switch (sum.CompareTo(i)) { case 0: perfect++; break; case 1: abundant++; break; } } deficient = bound - abundant - perfect; } }
http://rosettacode.org/wiki/Align_columns
Align columns
Given a text file of many lines, where fields within a line are delineated by a single 'dollar' character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be either left justified, right justified, or center justified within its column. Use the following text to test your programs: Given$a$text$file$of$many$lines,$where$fields$within$a$line$ are$delineated$by$a$single$'dollar'$character,$write$a$program that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$ column$are$separated$by$at$least$one$space. Further,$allow$for$each$word$in$a$column$to$be$either$left$ justified,$right$justified,$or$center$justified$within$its$column. Note that:   The example input texts lines may, or may not, have trailing dollar characters.   All columns should share the same alignment.   Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.   Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.   The minimum space between columns should be computed from the text and not hard-coded.   It is not a requirement to add separating characters between or around columns. 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
#COBOL
COBOL
  identification division. program-id. AlignColumns.   data division. working-storage section. *>-> Constants 78 MAX-LINES value 6. 78 MAX-LINE-SIZE value 66. 78 MAX-COLUMNS value 12. 78 MAX-COLUMN-SIZE value 16. *>-> Indexes 01 w-idx pic is 9(2). 01 w-idy pic is 9(2). 01 w-pos pic is 9(3). *>-> Data structures 01 w-lines. 05 w-line pic is x(MAX-LINE-SIZE) occurs MAX-LINES. 01 w-column-sizes. 05 w-column-size pic is 99 occurs MAX-COLUMNS value zeros. 01 w-matrix. 05 filler occurs MAX-LINES. 10 filler occurs MAX-COLUMNS. 15 w-content pic is x(MAX-COLUMN-SIZE). *>-> Output 01 w-line-out pic is x(120). *>-> Data alignment 01 w-alignment pic is x(1). 88 alignment-left value is "L". 88 alignment-center value is "C". 88 alignment-right value is "R".   procedure division. main. move "Given$a$text$file$of$many$lines,$where$fields$within$a$line$" to w-line(1) move "are$delineated$by$a$single$'dollar'$character,$write$a$program" to w-line(2) move "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$" to w-line(3) move "column$are$separated$by$at$least$one$space." to w-line(4) move "Further,$allow$for$each$word$in$a$column$to$be$either$left$" to w-line(5) move "justified,$right$justified,$or$center$justified$within$its$column." to w-line(6) perform calculate-size-columns set alignment-left to true perform show-content set alignment-center to true perform show-content set alignment-right to true perform show-content goback . calculate-size-columns. perform varying w-idx from 1 by 1 until w-idx > MAX-LINES unstring w-line(w-idx) delimited by "$" into w-content(w-idx, 1), w-content(w-idx, 2), w-content(w-idx, 3), w-content(w-idx, 4), w-content(w-idx, 5), w-content(w-idx, 6), w-content(w-idx, 7), w-content(w-idx, 8), w-content(w-idx, 9), w-content(w-idx, 10), w-content(w-idx, 11), w-content(w-idx, 12), perform varying w-idy from 1 by 1 until w-idy > MAX-COLUMNS if function stored-char-length(w-content(w-idx, w-idy)) > w-column-size(w-idy) move function stored-char-length(w-content(w-idx, w-idy)) to w-column-size(w-idy) end-if end-perform end-perform . show-content. move all "-" to w-line-out display w-line-out perform varying w-idx from 1 by 1 until w-idx > MAX-LINES move spaces to w-line-out move 1 to w-pos perform varying w-idy from 1 by 1 until w-idy > MAX-COLUMNS call "C$JUSTIFY" using w-content(w-idx, w-idy)(1:w-column-size(w-idy)), w-alignment move w-content(w-idx, w-idy) to w-line-out(w-pos:w-column-size(w-idy)) compute w-pos = w-pos + w-column-size(w-idy) + 1 end-perform display w-line-out end-perform .  
http://rosettacode.org/wiki/Active_object
Active object
In object-oriented programming an object is active when its state depends on clock. Usually an active object encapsulates a task that updates the object's state. To the outer world the object looks like a normal object with methods that can be called from outside. Implementation of such methods must have a certain synchronization mechanism with the encapsulated task in order to prevent object's state corruption. A typical instance of an active object is an animation widget. The widget state changes with the time, while as an object it has all properties of a normal widget. The task Implement an active integrator object. The object has an input and output. The input can be set using the method Input. The input is a function of time. The output can be queried using the method Output. The object integrates its input over the time and the result becomes the object's output. So if the input is K(t) and the output is S, the object state S is changed to S + (K(t1) + K(t0)) * (t1 - t0) / 2, i.e. it integrates K using the trapeze method. Initially K is constant 0 and S is 0. In order to test the object: set its input to sin (2π f t), where the frequency f=0.5Hz. The phase is irrelevant. wait 2s set the input to constant 0 wait 0.5s Verify that now the object's output is approximately 0 (the sine has the period of 2s). The accuracy of the result will depend on the OS scheduler time slicing and the accuracy of the clock.
#Phix
Phix
requires("0.8.2") integer xlock = init_cs() class integrator -- -- Integrates input function f over time -- v + (t1 - t0) * (f(t1) + f(t0)) / 2 -- integer f -- function f(atom t); (see note) atom interval, t0, k0 = 0, v = 0 bool running public integer id procedure set_func(integer rid) this.f = rid end procedure procedure update() enter_cs(xlock) integer f = this.f -- (nb: no "this") atom t1 = time(), k1 = f(t1) v += (t1 - t0) * (k1 + k0) / 2 t0 = t1 k0 = k1 leave_cs(xlock) end procedure procedure tick() running = true while running do sleep(interval) update() end while end procedure procedure stop() running = false wait_thread(id) end procedure function get_output() return v end function end class function new_integrator(integer rid, atom interval) integrator i = new({rid,interval,time()}) i.update() i.id = create_thread(i.tick,{i}) return i end function function zero(atom /*t*/) return 0 end function function sine(atom t) return sin(2*PI*0.5*t) end function integrator i = new_integrator(sine,0.01); sleep(2) ?i.get_output() i.set_func(zero) sleep(0.5) i.stop() ?i.get_output()
http://rosettacode.org/wiki/Aliquot_sequence_classifications
Aliquot sequence classifications
An aliquot sequence of a positive integer K is defined recursively as the first member being K and subsequent members being the sum of the Proper divisors of the previous term. If the terms eventually reach 0 then the series for K is said to terminate. There are several classifications for non termination: If the second term is K then all future terms are also K and so the sequence repeats from the first term with period 1 and K is called perfect. If the third term would be repeating K then the sequence repeats with period 2 and K is called amicable. If the Nth term would be repeating K for the first time, with N > 3 then the sequence repeats with period N - 1 and K is called sociable. Perfect, amicable and sociable numbers eventually repeat the original number K; there are other repetitions... Some K have a sequence that eventually forms a periodic repetition of period 1 but of a number other than K, for example 95 which forms the sequence 95, 25, 6, 6, 6, ... such K are called aspiring. K that have a sequence that eventually forms a periodic repetition of period >= 2 but of a number other than K, for example 562 which forms the sequence 562, 284, 220, 284, 220, ... such K are called cyclic. And finally: Some K form aliquot sequences that are not known to be either terminating or periodic; these K are to be called non-terminating. For the purposes of this task, K is to be classed as non-terminating if it has not been otherwise classed after generating 16 terms or if any term of the sequence is greater than 2**47 = 140,737,488,355,328. Task Create routine(s) to generate the aliquot sequence of a positive integer enough to classify it according to the classifications given above. Use it to display the classification and sequences of the numbers one to ten inclusive. Use it to show the classification and sequences of the following integers, in order: 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, and optionally 15355717786080. Show all output on this page. Related tasks   Abundant, deficient and perfect number classifications. (Classifications from only the first two members of the whole sequence).   Proper divisors   Amicable pairs
#QBasic
QBasic
DECLARE FUNCTION PDtotal! (n!) DECLARE SUB PrintAliquotClassifier (K!) CLS CONST limite = 10000000   DIM nums(22) DATA 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 28, 496 DATA 220, 1184, 12496, 790, 909, 562, 1064, 1488   FOR n = 1 TO UBOUND(nums) READ nums(n) PRINT "Number"; nums(n); " :"; PrintAliquotClassifier (nums(n)) NEXT n   PRINT "Program normal end." END   FUNCTION PDtotal (n) total = 0 FOR y = 2 TO n IF (n MOD y) = 0 THEN total = total + (n / y) NEXT y PDtotal = total END FUNCTION   SUB PrintAliquotClassifier (K) longit = 52: n = K: clase = 0: priorn = 0: inc = 0 DIM Aseq(longit)   FOR element = 2 TO longit Aseq(element) = PDtotal(n) PRINT Aseq(element); " "; COLOR 3 SELECT CASE Aseq(element) CASE 0 PRINT " Terminating": clase = 1: EXIT FOR CASE K AND element = 2 PRINT " Perfect": clase = 2: EXIT FOR CASE K AND element = 3 PRINT " Amicable": clase = 3: EXIT FOR CASE K AND element > 3 PRINT " Sociable": clase = 4: EXIT FOR CASE Aseq(element) <> K AND Aseq(element - 1) = Aseq(element) PRINT " Aspiring": clase = 5: EXIT FOR CASE Aseq(element) <> K AND Aseq(element - 2) = Aseq(element) PRINT " Cyclic": clase = 6: EXIT FOR END SELECT COLOR 7 n = Aseq(element) IF n > priorn THEN priorn = n: inc = inc + 1 ELSE inc = 0: priorn = 0 IF inc = 11 OR n > limite THEN EXIT FOR NEXT element IF clase = 0 THEN COLOR 12: PRINT " non-terminating" COLOR 7 END SUB
http://rosettacode.org/wiki/AKS_test_for_primes
AKS test for primes
The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles. The theorem on which the test is based can be stated as follows:   a number   p {\displaystyle p}   is prime   if and only if   all the coefficients of the polynomial expansion of ( x − 1 ) p − ( x p − 1 ) {\displaystyle (x-1)^{p}-(x^{p}-1)} are divisible by   p {\displaystyle p} . Example Using   p = 3 {\displaystyle p=3} : (x-1)^3 - (x^3 - 1) = (x^3 - 3x^2 + 3x - 1) - (x^3 - 1) = -3x^2 + 3x And all the coefficients are divisible by 3,   so 3 is prime. Note: This task is not the AKS primality test.   It is an inefficient exponential time algorithm discovered in the late 1600s and used as an introductory lemma in the AKS derivation. Task Create a function/subroutine/method that given   p {\displaystyle p}   generates the coefficients of the expanded polynomial representation of   ( x − 1 ) p {\displaystyle (x-1)^{p}} . Use the function to show here the polynomial expansions of   ( x − 1 ) p {\displaystyle (x-1)^{p}}   for   p {\displaystyle p}   in the range   0   to at least   7,   inclusive. Use the previous function in creating another function that when given   p {\displaystyle p}   returns whether   p {\displaystyle p}   is prime using the theorem. Use your test to generate a list of all primes under   35. As a stretch goal,   generate all primes under   50   (needs integers larger than 31-bit). References Agrawal-Kayal-Saxena (AKS) primality test (Wikipedia) Fool-Proof Test for Primes - Numberphile (Video). The accuracy of this video is disputed -- at best it is an oversimplification.
#Lua
Lua
-- AKS test for primes, in Lua, 6/23/2020 db local function coefs(n) local list = {[0]=1} for k = 0, n do list[k+1] = math.floor(list[k] * (n-k) / (k+1)) end for k = 1, n, 2 do list[k] = -list[k] end return list end   local function isprimeaks(n) local c = coefs(n) c[0], c[n] = c[0]-1, c[n]+1 for i = 0, n do if (c[i] % n ~= 0) then return false end end return true end   local function pprintcoefs(n, list) local result = "" for i = 0, n do local s = i==0 and "" or list[i]>=0 and " + " or " - " local c, e = math.abs(list[i]), n-i if (c==1 and e > 0) then c = "" end local x = e==0 and "" or e==1 and "x" or "x^"..e result = result .. s .. c .. x end print("(x-1)^" .. n .." : " .. result) end   for i = 0, 9 do pprintcoefs(i, coefs(i)) end   local primes = {} for i = 2, 53 do if (isprimeaks(i)) then primes[#primes+1] = i end end print(table.concat(primes, ", "))
http://rosettacode.org/wiki/Additive_primes
Additive primes
Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS entry:   A046704 additive primes.   the prime-numbers entry:   additive primes.   the geeks for geeks entry: additive prime number.   the prime-numbers fandom: additive primes.
#Ring
Ring
  load "stdlib.ring"   see "working..." + nl see "Additive primes are:" + nl   row = 0 limit = 500   for n = 1 to limit num = 0 if isprime(n) strn = string(n) for m = 1 to len(strn) num = num + number(strn[m]) next if isprime(num) row = row + 1 see "" + n + " " if row%10 = 0 see nl ok ok ok next   see nl + "found " + row + " additive primes." + nl see "done..." + nl  
http://rosettacode.org/wiki/Additive_primes
Additive primes
Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS entry:   A046704 additive primes.   the prime-numbers entry:   additive primes.   the geeks for geeks entry: additive prime number.   the prime-numbers fandom: additive primes.
#Ruby
Ruby
require "prime"   additive_primes = Prime.lazy.select{|prime| prime.digits.sum.prime? }   N = 500 res = additive_primes.take_while{|n| n < N}.to_a puts res.join(" ") puts "\n#{res.size} additive primes below #{N}."  
http://rosettacode.org/wiki/Almost_prime
Almost prime
A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,   where   k = 2 {\displaystyle k=2} ,   are the   semiprimes. Task Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for   1 <= K <= 5 {\displaystyle 1<=K<=5} . Related tasks   Semiprime   Category:Prime Numbers
#PicoLisp
PicoLisp
(de factor (N) (make (let (D 2 L (1 2 2 . (4 2 4 2 4 6 2 6 .)) M (sqrt N) ) (while (>= M D) (if (=0 (% N D)) (setq M (sqrt (setq N (/ N (link D)))) ) (inc 'D (pop 'L)) ) ) (link N) ) ) )   (de almost (N) (let (X 2 Y 0) (make (loop (when (and (nth (factor X) N) (not (cdr @))) (link X) (inc 'Y) ) (T (= 10 Y) 'done) (inc 'X) ) ) ) )   (for I 5 (println I '-> (almost I) ) )   (bye)
http://rosettacode.org/wiki/Almost_prime
Almost prime
A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,   where   k = 2 {\displaystyle k=2} ,   are the   semiprimes. Task Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for   1 <= K <= 5 {\displaystyle 1<=K<=5} . Related tasks   Semiprime   Category:Prime Numbers
#Potion
Potion
# Converted from C kprime = (n, k): p = 2, f = 0 while (f < k && p*p <= n): while (0 == n % p): n /= p f++. p++. n = if (n > 1): 1. else: 0. f + n == k.   1 to 5 (k): "k = " print, k print, ":" print i = 2, c = 0 while (c < 10): if (kprime(i, k)): " " print, i print, c++. i++ . "" say.
http://rosettacode.org/wiki/Anagrams
Anagrams
When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in them. Related tasks Word plays Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams 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
#FutureBasic
FutureBasic
  include "ConsoleWindow"   def tab 9   begin globals dim dynamic gDictionary(_maxLong) as Str255 end globals   local fn IsAnagram( word1 as Str31, word2 as Str31 ) as Boolean dim as long i, j, h, q dim as Boolean result   if word1[0] != word2[0] then result = _false : exit fn   for i = 0 to word1[0] h = 0 : q = 0 for j = 0 to word1[0] if word1[i] == word1[j] then h++ if word1[i] == word2[j] then q++ next if h != q then result = _false : exit fn next result = _true end fn = result   local fn LoadDictionaryToArray '~'1 dim as CFURLRef url dim as CFArrayRef arr dim as CFStringRef temp, cfStr dim as CFIndex elements dim as Handle h dim as Str255 s dim as long fileLen, i   kill dynamic gDictionary url = fn CFURLCreateWithFileSystemPath( _kCFAllocatorDefault, @"/usr/share/dict/words", _kCFURLPOSIXPathStyle, _false ) open "i", 2, url fileLen = lof(2, 1) h = fn NewHandleClear( fileLen ) if ( h ) read file 2, [h], fileLen cfStr = fn CFStringCreateWithBytes( _kCFAllocatorDefault, #[h], fn GetHandleSize(h), _kCFStringEncodingMacRoman, _false ) if ( cfStr ) arr = fn CFStringCreateArrayBySeparatingStrings( _kCFAllocatorDefault, cfStr, @"\n" ) CFRelease( cfStr ) elements = fn CFArrayGetCount( arr ) for i = 0 to elements - 1 temp = fn CFArrayGetValueAtIndex( arr, i ) fn CFStringGetPascalString( temp, @s, 256, _kCFStringEncodingMacRoman ) gDictionary(i) = s next CFRelease( arr ) end if fn DisposeH( h ) end if close #2 CFRelease( url ) end fn   local fn FindAnagrams( whichWord as Str31 ) dim as long elements, i   print "Anagrams for "; UCase$(whichWord); ":", elements = fn DynamicNextElement( dynamic( gDictionary ) ) for i = 0 to elements - 1 if ( len( gDictionary(i) ) == whichWord[0] ) if ( fn IsAnagram( whichWord, gDictionary(i) ) == _true ) print gDictionary(i), end if end if next print end fn   fn LoadDictionaryToArray   fn FindAnagrams( "bade" ) fn FindAnagrams( "abet" ) fn FindAnagrams( "beast" ) fn FindAnagrams( "tuba" ) fn FindAnagrams( "mace" ) fn FindAnagrams( "scare" ) fn FindAnagrams( "marine" ) fn FindAnagrams( "antler" ) fn FindAnagrams( "spare" ) fn FindAnagrams( "leading" ) fn FindAnagrams( "alerted" ) fn FindAnagrams( "allergy" ) fn FindAnagrams( "research") fn FindAnagrams( "hustle" ) fn FindAnagrams( "oriental") def tab 3 print fn FindAnagrams( "creationism" ) fn FindAnagrams( "resistance" ) fn FindAnagrams( "mountaineer" )  
http://rosettacode.org/wiki/Angle_difference_between_two_bearings
Angle difference between two bearings
Finding the angle between two bearings is often confusing.[1] Task Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings. Input bearings are expressed in the range   -180   to   +180   degrees. The  result  is also expressed in the range   -180   to   +180   degrees. Compute the angle for the following pairs: 20 degrees (b1) and 45 degrees (b2) -45 and 45 -85 and 90 -95 and 90 -45 and 125 -45 and 145 29.4803 and -88.6381 -78.3251 and -159.036 Optional extra Allow the input bearings to be any (finite) value. Test cases -70099.74233810938 and 29840.67437876723 -165313.6666297357 and 33693.9894517456 1174.8380510598456 and -154146.66490124757 60175.77306795546 and 42213.07192354373
#zkl
zkl
fcn bearingAngleDiff(b1,b2){ // -->Float, b1,b2 can be int or float ( (b:=(0.0 + b2 - b1 + 720)%360) > 180 ) and b - 360 or b; }
http://rosettacode.org/wiki/Anagrams/Deranged_anagrams
Anagrams/Deranged anagrams
Two or more words are said to be anagrams if they have the same characters, but in a different order. By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words. Task[edit] Use the word list at unixdict to find and display the longest deranged anagram. Related tasks Permutations/Derangements Best shuffle Word plays Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#zkl
zkl
words:=Dictionary(25000); //-->Dictionary(sorted word:all anagrams, ...) File("unixdict.txt").read().pump(Void,'wrap(w){ w=w.strip(); key:=w.sort(); words[key]=words.find(key,T).append(w); });   nws:=words.values.pump(List,fcn(ws){ //-->( (len,words), ...) if(ws.len()>1){ // two or more anagrams r:=List(); n:=ws[0].len(); // length of these anagrams foreach idx,w in (ws.enumerate()){ foreach w2 in (ws[idx+1,*]){ if(Utils.zipWith('!=,w,w2).filter().len()==n) r.write(T(w,w2)); } } if(r) return(r.insert(0,n)); } Void.Skip });   nws.filter(fcn(nws,max){ nws[0]==max }, nws.reduce(fcn(p,nws){ p.max(nws[0]) },0) ) .println();
http://rosettacode.org/wiki/Anonymous_recursion
Anonymous recursion
While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects,   and/or the function doesn't have the right arguments and/or return values. So we end up inventing some silly name like   foo2   or   foo_helper.   I have always found it painful to come up with a proper name, and see some disadvantages:   You have to think up a name, which then pollutes the namespace   Function is created which is called from nowhere else   The program flow in the source code is interrupted Some languages allow you to embed recursion directly in-place.   This might work via a label, a local gosub instruction, or some special keyword. Anonymous recursion can also be accomplished using the   Y combinator. Task If possible, demonstrate this by writing the recursive version of the fibonacci function   (see Fibonacci sequence)   which checks for a negative argument before doing the actual recursion.
#REXX
REXX
/*REXX program to show anonymous recursion (of a function or subroutine). */ numeric digits 1e6 /*in case the user goes ka-razy with X.*/ parse arg x . /*obtain the optional argument from CL.*/ if x=='' | x=="," then x= 12 /*Not specified? Then use the default.*/ w= length(x) /*W: used for formatting the output. */ do j=0 for x+1 /*use the argument as an upper limit.*/ say 'fibonacci('right(j, w)") =" fib(j) end /*j*/ /* [↑] show Fibonacci sequence: 0 ──► X*/ exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ fib: procedure; parse arg z; if z>=0 then return .(z) say "***error*** argument can't be negative."; exit .: procedure; parse arg #; if #<2 then return #; return .(#-1) + .(#-2)
http://rosettacode.org/wiki/Amicable_pairs
Amicable pairs
Two integers N {\displaystyle N} and M {\displaystyle M} are said to be amicable pairs if N ≠ M {\displaystyle N\neq M} and the sum of the proper divisors of N {\displaystyle N} ( s u m ( p r o p D i v s ( N ) ) {\displaystyle \mathrm {sum} (\mathrm {propDivs} (N))} ) = M {\displaystyle =M} as well as s u m ( p r o p D i v s ( M ) ) = N {\displaystyle \mathrm {sum} (\mathrm {propDivs} (M))=N} . Example 1184 and 1210 are an amicable pair, with proper divisors:   1, 2, 4, 8, 16, 32, 37, 74, 148, 296, 592   and   1, 2, 5, 10, 11, 22, 55, 110, 121, 242, 605   respectively. Task Calculate and show here the Amicable pairs below 20,000; (there are eight). Related tasks Proper divisors Abundant, deficient and perfect number classifications Aliquot sequence classifications and its amicable classification.
#Quackery
Quackery
[ properdivisors dup size 0 = iff [ drop 0 ] done behead swap witheach + ] is spd ( n --> n )   [ dup dup spd dup spd rot = unrot > and ] is largeamicable ( n --> b )   [ [] swap times [ i^ largeamicable if [ i^ dup spd swap join nested join ] ] ] is amicables ( n --> [ )   20000 amicables witheach [ witheach [ echo sp ] cr ]
http://rosettacode.org/wiki/Animate_a_pendulum
Animate a pendulum
One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display. The classic such physical system is a simple gravity pendulum. Task Create a simple physical model of a pendulum and animate it.
#Wren
Wren
import "graphics" for Canvas, Color import "dome" for Window import "math" for Math import "./dynamic" for Tuple   var Element = Tuple.create("Element", ["x", "y"]) var Dt = 0.1 var Angle = Num.pi / 2 var AngleVelocity = 0   class Pendulum { construct new(length) { Window.title = "Pendulum" _w = 2 * length + 50 _h = length / 2 * 3 Window.resize(_w, _h) Canvas.resize(_w, _h) _length = length _anchor = Element.new((_w/2).floor, (_h/4).floor) _fore = Color.black }   init() { drawPendulum() }   drawPendulum() { Canvas.cls(Color.white) var ball = Element.new((_anchor.x + Math.sin(Angle) * _length).truncate, (_anchor.y + Math.cos(Angle) * _length).truncate) Canvas.line(_anchor.x, _anchor.y, ball.x, ball.y, _fore, 2) Canvas.circlefill(_anchor.x - 3, _anchor.y - 4, 7, Color.lightgray) Canvas.circle(_anchor.x - 3, _anchor.y - 4, 7, _fore) Canvas.circlefill(ball.x - 7, ball.y - 7, 14, Color.yellow) Canvas.circle(ball.x - 7, ball.y - 7, 14, _fore) }   update() { AngleVelocity = AngleVelocity - 9.81 / _length * Math.sin(Angle) * Dt Angle = Angle + AngleVelocity * Dt }   draw(alpha) { drawPendulum() } }   var Game = Pendulum.new(200)
http://rosettacode.org/wiki/Amb
Amb
Define and give an example of the Amb operator. The Amb operator (short for "ambiguous") expresses nondeterminism. This doesn't refer to randomness (as in "nondeterministic universe") but is closely related to the term as it is used in automata theory ("non-deterministic finite automaton"). The Amb operator takes a variable number of expressions (or values if that's simpler in the language) and yields a correct one which will satisfy a constraint in some future computation, thereby avoiding failure. Problems whose solution the Amb operator naturally expresses can be approached with other tools, such as explicit nested iterations over data sets, or with pattern matching. By contrast, the Amb operator appears integrated into the language. Invocations of Amb are not wrapped in any visible loops or other search patterns; they appear to be independent. Essentially Amb(x, y, z) splits the computation into three possible futures: a future in which the value x is yielded, a future in which the value y is yielded and a future in which the value z is yielded. The future which leads to a successful subsequent computation is chosen. The other "parallel universes" somehow go away. Amb called with no arguments fails. For simplicity, one of the domain values usable with Amb may denote failure, if that is convenient. For instance, it is convenient if a Boolean false denotes failure, so that Amb(false) fails, and thus constraints can be expressed using Boolean expressions like Amb(x * y == 8) which unless x and y add to four. A pseudo-code program which satisfies this constraint might look like: let x = Amb(1, 2, 3) let y = Amb(7, 6, 4, 5) Amb(x * y = 8) print x, y The output is 2 4 because Amb(1, 2, 3) correctly chooses the future in which x has value 2, Amb(7, 6, 4, 5) chooses 4 and consequently Amb(x * y = 8) produces a success. Alternatively, failure could be represented using strictly Amb(): unless x * y = 8 do Amb() Or else Amb could take the form of two operators or functions: one for producing values and one for enforcing constraints: let x = Ambsel(1, 2, 3) let y = Ambsel(4, 5, 6) Ambassert(x * y = 8) print x, y where Ambassert behaves like Amb() if the Boolean expression is false, otherwise it allows the future computation to take place, without yielding any value. The task is to somehow implement Amb, and demonstrate it with a program which chooses one word from each of the following four sets of character strings to generate a four-word sentence: "the" "that" "a" "frog" "elephant" "thing" "walked" "treaded" "grows" "slowly" "quickly" The constraint to be satisfied is that the last character of each word (other than the last) is the same as the first character of its successor. The only successful sentence is "that thing grows slowly"; other combinations do not satisfy the constraint and thus fail. The goal of this task isn't to simply process the four lists of words with explicit, deterministic program flow such as nested iteration, to trivially demonstrate the correct output. The goal is to implement the Amb operator, or a facsimile thereof that is possible within the language limitations.
#PARI.2FGP
PARI/GP
Amb(V)={ amb(vector(#V,i,vector(#V[i],j,Vec(V[i][j]))),[]) }; amb(V,s)={ if (#V == 0, return(concat(s))); my(v=V[1],U=vecextract(V,2^#V-2),t,final=if(#s,s[#s])); if(#s, s = concat(s,[" "])); for(i=1,#v, if ((#s == 0 || final == v[i][1]), t = amb(U, concat(s, v[i])); if (t, return(t)) ) ); 0 }; Amb([["the","that","a"],["frog","elephant","thing"],["walked","treaded","grows"],["slowly","quickly"]])
http://rosettacode.org/wiki/Accumulator_factory
Accumulator factory
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created). Rules The detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in small italic text). Before you submit an example, make sure the function Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i). Although these exact function and parameter names need not be used Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) (i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that) Generates functions that return the sum of every number ever passed to them, not just the most recent. (This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.) Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. (Follow your language's conventions here.) Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. (No global variables or other such things.) E.g. if after the example, you added the following code (in a made-up language) where the factory function is called foo: x = foo(1); x(5); foo(3); print x(2.3); It should print 8.3. (There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.) Task Create a function that implements the described rules. It need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them. Where it is not possible to hold exactly to the constraints above, describe the deviations.
#Haskell
Haskell
import Control.Monad.ST import Data.STRef   accumulator :: (Num a) => a -> ST s (a -> ST s a) accumulator sum0 = do sum <- newSTRef sum0 return $ \n -> do modifySTRef sum (+ n) readSTRef sum   main :: IO () main = print foo where foo = runST $ do x <- accumulator 1 x 5 accumulator 3 x 2.3
http://rosettacode.org/wiki/Accumulator_factory
Accumulator factory
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created). Rules The detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in small italic text). Before you submit an example, make sure the function Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i). Although these exact function and parameter names need not be used Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) (i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that) Generates functions that return the sum of every number ever passed to them, not just the most recent. (This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.) Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. (Follow your language's conventions here.) Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. (No global variables or other such things.) E.g. if after the example, you added the following code (in a made-up language) where the factory function is called foo: x = foo(1); x(5); foo(3); print x(2.3); It should print 8.3. (There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.) Task Create a function that implements the described rules. It need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them. Where it is not possible to hold exactly to the constraints above, describe the deviations.
#Icon_and_Unicon
Icon and Unicon
procedure main() a := genAcc(3) b := genAcc(5)   write(" " ,center("a",5), " ", center("b", 5)) write("genAcc: ", right(a(4),5), " ", right(b(4), 5)) write("genAcc: ", right(a(2),5), " ", right(b(3),5)) write("genAcc: ", right(a(4.5),5)," ", right(b(1.3),5)) end   procedure genAcc(n) # The generator factory return makeProc { while i := (n@&source)[1] do n +:= i } end   procedure makeProc(A) # A Programmer-Defined Control Operation return (@A[1],A[1]) end
http://rosettacode.org/wiki/Ackermann_function
Ackermann function
The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { n + 1 if  m = 0 A ( m − 1 , 1 ) if  m > 0  and  n = 0 A ( m − 1 , A ( m , n − 1 ) ) if  m > 0  and  n > 0. {\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}} Its arguments are never negative and it always terminates. Task Write a function which returns the value of A ( m , n ) {\displaystyle A(m,n)} . Arbitrary precision is preferred (since the function grows so quickly), but not required. See also Conway chained arrow notation for the Ackermann function.
#Argile
Argile
use std   for each (val nat n) from 0 to 6 for each (val nat m) from 0 to 3 print "A("m","n") = "(A m n)   .:A <nat m, nat n>:. -> nat return (n+1) if m == 0 return (A (m - 1) 1) if n == 0 A (m - 1) (A m (n - 1))
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications
Abundant, deficient and perfect number classifications
These define three classifications of positive integers based on their   proper divisors. Let   P(n)   be the sum of the proper divisors of   n   where the proper divisors are all positive divisors of   n   other than   n   itself. if P(n) < n then n is classed as deficient (OEIS A005100). if P(n) == n then n is classed as perfect (OEIS A000396). if P(n) > n then n is classed as abundant (OEIS A005101). Example 6   has proper divisors of   1,   2,   and   3. 1 + 2 + 3 = 6,   so   6   is classed as a perfect number. Task Calculate how many of the integers   1   to   20,000   (inclusive) are in each of the three classes. Show the results here. Related tasks   Aliquot sequence classifications.   (The whole series from which this task is a subset.)   Proper divisors   Amicable pairs
#C.2B.2B
C++
#include <iostream> #include <algorithm> #include <vector>   std::vector<int> findProperDivisors ( int n ) { std::vector<int> divisors ; for ( int i = 1 ; i < n / 2 + 1 ; i++ ) { if ( n % i == 0 ) divisors.push_back( i ) ; } return divisors ; }   int main( ) { std::vector<int> deficients , perfects , abundants , divisors ; for ( int n = 1 ; n < 20001 ; n++ ) { divisors = findProperDivisors( n ) ; int sum = std::accumulate( divisors.begin( ) , divisors.end( ) , 0 ) ; if ( sum < n ) { deficients.push_back( n ) ; } if ( sum == n ) { perfects.push_back( n ) ; } if ( sum > n ) { abundants.push_back( n ) ; } } std::cout << "Deficient : " << deficients.size( ) << std::endl ; std::cout << "Perfect  : " << perfects.size( ) << std::endl ; std::cout << "Abundant  : " << abundants.size( ) << std::endl ; return 0 ; }
http://rosettacode.org/wiki/Align_columns
Align columns
Given a text file of many lines, where fields within a line are delineated by a single 'dollar' character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be either left justified, right justified, or center justified within its column. Use the following text to test your programs: Given$a$text$file$of$many$lines,$where$fields$within$a$line$ are$delineated$by$a$single$'dollar'$character,$write$a$program that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$ column$are$separated$by$at$least$one$space. Further,$allow$for$each$word$in$a$column$to$be$either$left$ justified,$right$justified,$or$center$justified$within$its$column. Note that:   The example input texts lines may, or may not, have trailing dollar characters.   All columns should share the same alignment.   Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.   Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.   The minimum space between columns should be computed from the text and not hard-coded.   It is not a requirement to add separating characters between or around columns. 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
#CoffeeScript
CoffeeScript
  pad = (n) -> s = '' while n > 0 s += ' ' n -= 1 s   align = (input, alignment = 'center') -> tokenized_lines = (line.split '$' for line in input) col_widths = {} for line in tokenized_lines for token, i in line if !col_widths[i]? or token.length > col_widths[i] col_widths[i] = token.length padders = center: (s, width) -> excess = width - s.length left = Math.floor excess / 2 right = excess - left pad(left) + s + pad(right)   right: (s, width) -> excess = width - s.length pad(excess) + s   left: (s, width) -> excess = width - s.length s + pad(excess)   padder = padders[alignment]   for line in tokenized_lines padded_tokens = (padder(token, col_widths[i]) for token, i in line) console.log padded_tokens.join ' '     input = [ "Given$a$text$file$of$many$lines,$where$fields$within$a$line$" "are$delineated$by$a$single$'dollar'$character,$write$a$program" "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$" "column$are$separated$by$at$least$one$space." "Further,$allow$for$each$word$in$a$column$to$be$either$left$" "justified,$right$justified,$or$center$justified$within$its$column." ]   for alignment in ['center', 'right', 'left'] console.log "\n----- #{alignment}" align input, alignment  
http://rosettacode.org/wiki/Active_object
Active object
In object-oriented programming an object is active when its state depends on clock. Usually an active object encapsulates a task that updates the object's state. To the outer world the object looks like a normal object with methods that can be called from outside. Implementation of such methods must have a certain synchronization mechanism with the encapsulated task in order to prevent object's state corruption. A typical instance of an active object is an animation widget. The widget state changes with the time, while as an object it has all properties of a normal widget. The task Implement an active integrator object. The object has an input and output. The input can be set using the method Input. The input is a function of time. The output can be queried using the method Output. The object integrates its input over the time and the result becomes the object's output. So if the input is K(t) and the output is S, the object state S is changed to S + (K(t1) + K(t0)) * (t1 - t0) / 2, i.e. it integrates K using the trapeze method. Initially K is constant 0 and S is 0. In order to test the object: set its input to sin (2π f t), where the frequency f=0.5Hz. The phase is irrelevant. wait 2s set the input to constant 0 wait 0.5s Verify that now the object's output is approximately 0 (the sine has the period of 2s). The accuracy of the result will depend on the OS scheduler time slicing and the accuracy of the clock.
#PicoLisp
PicoLisp
(load "@lib/math.l")   (class +Active) # inp val sum usec   (dm T () (unless (assoc -100 *Run) # Install timer task (task -100 100 # Update objects every 0.1 sec (mapc 'update> *Actives) ) ) (=: inp '((U) 0)) # Set zero input function (=: val 0) # Initialize last value (=: sum 0) # Initialize sum (=: usec (usec)) # and time (push '*Actives This) ) # Install in notification list   (dm input> (Fun) (=: inp Fun) )   (dm update> () (let (U (usec) V ((: inp) U)) # Get current time, calculate value (inc (:: sum) (*/ (+ V (: val)) # (K(t[1]) + K(t[0])) * (- U (: usec)) # (t[1] - t[0]) / 2.0 ) ) # 2.0 (=: val V) (=: usec U) ) )   (dm output> () (format (: sum) *Scl) ) # Get result   (dm stop> () (unless (del This '*Actives) # Removing the last active object? (task -100) ) ) # Yes: Uninstall timer task   (de integrate () # Test it (let Obj (new '(+Active)) # Create an active object (input> Obj # Set input function '((U) (sin (*/ pi U 1.0))) ) # to sin(π * t) (wait 2000) # Wait 2 sec (input> Obj '((U) 0)) # Reset input function (wait 500) # Wait 0.5 sec (prinl "Output: " (output> Obj)) # Print return value (stop> Obj) ) ) # Stop active object
http://rosettacode.org/wiki/Active_object
Active object
In object-oriented programming an object is active when its state depends on clock. Usually an active object encapsulates a task that updates the object's state. To the outer world the object looks like a normal object with methods that can be called from outside. Implementation of such methods must have a certain synchronization mechanism with the encapsulated task in order to prevent object's state corruption. A typical instance of an active object is an animation widget. The widget state changes with the time, while as an object it has all properties of a normal widget. The task Implement an active integrator object. The object has an input and output. The input can be set using the method Input. The input is a function of time. The output can be queried using the method Output. The object integrates its input over the time and the result becomes the object's output. So if the input is K(t) and the output is S, the object state S is changed to S + (K(t1) + K(t0)) * (t1 - t0) / 2, i.e. it integrates K using the trapeze method. Initially K is constant 0 and S is 0. In order to test the object: set its input to sin (2π f t), where the frequency f=0.5Hz. The phase is irrelevant. wait 2s set the input to constant 0 wait 0.5s Verify that now the object's output is approximately 0 (the sine has the period of 2s). The accuracy of the result will depend on the OS scheduler time slicing and the accuracy of the clock.
#PureBasic
PureBasic
Prototype.d ValueFunction(f.d, t.d)   Class IntegralClass Time0.i Mutex.i S.d Freq.d Thread.i Quit.i *func.ValueFunction   Protect Method Sampler() Repeat Delay(1) If This\func And This\Mutex LockMutex(This\Mutex) This\S + This\func(This\Freq, ElapsedMilliseconds()-This\Time0) UnlockMutex(This\Mutex) EndIf Until This\Quit EndMethod   BeginPublic Method Input(*func.ValueFunction) LockMutex(This\Mutex) This\func = *func UnlockMutex(This\Mutex) EndMethod   Method.d Output() Protected Result.d LockMutex(This\Mutex) Result = This\S UnlockMutex(This\Mutex) MethodReturn Result EndMethod   Method Init(F.d, *f) This\Freq = F This\func = *f This\Mutex = CreateMutex() This\Time0 = ElapsedMilliseconds() This\Thread = CreateThread(This\Sampler, This) ThreadPriority(This\Thread, 10) EndMethod   Method Release() This\Quit = #True WaitThread(This\Thread) EndMethod EndPublic   EndClass   ;- Procedures for generating values Procedure.d n(f.d, t.d) ; Returns nothing EndProcedure   Procedure.d f(f.d, t.d) ; Returns the function of this task ProcedureReturn Sin(2*#PI*f*t) EndProcedure   ;- Test Code *a.IntegralClass = NewObject.IntegralClass(0.5, @n()) ; Create the AO *a\Input(@f()) ; Start sampling function f() Delay(2000) ; Delay 2 sec *a\Input(@n()) ; Change to sampling 'nothing' Delay( 500) ; Wait 1/2 sec MessageRequester("Info", StrD(*a\Output())) ; Present the result *a= FreeObject
http://rosettacode.org/wiki/Aliquot_sequence_classifications
Aliquot sequence classifications
An aliquot sequence of a positive integer K is defined recursively as the first member being K and subsequent members being the sum of the Proper divisors of the previous term. If the terms eventually reach 0 then the series for K is said to terminate. There are several classifications for non termination: If the second term is K then all future terms are also K and so the sequence repeats from the first term with period 1 and K is called perfect. If the third term would be repeating K then the sequence repeats with period 2 and K is called amicable. If the Nth term would be repeating K for the first time, with N > 3 then the sequence repeats with period N - 1 and K is called sociable. Perfect, amicable and sociable numbers eventually repeat the original number K; there are other repetitions... Some K have a sequence that eventually forms a periodic repetition of period 1 but of a number other than K, for example 95 which forms the sequence 95, 25, 6, 6, 6, ... such K are called aspiring. K that have a sequence that eventually forms a periodic repetition of period >= 2 but of a number other than K, for example 562 which forms the sequence 562, 284, 220, 284, 220, ... such K are called cyclic. And finally: Some K form aliquot sequences that are not known to be either terminating or periodic; these K are to be called non-terminating. For the purposes of this task, K is to be classed as non-terminating if it has not been otherwise classed after generating 16 terms or if any term of the sequence is greater than 2**47 = 140,737,488,355,328. Task Create routine(s) to generate the aliquot sequence of a positive integer enough to classify it according to the classifications given above. Use it to display the classification and sequences of the numbers one to ten inclusive. Use it to show the classification and sequences of the following integers, in order: 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, and optionally 15355717786080. Show all output on this page. Related tasks   Abundant, deficient and perfect number classifications. (Classifications from only the first two members of the whole sequence).   Proper divisors   Amicable pairs
#Racket
Racket
#lang racket (require "proper-divisors.rkt" math/number-theory)   (define SCOPE 20000)   (define P (let ((P-v (vector))) (λ (n) (cond [(> n SCOPE) (apply + (drop-right (divisors n) 1))] [else (set! P-v (fold-divisors P-v n 0 +)) (vector-ref P-v n)]))))   ;; initialise P-v (void (P SCOPE))   (define (aliquot-sequence-class K)  ;; note that seq is reversed as a list, since we're consing (define (inr-asc seq) (match seq [(list 0 _ ...) (values "terminating" seq)] [(list (== K) (== K) _ ...) (values "perfect" seq)] [(list n n _ ...) (values (format "aspiring to ~a" n) seq)] [(list (== K) ami (== K) _ ...) (values (format "amicable with ~a" ami) seq)] [(list (== K) cycle ... (== K)) (values (format "sociable length ~a" (add1 (length cycle))) seq)] [(list n cycle ... n _ ...) (values (format "cyclic on ~a length ~a" n (add1 (length cycle))) seq)] [(list X _ ...) #:when (> X 140737488355328) (values "non-terminating big number" seq)] [(list seq ...) #:when (> (length seq) 16) (values "non-terminating long sequence" seq)] [(list seq1 seq ...) (inr-asc (list* (P seq1) seq1 seq))])) (inr-asc (list K)))   (define (report-aliquot-sequence-class n) (define-values (c s) (aliquot-sequence-class n)) (printf "~a:\t~a\t~a~%" n c (reverse s)))   (for ((i (in-range 1 10))) (report-aliquot-sequence-class i)) (newline)   (for ((i (in-list '(11 12 28 496 220 1184 12496 1264460 790 909 562 1064 1488 15355717786080)))) (report-aliquot-sequence-class i))
http://rosettacode.org/wiki/AKS_test_for_primes
AKS test for primes
The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles. The theorem on which the test is based can be stated as follows:   a number   p {\displaystyle p}   is prime   if and only if   all the coefficients of the polynomial expansion of ( x − 1 ) p − ( x p − 1 ) {\displaystyle (x-1)^{p}-(x^{p}-1)} are divisible by   p {\displaystyle p} . Example Using   p = 3 {\displaystyle p=3} : (x-1)^3 - (x^3 - 1) = (x^3 - 3x^2 + 3x - 1) - (x^3 - 1) = -3x^2 + 3x And all the coefficients are divisible by 3,   so 3 is prime. Note: This task is not the AKS primality test.   It is an inefficient exponential time algorithm discovered in the late 1600s and used as an introductory lemma in the AKS derivation. Task Create a function/subroutine/method that given   p {\displaystyle p}   generates the coefficients of the expanded polynomial representation of   ( x − 1 ) p {\displaystyle (x-1)^{p}} . Use the function to show here the polynomial expansions of   ( x − 1 ) p {\displaystyle (x-1)^{p}}   for   p {\displaystyle p}   in the range   0   to at least   7,   inclusive. Use the previous function in creating another function that when given   p {\displaystyle p}   returns whether   p {\displaystyle p}   is prime using the theorem. Use your test to generate a list of all primes under   35. As a stretch goal,   generate all primes under   50   (needs integers larger than 31-bit). References Agrawal-Kayal-Saxena (AKS) primality test (Wikipedia) Fool-Proof Test for Primes - Numberphile (Video). The accuracy of this video is disputed -- at best it is an oversimplification.
#Lambdatalk
Lambdatalk
  {require lib_BN} // for big numbers   1) pascalian binomial coefficient C(n,p) = n!/(p!(n-p)!) = (n*(n-1)...(n-p+1))/(p*(p-1)...2*1)   {def coeff {lambda {:n :p} {BN.intPart {BN./ {S.reduce BN.* {S.serie :n {- :n :p -1} -1}} {S.reduce BN.* {S.serie :p 1 -1}}}}}} -> coeff   2) polynomial expansions of (x − 1)^p   {def sign {lambda {:n} {if {= {% :n 2} 0} then + else -}}} -> sign   {def coeffs {lambda {:n} {br}(x - 1)^:n = {if {= :n 0} then + 1x^0 else {if {= :n 1} then + 1x^1 - 1x^0 else {sign 0} 1x^:n {S.map {{lambda {:p :n} {sign {- :p :n}} {coeff :p :n}x^{- :p :n}} :n} {S.serie 1 {- :n 1}}} {sign :n} 1x^0}}}} -> coeffs   {S.map coeffs {S.serie 0 7}} -> (x - 1)^0 = + 1x^0 (x - 1)^1 = + 1x^1 - 1x^0 (x - 1)^2 = + 1x^2 - 2x^1 + 1x^0 (x - 1)^3 = + 1x^3 + 3x^2 - 3x^1 - 1x^0 (x - 1)^4 = + 1x^4 - 4x^3 + 6x^2 - 4x^1 + 1x^0 (x - 1)^5 = + 1x^5 + 5x^4 - 10x^3 + 10x^2 - 5x^1 - 1x^0 (x - 1)^6 = + 1x^6 - 6x^5 + 15x^4 - 20x^3 + 15x^2 - 6x^1 + 1x^0 (x - 1)^7 = + 1x^7 + 7x^6 - 21x^5 + 35x^4 - 35x^3 + 21x^2 - 7x^1 - 1x^0   3) primality test   Taking into account the symmetry of the list of coefficients and the uselessness of the sign in the calculation of the divisibility, one can limit the tests to half of the list, and define a simplified function, aks_coeffs:   {def aks_coeffs {lambda {:n} {S.map {coeff :n} {S.serie 1 {+ {/ {- :n 1} 2} 1}}}}} -> aks_coeffs   {def divide {lambda {:a :b} {= {BN.compare {BN.% :b :a} 0} 0}}} -> divide   {def isprime {lambda {:n} {if {and {S.map {divide :n} {aks_coeffs :n}}} then :n else .}}} -> isprime   {S.map isprime {S.serie 2 100}} -> 2 3 . 5 . 7 . . . 11 . 13 . . . 17 . 19 . . . 23 . . . . . 29 . 31 . . . . . 37 . . . 41 . 43 . . . 47 . . . . . 53 . . . . . 59 . 61 . . . . . 67 . . . 71 . 73 . . . . . 79 . . . 83 . . . . . 89 . . . . . . . 97 . . .  
http://rosettacode.org/wiki/Additive_primes
Additive primes
Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS entry:   A046704 additive primes.   the prime-numbers entry:   additive primes.   the geeks for geeks entry: additive prime number.   the prime-numbers fandom: additive primes.
#Rust
Rust
fn main() { let limit = 500; let column_w = limit.to_string().len() + 1; let mut pms = Vec::with_capacity(limit / 2 - limit / 3 / 2 - limit / 5 / 3 / 2 + 1); let mut count = 0; for u in (2..3).chain((3..limit).step_by(2)) { if pms.iter().take_while(|&&p| p * p <= u).all(|&p| u % p != 0) { pms.push(u); let dgs = std::iter::successors(Some(u), |&n| (n > 9).then(|| n / 10)).map(|n| n % 10); if pms.binary_search(&dgs.sum()).is_ok() { print!("{}{u:column_w$}", if count % 10 == 0 { "\n" } else { "" }); count += 1; } } } println!("\n---\nFound {count} additive primes less than {limit}"); }
http://rosettacode.org/wiki/Almost_prime
Almost prime
A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,   where   k = 2 {\displaystyle k=2} ,   are the   semiprimes. Task Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for   1 <= K <= 5 {\displaystyle 1<=K<=5} . Related tasks   Semiprime   Category:Prime Numbers
#Prolog
Prolog
% almostPrime(K, +Take, List) succeeds if List can be unified with the % first Take K-almost-primes. % Notice that K need not be specified. % To avoid having to cache or recompute the first Take primes, we define % almostPrime/3 in terms of almostPrime/4 as follows: % almostPrime(K, Take, List) :- % Compute the list of the first Take primes: nPrimes(Take, Primes), almostPrime(K, Take, Primes, List).   almostPrime(1, Take, Primes, Primes).   almostPrime(K, Take, Primes, List) :- generate(2, K), % generate K >= 2 K1 is K - 1, almostPrime(K1, Take, Primes, L), multiplylist( Primes, L, Long), sort(Long, Sorted), % uniquifies take(Take, Sorted, List).  
http://rosettacode.org/wiki/Anagrams
Anagrams
When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in them. Related tasks Word plays Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams 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
#GAP
GAP
Anagrams := function(name) local f, p, L, line, word, words, swords, res, cur, r; words := [ ]; swords := [ ]; f := InputTextFile(name); while true do line := ReadLine(f); if line = fail then break; else word := Chomp(line); Add(words, word); Add(swords, SortedList(word)); fi; od; CloseStream(f); p := SortingPerm(swords); L := Permuted(words, p); r := ""; cur := [ ]; res := [ ]; for word in L do if SortedList(word) = r then Add(cur, word); else if Length(cur) > 0 then Add(res, cur); fi; r := SortedList(word); cur := [ word ]; fi; od; if Length(cur) > 0 then Add(res, cur); fi; return Filtered(res, v -> Length(v) > 1); end;     ana := Anagrams("my/gap/unixdict.txt");;   # What is the longest anagram sequence ? Maximum(List(ana, Length)); # 5   # Which are they ? Filtered(ana, v -> Length(v) = 5); # [ [ "abel", "able", "bale", "bela", "elba" ], # [ "caret", "carte", "cater", "crate", "trace" ], # [ "angel", "angle", "galen", "glean", "lange" ], # [ "alger", "glare", "lager", "large", "regal" ], # [ "elan", "lane", "lean", "lena", "neal" ], # [ "evil", "levi", "live", "veil", "vile" ] ]
http://rosettacode.org/wiki/Anonymous_recursion
Anonymous recursion
While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects,   and/or the function doesn't have the right arguments and/or return values. So we end up inventing some silly name like   foo2   or   foo_helper.   I have always found it painful to come up with a proper name, and see some disadvantages:   You have to think up a name, which then pollutes the namespace   Function is created which is called from nowhere else   The program flow in the source code is interrupted Some languages allow you to embed recursion directly in-place.   This might work via a label, a local gosub instruction, or some special keyword. Anonymous recursion can also be accomplished using the   Y combinator. Task If possible, demonstrate this by writing the recursive version of the fibonacci function   (see Fibonacci sequence)   which checks for a negative argument before doing the actual recursion.
#Ring
Ring
  # Project : Anonymous recursion   t=0 for x = -2 to 12 n = x recursion() if x > -1 see t + nl ok next   func recursion() nold1=1 nold2=0 if n < 0 see "positive argument required!" + nl return ok if n=0 t=nold2 return t ok if n=1 t=nold1 return t ok while n t=nold2+nold1 if n>2 n=n-1 nold2=nold1 nold1=t loop ok return t end return t  
http://rosettacode.org/wiki/Amicable_pairs
Amicable pairs
Two integers N {\displaystyle N} and M {\displaystyle M} are said to be amicable pairs if N ≠ M {\displaystyle N\neq M} and the sum of the proper divisors of N {\displaystyle N} ( s u m ( p r o p D i v s ( N ) ) {\displaystyle \mathrm {sum} (\mathrm {propDivs} (N))} ) = M {\displaystyle =M} as well as s u m ( p r o p D i v s ( M ) ) = N {\displaystyle \mathrm {sum} (\mathrm {propDivs} (M))=N} . Example 1184 and 1210 are an amicable pair, with proper divisors:   1, 2, 4, 8, 16, 32, 37, 74, 148, 296, 592   and   1, 2, 5, 10, 11, 22, 55, 110, 121, 242, 605   respectively. Task Calculate and show here the Amicable pairs below 20,000; (there are eight). Related tasks Proper divisors Abundant, deficient and perfect number classifications Aliquot sequence classifications and its amicable classification.
#R
R
  divisors <- function (n) { Filter( function (m) 0 == n %% m, 1:(n/2) ) }   table = sapply(1:19999, function (n) sum(divisors(n)) )   for (n in 1:19999) { m = table[n] if ((m > n) && (m < 20000) && (n == table[m])) cat(n, " ", m, "\n") }  
http://rosettacode.org/wiki/Animate_a_pendulum
Animate a pendulum
One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display. The classic such physical system is a simple gravity pendulum. Task Create a simple physical model of a pendulum and animate it.
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations   proc Ball(X0, Y0, R, C); \Draw a filled circle int X0, Y0, R, C; \center coordinates, radius, color int X, Y; for Y:= -R to R do for X:= -R to R do if X*X + Y*Y <= R*R then Point(X+X0, Y+Y0, C);     def L = 2.0, \pendulum arm length (meters) G = 9.81, \acceleration due to gravity (meters/second^2) Pi = 3.14, DT = 1.0/72.0; \delta time = screen refresh rate (seconds) def X0=640/2, Y0=480/2; \anchor point = center coordinate real S, V, A, T; \arc length, velocity, acceleration, theta angle int X, Y; \ball coordinates   [SetVid($101); \set 640x480x8 graphic display mode T:= Pi*0.75; V:= 0.0; \starting angle and velocity S:= T*L; repeat A:= -G*Sin(T); V:= V + A*DT; S:= S + V*DT; T:= S/L; X:= X0 + fix(L*100.0*Sin(T)); \100 scales to fit screen Y:= Y0 + fix(L*100.0*Cos(T)); Move(X0, Y0); Line(X, Y, 7); \draw pendulum Ball(X, Y, 10, $E\yellow\); while port($3DA) & $08 do []; \wait for vertical retrace to go away repeat until port($3DA) & $08; \wait for vertical retrace signal Move(X0, Y0); Line(X, Y, 0); \erase pendulum Ball(X, Y, 10, 0\black\); until KeyHit; \keystroke terminates program SetVid(3); \restore normal text screen ]
http://rosettacode.org/wiki/Amb
Amb
Define and give an example of the Amb operator. The Amb operator (short for "ambiguous") expresses nondeterminism. This doesn't refer to randomness (as in "nondeterministic universe") but is closely related to the term as it is used in automata theory ("non-deterministic finite automaton"). The Amb operator takes a variable number of expressions (or values if that's simpler in the language) and yields a correct one which will satisfy a constraint in some future computation, thereby avoiding failure. Problems whose solution the Amb operator naturally expresses can be approached with other tools, such as explicit nested iterations over data sets, or with pattern matching. By contrast, the Amb operator appears integrated into the language. Invocations of Amb are not wrapped in any visible loops or other search patterns; they appear to be independent. Essentially Amb(x, y, z) splits the computation into three possible futures: a future in which the value x is yielded, a future in which the value y is yielded and a future in which the value z is yielded. The future which leads to a successful subsequent computation is chosen. The other "parallel universes" somehow go away. Amb called with no arguments fails. For simplicity, one of the domain values usable with Amb may denote failure, if that is convenient. For instance, it is convenient if a Boolean false denotes failure, so that Amb(false) fails, and thus constraints can be expressed using Boolean expressions like Amb(x * y == 8) which unless x and y add to four. A pseudo-code program which satisfies this constraint might look like: let x = Amb(1, 2, 3) let y = Amb(7, 6, 4, 5) Amb(x * y = 8) print x, y The output is 2 4 because Amb(1, 2, 3) correctly chooses the future in which x has value 2, Amb(7, 6, 4, 5) chooses 4 and consequently Amb(x * y = 8) produces a success. Alternatively, failure could be represented using strictly Amb(): unless x * y = 8 do Amb() Or else Amb could take the form of two operators or functions: one for producing values and one for enforcing constraints: let x = Ambsel(1, 2, 3) let y = Ambsel(4, 5, 6) Ambassert(x * y = 8) print x, y where Ambassert behaves like Amb() if the Boolean expression is false, otherwise it allows the future computation to take place, without yielding any value. The task is to somehow implement Amb, and demonstrate it with a program which chooses one word from each of the following four sets of character strings to generate a four-word sentence: "the" "that" "a" "frog" "elephant" "thing" "walked" "treaded" "grows" "slowly" "quickly" The constraint to be satisfied is that the last character of each word (other than the last) is the same as the first character of its successor. The only successful sentence is "that thing grows slowly"; other combinations do not satisfy the constraint and thus fail. The goal of this task isn't to simply process the four lists of words with explicit, deterministic program flow such as nested iteration, to trivially demonstrate the correct output. The goal is to implement the Amb operator, or a facsimile thereof that is possible within the language limitations.
#Perl
Perl
use strict; use warnings;   use constant EXIT_FAILURE => 1; use constant EXIT_SUCCESS => 0;   sub amb { exit(EXIT_FAILURE) if !@_; for my $word (@_) { my $pid = fork; die $! unless defined $pid; return $word if !$pid; my $wpid = waitpid $pid, 0; die $! unless $wpid == $pid; exit(EXIT_SUCCESS) if $? == EXIT_SUCCESS; } exit(EXIT_FAILURE); }   sub joined { my ($join_a, $join_b) = @_; substr($join_a, -1) eq substr($join_b, 0, 1); }   my $w1 = amb(qw(the that a)); my $w2 = amb(qw(frog elephant thing)); my $w3 = amb(qw(walked treaded grows)); my $w4 = amb(qw(slowly quickly));   amb() unless joined $w1, $w2; amb() unless joined $w2, $w3; amb() unless joined $w3, $w4;   print "$w1 $w2 $w3 $w4\n"; exit(EXIT_SUCCESS);
http://rosettacode.org/wiki/Accumulator_factory
Accumulator factory
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created). Rules The detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in small italic text). Before you submit an example, make sure the function Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i). Although these exact function and parameter names need not be used Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) (i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that) Generates functions that return the sum of every number ever passed to them, not just the most recent. (This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.) Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. (Follow your language's conventions here.) Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. (No global variables or other such things.) E.g. if after the example, you added the following code (in a made-up language) where the factory function is called foo: x = foo(1); x(5); foo(3); print x(2.3); It should print 8.3. (There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.) Task Create a function that implements the described rules. It need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them. Where it is not possible to hold exactly to the constraints above, describe the deviations.
#Io
Io
accumulator := method(sum, block(x, sum = sum + x) setIsActivatable(true) ) x := accumulator(1) x(5) accumulator(3) x(2.3) println // --> 8.3000000000000007
http://rosettacode.org/wiki/Accumulator_factory
Accumulator factory
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created). Rules The detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in small italic text). Before you submit an example, make sure the function Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i). Although these exact function and parameter names need not be used Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) (i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that) Generates functions that return the sum of every number ever passed to them, not just the most recent. (This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.) Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. (Follow your language's conventions here.) Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. (No global variables or other such things.) E.g. if after the example, you added the following code (in a made-up language) where the factory function is called foo: x = foo(1); x(5); foo(3); print x(2.3); It should print 8.3. (There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.) Task Create a function that implements the described rules. It need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them. Where it is not possible to hold exactly to the constraints above, describe the deviations.
#J
J
oleg=:1 :0 a=. cocreate'' n__a=: m a&(4 : 'n__x=: n__x + y') )
http://rosettacode.org/wiki/Ackermann_function
Ackermann function
The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { n + 1 if  m = 0 A ( m − 1 , 1 ) if  m > 0  and  n = 0 A ( m − 1 , A ( m , n − 1 ) ) if  m > 0  and  n > 0. {\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}} Its arguments are never negative and it always terminates. Task Write a function which returns the value of A ( m , n ) {\displaystyle A(m,n)} . Arbitrary precision is preferred (since the function grows so quickly), but not required. See also Conway chained arrow notation for the Ackermann function.
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI or android 32 bits */ /* program ackermann.s */   /* REMARK 1 : this program use routines in a include file see task Include a file language arm assembly for the routine affichageMess conversion10 see at end of this program the instruction include */ /* for constantes see task include a file in arm assembly */ /************************************/ /* Constantes */ /************************************/ .include "../constantes.inc" .equ MMAXI, 4 .equ NMAXI, 10   /*********************************/ /* Initialized data */ /*********************************/ .data sMessResult: .asciz "Result for @ @  : @ \n" szMessError: .asciz "Overflow !!.\n" szCarriageReturn: .asciz "\n"   /*********************************/ /* UnInitialized data */ /*********************************/ .bss sZoneConv: .skip 24 /*********************************/ /* code section */ /*********************************/ .text .global main main: @ entry of program mov r3,#0 mov r4,#0 1: mov r0,r3 mov r1,r4 bl ackermann mov r5,r0 mov r0,r3 ldr r1,iAdrsZoneConv @ else display odd message bl conversion10 @ call decimal conversion ldr r0,iAdrsMessResult ldr r1,iAdrsZoneConv @ insert value conversion in message bl strInsertAtCharInc mov r6,r0 mov r0,r4 ldr r1,iAdrsZoneConv @ else display odd message bl conversion10 @ call decimal conversion mov r0,r6 ldr r1,iAdrsZoneConv @ insert value conversion in message bl strInsertAtCharInc mov r6,r0 mov r0,r5 ldr r1,iAdrsZoneConv @ else display odd message bl conversion10 @ call decimal conversion mov r0,r6 ldr r1,iAdrsZoneConv @ insert value conversion in message bl strInsertAtCharInc bl affichageMess add r4,#1 cmp r4,#NMAXI blt 1b mov r4,#0 add r3,#1 cmp r3,#MMAXI blt 1b 100: @ standard end of the program mov r0, #0 @ return code mov r7, #EXIT @ request to exit program svc #0 @ perform the system call   iAdrszCarriageReturn: .int szCarriageReturn iAdrsMessResult: .int sMessResult iAdrsZoneConv: .int sZoneConv /***************************************************/ /* fonction ackermann */ /***************************************************/ // r0 contains a number m // r1 contains a number n // r0 return résult ackermann: push {r1-r2,lr} @ save registers cmp r0,#0 beq 5f movlt r0,#-1 @ error blt 100f cmp r1,#0 movlt r0,#-1 @ error blt 100f bgt 1f sub r0,r0,#1 mov r1,#1 bl ackermann b 100f 1: mov r2,r0 sub r1,r1,#1 bl ackermann mov r1,r0 sub r0,r2,#1 bl ackermann b 100f 5: adds r0,r1,#1 bcc 100f ldr r0,iAdrszMessError bl affichageMess bkpt 100: pop {r1-r2,lr} @ restaur registers bx lr @ return iAdrszMessError: .int szMessError /***************************************************/ /* ROUTINES INCLUDE */ /***************************************************/ .include "../affichage.inc"  
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications
Abundant, deficient and perfect number classifications
These define three classifications of positive integers based on their   proper divisors. Let   P(n)   be the sum of the proper divisors of   n   where the proper divisors are all positive divisors of   n   other than   n   itself. if P(n) < n then n is classed as deficient (OEIS A005100). if P(n) == n then n is classed as perfect (OEIS A000396). if P(n) > n then n is classed as abundant (OEIS A005101). Example 6   has proper divisors of   1,   2,   and   3. 1 + 2 + 3 = 6,   so   6   is classed as a perfect number. Task Calculate how many of the integers   1   to   20,000   (inclusive) are in each of the three classes. Show the results here. Related tasks   Aliquot sequence classifications.   (The whole series from which this task is a subset.)   Proper divisors   Amicable pairs
#Ceylon
Ceylon
shared void run() {   function divisors(Integer int) => if(int <= 1) then {} else (1..int / 2).filter((Integer element) => element.divides(int));   function classify(Integer int) => sum {0, *divisors(int)} <=> int;   value counts = (1..20k).map(classify).frequencies();   print("deficient: ``counts[smaller] else "none"``"); print("perfect: ``counts[equal] else "none"``"); print("abundant: ``counts[larger] else "none"``"); }
http://rosettacode.org/wiki/Align_columns
Align columns
Given a text file of many lines, where fields within a line are delineated by a single 'dollar' character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be either left justified, right justified, or center justified within its column. Use the following text to test your programs: Given$a$text$file$of$many$lines,$where$fields$within$a$line$ are$delineated$by$a$single$'dollar'$character,$write$a$program that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$ column$are$separated$by$at$least$one$space. Further,$allow$for$each$word$in$a$column$to$be$either$left$ justified,$right$justified,$or$center$justified$within$its$column. Note that:   The example input texts lines may, or may not, have trailing dollar characters.   All columns should share the same alignment.   Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.   Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.   The minimum space between columns should be computed from the text and not hard-coded.   It is not a requirement to add separating characters between or around columns. 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
#Common_Lisp
Common Lisp
(defun nonempty (seq) (position-if (lambda (x) (declare (ignore x)) t) seq))   (defun split (delim seq) "Splits seq on delim into a list of subsequences. Trailing empty subsequences are removed." (labels ((f (seq &aux (pos (position delim seq))) (if pos (cons (subseq seq 0 pos) (f (subseq seq (1+ pos)))) (list seq)))) (let* ((list (f seq)) (end (position-if #'nonempty list :from-end t))) (subseq list 0 (1+ end)))))   (defun lengthen (list minlen filler-elem &aux (len (length list))) "Destructively pads list with filler-elem up to minlen." (if (< len minlen) (nconc list (make-list (- minlen len) :initial-element filler-elem)) list))   (defun align-columns (text &key (align :left) &aux (fmtmod (case align (:left "@") (:right ":") (:center "@:") (t (error "Invalid alignment.")))) (fields (mapcar (lambda (line) (split #\$ line)) (split #\Newline text))) (mostcols (loop for l in fields maximize (length l))) widest) (setf fields (mapcar (lambda (l) (lengthen l mostcols "")) fields)) (setf widest (loop for col below (length (first fields)) collect (loop for row in fields maximize (length (elt row col))))) (format nil (with-output-to-string (s) (princ "~{~{" s) (dolist (w widest) (format s "~~~d~a<~~a~~>" (1+ w) fmtmod)) (princ "~}~%~}" s)) fields))
http://rosettacode.org/wiki/Active_object
Active object
In object-oriented programming an object is active when its state depends on clock. Usually an active object encapsulates a task that updates the object's state. To the outer world the object looks like a normal object with methods that can be called from outside. Implementation of such methods must have a certain synchronization mechanism with the encapsulated task in order to prevent object's state corruption. A typical instance of an active object is an animation widget. The widget state changes with the time, while as an object it has all properties of a normal widget. The task Implement an active integrator object. The object has an input and output. The input can be set using the method Input. The input is a function of time. The output can be queried using the method Output. The object integrates its input over the time and the result becomes the object's output. So if the input is K(t) and the output is S, the object state S is changed to S + (K(t1) + K(t0)) * (t1 - t0) / 2, i.e. it integrates K using the trapeze method. Initially K is constant 0 and S is 0. In order to test the object: set its input to sin (2π f t), where the frequency f=0.5Hz. The phase is irrelevant. wait 2s set the input to constant 0 wait 0.5s Verify that now the object's output is approximately 0 (the sine has the period of 2s). The accuracy of the result will depend on the OS scheduler time slicing and the accuracy of the clock.
#Python
Python
from time import time, sleep from threading import Thread   class Integrator(Thread): 'continuously integrate a function `K`, at each `interval` seconds' def __init__(self, K=lambda t:0, interval=1e-4): Thread.__init__(self) self.interval = interval self.K = K self.S = 0.0 self.__run = True self.start()   def run(self): "entry point for the thread" interval = self.interval start = time() t0, k0 = 0, self.K(0) while self.__run: sleep(interval) t1 = time() - start k1 = self.K(t1) self.S += (k1 + k0)*(t1 - t0)/2.0 t0, k0 = t1, k1   def join(self): self.__run = False Thread.join(self)   if __name__ == "__main__": from math import sin, pi   ai = Integrator(lambda t: sin(pi*t)) sleep(2) print(ai.S) ai.K = lambda t: 0 sleep(0.5) print(ai.S)
http://rosettacode.org/wiki/Aliquot_sequence_classifications
Aliquot sequence classifications
An aliquot sequence of a positive integer K is defined recursively as the first member being K and subsequent members being the sum of the Proper divisors of the previous term. If the terms eventually reach 0 then the series for K is said to terminate. There are several classifications for non termination: If the second term is K then all future terms are also K and so the sequence repeats from the first term with period 1 and K is called perfect. If the third term would be repeating K then the sequence repeats with period 2 and K is called amicable. If the Nth term would be repeating K for the first time, with N > 3 then the sequence repeats with period N - 1 and K is called sociable. Perfect, amicable and sociable numbers eventually repeat the original number K; there are other repetitions... Some K have a sequence that eventually forms a periodic repetition of period 1 but of a number other than K, for example 95 which forms the sequence 95, 25, 6, 6, 6, ... such K are called aspiring. K that have a sequence that eventually forms a periodic repetition of period >= 2 but of a number other than K, for example 562 which forms the sequence 562, 284, 220, 284, 220, ... such K are called cyclic. And finally: Some K form aliquot sequences that are not known to be either terminating or periodic; these K are to be called non-terminating. For the purposes of this task, K is to be classed as non-terminating if it has not been otherwise classed after generating 16 terms or if any term of the sequence is greater than 2**47 = 140,737,488,355,328. Task Create routine(s) to generate the aliquot sequence of a positive integer enough to classify it according to the classifications given above. Use it to display the classification and sequences of the numbers one to ten inclusive. Use it to show the classification and sequences of the following integers, in order: 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, and optionally 15355717786080. Show all output on this page. Related tasks   Abundant, deficient and perfect number classifications. (Classifications from only the first two members of the whole sequence).   Proper divisors   Amicable pairs
#Raku
Raku
sub propdivsum (\x) { my @l = x > 1; (2 .. x.sqrt.floor).map: -> \d { unless x % d { my \y = x div d; y == d ?? @l.push: d !! @l.append: d,y } } sum @l; }   multi quality (0,1) { 'perfect ' } multi quality (0,2) { 'amicable' } multi quality (0,$n) { "sociable-$n" } multi quality ($,1) { 'aspiring' } multi quality ($,$n) { "cyclic-$n" }   sub aliquotidian ($x) { my %seen; my @seq = $x, &propdivsum ... *; for 0..16 -> $to { my $this = @seq[$to] or return "$x\tterminating\t[@seq[^$to]]"; last if $this > 140737488355328; if %seen{$this}:exists { my $from = %seen{$this}; return "$x\t&quality($from, $to-$from)\t[@seq[^$to]]"; } %seen{$this} = $to; } "$x non-terminating\t[{@seq}]"; }   aliquotidian($_).say for flat 1..10, 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, 15355717786080;
http://rosettacode.org/wiki/AKS_test_for_primes
AKS test for primes
The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles. The theorem on which the test is based can be stated as follows:   a number   p {\displaystyle p}   is prime   if and only if   all the coefficients of the polynomial expansion of ( x − 1 ) p − ( x p − 1 ) {\displaystyle (x-1)^{p}-(x^{p}-1)} are divisible by   p {\displaystyle p} . Example Using   p = 3 {\displaystyle p=3} : (x-1)^3 - (x^3 - 1) = (x^3 - 3x^2 + 3x - 1) - (x^3 - 1) = -3x^2 + 3x And all the coefficients are divisible by 3,   so 3 is prime. Note: This task is not the AKS primality test.   It is an inefficient exponential time algorithm discovered in the late 1600s and used as an introductory lemma in the AKS derivation. Task Create a function/subroutine/method that given   p {\displaystyle p}   generates the coefficients of the expanded polynomial representation of   ( x − 1 ) p {\displaystyle (x-1)^{p}} . Use the function to show here the polynomial expansions of   ( x − 1 ) p {\displaystyle (x-1)^{p}}   for   p {\displaystyle p}   in the range   0   to at least   7,   inclusive. Use the previous function in creating another function that when given   p {\displaystyle p}   returns whether   p {\displaystyle p}   is prime using the theorem. Use your test to generate a list of all primes under   35. As a stretch goal,   generate all primes under   50   (needs integers larger than 31-bit). References Agrawal-Kayal-Saxena (AKS) primality test (Wikipedia) Fool-Proof Test for Primes - Numberphile (Video). The accuracy of this video is disputed -- at best it is an oversimplification.
#Liberty_BASIC
Liberty BASIC
  global pasTriMax pasTriMax = 61 dim pasTri(pasTriMax + 1)   for n = 0 to 9 call expandPoly n next n for n = 2 to pasTriMax if isPrime(n) <> 0 then print using("###", n); end if next n print end   sub expandPoly n n = int(n) dim vz$(1) vz$(0) = "+" vz$(1) = "-" if n > pasTriMax then print n; " is out of range" end end if select case n case 0 print "(x-1)^0 = 1" case 1 print "(x-1)^1 = x-1" case else call pascalTriangle n print "(x-1)^"; n; " = "; print "x^"; n; bVz = 1 nDiv2 = int(n / 2) for j = n - 1 to nDiv2 + 1 step -1 print vz$(bVz); pasTri(n - j); "*x^"; j; bVz = abs(1 - bVz) next j for j = nDiv2 to 2 step -1 print vz$(bVz); pasTri(j); "*x^"; j; bVz = abs(1 - bVz) next j print vz$(bVz); pasTri(1); "*x"; bVz = abs(1 - bVz) print vz$(bVz); pasTri(0) end select end sub   function isPrime(n) n = int(n) if n > pasTriMax then print n; " is out of range" end end if call pascalTriangle n res = 1 i = int(n / 2) while res and (i > 1) res = res and (pasTri(i) mod n = 0) i = i - 1 wend isPrime = res end function   sub pascalTriangle n rem Calculate the n'th line 0.. middle n = int(n) pasTri(0) = 1 j = 1 while j <= n j = j + 1 k = int(j / 2) pasTri(k) = pasTri(k - 1) for k = k to 1 step -1 pasTri(k) = pasTri(k) + pasTri(k - 1) next k wend end sub  
http://rosettacode.org/wiki/Additive_primes
Additive primes
Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS entry:   A046704 additive primes.   the prime-numbers entry:   additive primes.   the geeks for geeks entry: additive prime number.   the prime-numbers fandom: additive primes.
#Sage
Sage
  limit = 500 additivePrimes = list(filter(lambda x: x > 0, list(map(lambda x: int(x) if sum([int(digit) for digit in x]) in Primes() else 0, list(map(str,list(primes(1,limit)))))))) print(f"{additivePrimes}\nFound {len(additivePrimes)} additive primes less than {limit}")  
http://rosettacode.org/wiki/Additive_primes
Additive primes
Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS entry:   A046704 additive primes.   the prime-numbers entry:   additive primes.   the geeks for geeks entry: additive prime number.   the prime-numbers fandom: additive primes.
#Seed7
Seed7
$ include "seed7_05.s7i";   const func boolean: isPrime (in integer: number) is func result var boolean: prime is FALSE; local var integer: upTo is 0; var integer: testNum is 3; begin if number = 2 then prime := TRUE; elsif odd(number) and number > 2 then upTo := sqrt(number); while number rem testNum <> 0 and testNum <= upTo do testNum +:= 2; end while; prime := testNum > upTo; end if; end func;   const func integer: digitSum (in var integer: number) is func result var integer: sum is 0; begin while number > 0 do sum +:= number rem 10; number := number div 10; end while; end func;   const proc: main is func local var integer: n is 0; var integer: count is 0; begin for n range 2 to 499 do if isPrime(n) and isPrime(digitSum(n)) then write(n lpad 3 <& " "); incr(count); if count rem 9 = 0 then writeln; end if; end if; end for; writeln("\nFound " <& count <& " additive primes < 500."); end func;
http://rosettacode.org/wiki/Additive_primes
Additive primes
Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS entry:   A046704 additive primes.   the prime-numbers entry:   additive primes.   the geeks for geeks entry: additive prime number.   the prime-numbers fandom: additive primes.
#Sidef
Sidef
func additive_primes(upto, base = 10) { upto.primes.grep { .sumdigits(base).is_prime } }   additive_primes(500).each_slice(10, {|*a| a.map { '%3s' % _ }.join(' ').say })
http://rosettacode.org/wiki/Almost_prime
Almost prime
A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,   where   k = 2 {\displaystyle k=2} ,   are the   semiprimes. Task Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for   1 <= K <= 5 {\displaystyle 1<=K<=5} . Related tasks   Semiprime   Category:Prime Numbers
#Processing
Processing
void setup() { for (int i = 1; i <= 5; i++) { int count = 0; print("k = " + i + ": "); int n = 2; while (count < 10) { if (isAlmostPrime(i, n)) { count++; print(n + " "); } n++; } println(); } }   boolean isAlmostPrime(int k, int n) { if (countPrimeFactors(n) == k) { return true; } else { return false; } }   int countPrimeFactors(int n) { int count = 0; int i = 2; while (n > 1) { if (n % i == 0) { n /= i; count++; } else { i++; } } return count; }
http://rosettacode.org/wiki/Almost_prime
Almost prime
A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,   where   k = 2 {\displaystyle k=2} ,   are the   semiprimes. Task Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for   1 <= K <= 5 {\displaystyle 1<=K<=5} . Related tasks   Semiprime   Category:Prime Numbers
#PureBasic
PureBasic
EnableExplicit   Procedure.b kprime(n.i, k.i) Define p.i = 2, f.i = 0   While f < k And p*p <= n While n % p = 0 n / p f + 1 Wend p + 1 Wend   ProcedureReturn Bool(f + Bool(n > 1) = k)   EndProcedure   ;___main____ If Not OpenConsole("Almost prime") End -1 EndIf   Define i.i, c.i, k.i   For k = 1 To 5 Print("k = " + Str(k) + ":")   i = 2 c = 0 While c < 10 If kprime(i, k) Print(RSet(Str(i),4)) c + 1 EndIf i + 1 Wend PrintN("") Next   Input()
http://rosettacode.org/wiki/Anagrams
Anagrams
When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in them. Related tasks Word plays Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams 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
package main   import ( "bytes" "fmt" "io/ioutil" "net/http" "sort" )   func main() { r, err := http.Get("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt") if err != nil { fmt.Println(err) return } b, err := ioutil.ReadAll(r.Body) r.Body.Close() if err != nil { fmt.Println(err) return } var ma int var bs byteSlice m := make(map[string][][]byte) for _, word := range bytes.Fields(b) { bs = append(bs[:0], byteSlice(word)...) sort.Sort(bs) k := string(bs) a := append(m[k], word) if len(a) > ma { ma = len(a) } m[k] = a } for _, a := range m { if len(a) == ma { fmt.Printf("%s\n", a) } } }   type byteSlice []byte   func (b byteSlice) Len() int { return len(b) } func (b byteSlice) Swap(i, j int) { b[i], b[j] = b[j], b[i] } func (b byteSlice) Less(i, j int) bool { return b[i] < b[j] }
http://rosettacode.org/wiki/Anonymous_recursion
Anonymous recursion
While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects,   and/or the function doesn't have the right arguments and/or return values. So we end up inventing some silly name like   foo2   or   foo_helper.   I have always found it painful to come up with a proper name, and see some disadvantages:   You have to think up a name, which then pollutes the namespace   Function is created which is called from nowhere else   The program flow in the source code is interrupted Some languages allow you to embed recursion directly in-place.   This might work via a label, a local gosub instruction, or some special keyword. Anonymous recursion can also be accomplished using the   Y combinator. Task If possible, demonstrate this by writing the recursive version of the fibonacci function   (see Fibonacci sequence)   which checks for a negative argument before doing the actual recursion.
#Ruby
Ruby
def fib(n) raise RangeError, "fib of negative" if n < 0 (fib2 = proc { |m| m < 2 ? m : fib2[m - 1] + fib2[m - 2] })[n] end
http://rosettacode.org/wiki/Amicable_pairs
Amicable pairs
Two integers N {\displaystyle N} and M {\displaystyle M} are said to be amicable pairs if N ≠ M {\displaystyle N\neq M} and the sum of the proper divisors of N {\displaystyle N} ( s u m ( p r o p D i v s ( N ) ) {\displaystyle \mathrm {sum} (\mathrm {propDivs} (N))} ) = M {\displaystyle =M} as well as s u m ( p r o p D i v s ( M ) ) = N {\displaystyle \mathrm {sum} (\mathrm {propDivs} (M))=N} . Example 1184 and 1210 are an amicable pair, with proper divisors:   1, 2, 4, 8, 16, 32, 37, 74, 148, 296, 592   and   1, 2, 5, 10, 11, 22, 55, 110, 121, 242, 605   respectively. Task Calculate and show here the Amicable pairs below 20,000; (there are eight). Related tasks Proper divisors Abundant, deficient and perfect number classifications Aliquot sequence classifications and its amicable classification.
#Racket
Racket
#lang racket (require "proper-divisors.rkt") (define SCOPE 20000)   (define P (let ((P-v (vector))) (λ (n) (set! P-v (fold-divisors P-v n 0 +)) (vector-ref P-v n))))   ;; returns #f if not an amicable number, amicable pairing otherwise (define (amicable? n) (define m (P n)) (define m-sod (P m)) (and (= m-sod n) (< m n) ; each pair exactly once, also eliminates perfect numbers m))   (void (amicable? SCOPE)) ; prime the memoisation   (for* ((n (in-range 1 (add1 SCOPE))) (m (in-value (amicable? n))) #:when m) (printf #<<EOS amicable pair: ~a, ~a ~a: divisors: ~a ~a: divisors: ~a     EOS n m n (proper-divisors n) m (proper-divisors m)))  
http://rosettacode.org/wiki/Animate_a_pendulum
Animate a pendulum
One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display. The classic such physical system is a simple gravity pendulum. Task Create a simple physical model of a pendulum and animate it.
#Yabasic
Yabasic
clear screen open window 400, 300 window origin "cc"   rodLen = 160 gravity = 2 damp = .989 TWO_PI = pi * 2 angle = 90 * 0.01745329251 // convert degree to radian   repeat acceleration = -gravity / rodLen * sin(angle) angle = angle + velocity : if angle > TWO_PI angle = 0 velocity = velocity + acceleration velocity = velocity * damp posX = sin(angle) * rodLen posY = cos(angle) * rodLen - 70 clear window text -50, -100, "Press 'q' to quit" color 250, 0, 250 fill circle 0, -70, 4 line 0, -70, posX, posY color 250, 100, 20 fill circle posX, posY, 10 until(lower$(inkey$(0.02)) = "q")   exit
http://rosettacode.org/wiki/Amb
Amb
Define and give an example of the Amb operator. The Amb operator (short for "ambiguous") expresses nondeterminism. This doesn't refer to randomness (as in "nondeterministic universe") but is closely related to the term as it is used in automata theory ("non-deterministic finite automaton"). The Amb operator takes a variable number of expressions (or values if that's simpler in the language) and yields a correct one which will satisfy a constraint in some future computation, thereby avoiding failure. Problems whose solution the Amb operator naturally expresses can be approached with other tools, such as explicit nested iterations over data sets, or with pattern matching. By contrast, the Amb operator appears integrated into the language. Invocations of Amb are not wrapped in any visible loops or other search patterns; they appear to be independent. Essentially Amb(x, y, z) splits the computation into three possible futures: a future in which the value x is yielded, a future in which the value y is yielded and a future in which the value z is yielded. The future which leads to a successful subsequent computation is chosen. The other "parallel universes" somehow go away. Amb called with no arguments fails. For simplicity, one of the domain values usable with Amb may denote failure, if that is convenient. For instance, it is convenient if a Boolean false denotes failure, so that Amb(false) fails, and thus constraints can be expressed using Boolean expressions like Amb(x * y == 8) which unless x and y add to four. A pseudo-code program which satisfies this constraint might look like: let x = Amb(1, 2, 3) let y = Amb(7, 6, 4, 5) Amb(x * y = 8) print x, y The output is 2 4 because Amb(1, 2, 3) correctly chooses the future in which x has value 2, Amb(7, 6, 4, 5) chooses 4 and consequently Amb(x * y = 8) produces a success. Alternatively, failure could be represented using strictly Amb(): unless x * y = 8 do Amb() Or else Amb could take the form of two operators or functions: one for producing values and one for enforcing constraints: let x = Ambsel(1, 2, 3) let y = Ambsel(4, 5, 6) Ambassert(x * y = 8) print x, y where Ambassert behaves like Amb() if the Boolean expression is false, otherwise it allows the future computation to take place, without yielding any value. The task is to somehow implement Amb, and demonstrate it with a program which chooses one word from each of the following four sets of character strings to generate a four-word sentence: "the" "that" "a" "frog" "elephant" "thing" "walked" "treaded" "grows" "slowly" "quickly" The constraint to be satisfied is that the last character of each word (other than the last) is the same as the first character of its successor. The only successful sentence is "that thing grows slowly"; other combinations do not satisfy the constraint and thus fail. The goal of this task isn't to simply process the four lists of words with explicit, deterministic program flow such as nested iteration, to trivially demonstrate the correct output. The goal is to implement the Amb operator, or a facsimile thereof that is possible within the language limitations.
#Phix
Phix
function amb1(sequence sets, object res=0, integer idx=1) integer ch = 0, pass = 0 if idx>length(sets) then pass = 1 else if res=0 then res = repeat(0,length(sets)) else res = deep_copy(res) ch = sets[idx-1][res[idx-1]][$] end if for k=1 to length(sets[idx]) do if ch=0 or sets[idx][k][1]=ch then res[idx] = k {pass,res} = amb1(sets,res,idx+1) if pass then exit end if end if end for end if return {pass,res} end function sequence sets = {{"the","that","a"}, {"frog","elephant","thing"}, {"walked","treaded","grows"}, {"slowly","quickly"}} {integer pass, sequence res} = amb1(sets) if pass then puts(1,"success: ") for i=1 to length(sets) do res[i] = sets[i][res[i]] end for ?res else puts(1,"failure\n") end if
http://rosettacode.org/wiki/Accumulator_factory
Accumulator factory
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created). Rules The detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in small italic text). Before you submit an example, make sure the function Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i). Although these exact function and parameter names need not be used Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) (i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that) Generates functions that return the sum of every number ever passed to them, not just the most recent. (This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.) Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. (Follow your language's conventions here.) Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. (No global variables or other such things.) E.g. if after the example, you added the following code (in a made-up language) where the factory function is called foo: x = foo(1); x(5); foo(3); print x(2.3); It should print 8.3. (There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.) Task Create a function that implements the described rules. It need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them. Where it is not possible to hold exactly to the constraints above, describe the deviations.
#Java
Java
public class Accumulator //implements java.util.function.UnaryOperator<Number> // Java 8 { private Number sum;   public Accumulator(Number sum0) { sum = sum0; }   public Number apply(Number n) { // Acts like sum += n, but chooses long or double. // Converts weird types (like BigInteger) to double. return (longable(sum) && longable(n)) ? (sum = sum.longValue() + n.longValue()) : (sum = sum.doubleValue() + n.doubleValue()); }   private static boolean longable(Number n) { return n instanceof Byte || n instanceof Short || n instanceof Integer || n instanceof Long; }   public static void main(String[] args) { Accumulator x = new Accumulator(1); x.apply(5); new Accumulator(3); System.out.println(x.apply(2.3)); } }  
http://rosettacode.org/wiki/Ackermann_function
Ackermann function
The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { n + 1 if  m = 0 A ( m − 1 , 1 ) if  m > 0  and  n = 0 A ( m − 1 , A ( m , n − 1 ) ) if  m > 0  and  n > 0. {\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}} Its arguments are never negative and it always terminates. Task Write a function which returns the value of A ( m , n ) {\displaystyle A(m,n)} . Arbitrary precision is preferred (since the function grows so quickly), but not required. See also Conway chained arrow notation for the Ackermann function.
#Arturo
Arturo
ackermann: function [m,n][ (m=0)? -> n+1 [ (n=0)? -> ackermann m-1 1 -> ackermann m-1 ackermann m n-1 ] ]   loop 0..3 'a [ loop 0..4 'b [ print ["ackermann" a b "=>" ackermann a b] ] ]
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications
Abundant, deficient and perfect number classifications
These define three classifications of positive integers based on their   proper divisors. Let   P(n)   be the sum of the proper divisors of   n   where the proper divisors are all positive divisors of   n   other than   n   itself. if P(n) < n then n is classed as deficient (OEIS A005100). if P(n) == n then n is classed as perfect (OEIS A000396). if P(n) > n then n is classed as abundant (OEIS A005101). Example 6   has proper divisors of   1,   2,   and   3. 1 + 2 + 3 = 6,   so   6   is classed as a perfect number. Task Calculate how many of the integers   1   to   20,000   (inclusive) are in each of the three classes. Show the results here. Related tasks   Aliquot sequence classifications.   (The whole series from which this task is a subset.)   Proper divisors   Amicable pairs
#Clojure
Clojure
(defn pad-class [n] (let [divs (filter #(zero? (mod n %)) (range 1 n)) divs-sum (reduce + divs)] (cond (< divs-sum n) :deficient (= divs-sum n) :perfect (> divs-sum n) :abundant)))   (def pad-classes (map pad-class (map inc (range))))   (defn count-classes [n] (let [classes (take n pad-classes)] {:perfect (count (filter #(= % :perfect) classes))  :abundant (count (filter #(= % :abundant) classes))  :deficient (count (filter #(= % :deficient) classes))}))
http://rosettacode.org/wiki/Align_columns
Align columns
Given a text file of many lines, where fields within a line are delineated by a single 'dollar' character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be either left justified, right justified, or center justified within its column. Use the following text to test your programs: Given$a$text$file$of$many$lines,$where$fields$within$a$line$ are$delineated$by$a$single$'dollar'$character,$write$a$program that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$ column$are$separated$by$at$least$one$space. Further,$allow$for$each$word$in$a$column$to$be$either$left$ justified,$right$justified,$or$center$justified$within$its$column. Note that:   The example input texts lines may, or may not, have trailing dollar characters.   All columns should share the same alignment.   Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.   Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.   The minimum space between columns should be computed from the text and not hard-coded.   It is not a requirement to add separating characters between or around columns. 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
#D
D
void main() { import std.stdio, std.string, std.algorithm, std.range, std.typetuple;   immutable data = "Given$a$txt$file$of$many$lines,$where$fields$within$a$line$ are$delineated$by$a$single$'dollar'$character,$write$a$program that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$ column$are$separated$by$at$least$one$space. Further,$allow$for$each$word$in$a$column$to$be$either$left$ justified,$right$justified,$or$center$justified$within$its$column." .split.map!(r => r.chomp("$").split("$")).array;   size_t[size_t] maxWidths; foreach (const line; data) foreach (immutable i, const word; line) maxWidths[i] = max(maxWidths.get(i, 0), word.length);   foreach (immutable just; TypeTuple!(leftJustify, center, rightJustify)) foreach (immutable line; data) writefln("%-(%s %)", line.length.iota .map!(i => just(line[i], maxWidths[i], ' '))); }
http://rosettacode.org/wiki/Active_object
Active object
In object-oriented programming an object is active when its state depends on clock. Usually an active object encapsulates a task that updates the object's state. To the outer world the object looks like a normal object with methods that can be called from outside. Implementation of such methods must have a certain synchronization mechanism with the encapsulated task in order to prevent object's state corruption. A typical instance of an active object is an animation widget. The widget state changes with the time, while as an object it has all properties of a normal widget. The task Implement an active integrator object. The object has an input and output. The input can be set using the method Input. The input is a function of time. The output can be queried using the method Output. The object integrates its input over the time and the result becomes the object's output. So if the input is K(t) and the output is S, the object state S is changed to S + (K(t1) + K(t0)) * (t1 - t0) / 2, i.e. it integrates K using the trapeze method. Initially K is constant 0 and S is 0. In order to test the object: set its input to sin (2π f t), where the frequency f=0.5Hz. The phase is irrelevant. wait 2s set the input to constant 0 wait 0.5s Verify that now the object's output is approximately 0 (the sine has the period of 2s). The accuracy of the result will depend on the OS scheduler time slicing and the accuracy of the clock.
#Racket
Racket
  #lang racket   (require (only-in racket/gui sleep/yield timer%))   (define active% (class object% (super-new) (init-field k) ; input function (field [s 0])  ; state (define t_0 0)   (define/public (input new-k) (set! k new-k)) (define/public (output) s)   (define (callback) (define t_1 (/ (- (current-inexact-milliseconds) start) 1000)) (set! s (+ s (* (+ (k t_0) (k t_1)) (/ (- t_1 t_0) 2)))) (set! t_0 t_1))   (define start (current-inexact-milliseconds)) (new timer% [interval 1000] [notify-callback callback])))   (define active (new active% [k (λ (t) (sin (* 2 pi 0.5 t)))])) (sleep/yield 2) (send active input (λ _ 0)) (sleep/yield 0.5) (displayln (send active output))  
http://rosettacode.org/wiki/Active_object
Active object
In object-oriented programming an object is active when its state depends on clock. Usually an active object encapsulates a task that updates the object's state. To the outer world the object looks like a normal object with methods that can be called from outside. Implementation of such methods must have a certain synchronization mechanism with the encapsulated task in order to prevent object's state corruption. A typical instance of an active object is an animation widget. The widget state changes with the time, while as an object it has all properties of a normal widget. The task Implement an active integrator object. The object has an input and output. The input can be set using the method Input. The input is a function of time. The output can be queried using the method Output. The object integrates its input over the time and the result becomes the object's output. So if the input is K(t) and the output is S, the object state S is changed to S + (K(t1) + K(t0)) * (t1 - t0) / 2, i.e. it integrates K using the trapeze method. Initially K is constant 0 and S is 0. In order to test the object: set its input to sin (2π f t), where the frequency f=0.5Hz. The phase is irrelevant. wait 2s set the input to constant 0 wait 0.5s Verify that now the object's output is approximately 0 (the sine has the period of 2s). The accuracy of the result will depend on the OS scheduler time slicing and the accuracy of the clock.
#Raku
Raku
class Integrator { has $.f is rw = sub ($t) { 0 }; has $.now is rw; has $.value is rw = 0; has $.integrator is rw;   method init() { self.value = &(self.f)(0); self.integrator = Thread.new( :code({ loop { my $t1 = now; self.value += (&(self.f)(self.now) + &(self.f)($t1)) * ($t1 - self.now) / 2; self.now = $t1; sleep .001; } }), :app_lifetime(True) ).run }   method Input (&f-of-t) { self.f = &f-of-t; self.now = now; self.init; }   method Output { self.value } }   my $a = Integrator.new;   $a.Input( sub ($t) { sin(2 * π * .5 * $t) } );   say "Initial value: ", $a.Output;   sleep 2;   say "After 2 seconds: ", $a.Output;   $a.Input( sub ($t) { 0 } );   sleep .5;   say "f(0): ", $a.Output;
http://rosettacode.org/wiki/Aliquot_sequence_classifications
Aliquot sequence classifications
An aliquot sequence of a positive integer K is defined recursively as the first member being K and subsequent members being the sum of the Proper divisors of the previous term. If the terms eventually reach 0 then the series for K is said to terminate. There are several classifications for non termination: If the second term is K then all future terms are also K and so the sequence repeats from the first term with period 1 and K is called perfect. If the third term would be repeating K then the sequence repeats with period 2 and K is called amicable. If the Nth term would be repeating K for the first time, with N > 3 then the sequence repeats with period N - 1 and K is called sociable. Perfect, amicable and sociable numbers eventually repeat the original number K; there are other repetitions... Some K have a sequence that eventually forms a periodic repetition of period 1 but of a number other than K, for example 95 which forms the sequence 95, 25, 6, 6, 6, ... such K are called aspiring. K that have a sequence that eventually forms a periodic repetition of period >= 2 but of a number other than K, for example 562 which forms the sequence 562, 284, 220, 284, 220, ... such K are called cyclic. And finally: Some K form aliquot sequences that are not known to be either terminating or periodic; these K are to be called non-terminating. For the purposes of this task, K is to be classed as non-terminating if it has not been otherwise classed after generating 16 terms or if any term of the sequence is greater than 2**47 = 140,737,488,355,328. Task Create routine(s) to generate the aliquot sequence of a positive integer enough to classify it according to the classifications given above. Use it to display the classification and sequences of the numbers one to ten inclusive. Use it to show the classification and sequences of the following integers, in order: 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, and optionally 15355717786080. Show all output on this page. Related tasks   Abundant, deficient and perfect number classifications. (Classifications from only the first two members of the whole sequence).   Proper divisors   Amicable pairs
#REXX
REXX
/*REXX program classifies various positive integers for types of aliquot sequences. */ parse arg low high $L /*obtain optional arguments from the CL*/ high= word(high low 10,1); low= word(low 1,1) /*obtain the LOW and HIGH (range). */ if $L='' then $L=11 12 28 496 220 1184 12496 1264460 790 909 562 1064 1488 15355717786080 numeric digits 100 /*be able to compute the number: BIG */ big= 2**47; NTlimit= 16 + 1 /*limits for a non─terminating sequence*/ numeric digits max(9, length(big) ) /*be able to handle big numbers for // */ digs= digits() /*used for align numbers for the output*/ #.= .; #.0= 0; #.1= 0 /*#. are the proper divisor sums. */ say center('numbers from ' low " ───► " high ' (inclusive)', 153, "═") do n=low to high; call classify n /*call a subroutine to classify number.*/ end /*n*/ /* [↑] process a range of integers. */ say say center('first numbers for each classification', 153, "═") class.= 0 /* [↓] ensure one number of each class*/ do q=1 until class.sociable\==0 /*the only one that has to be counted. */ call classify -q /*minus (-) sign indicates don't tell. */ _= what; upper _ /*obtain the class and uppercase it. */ class._= class._ + 1 /*bump counter for this class sequence.*/ if class._==1 then say right(q, digs)':' center(what, digs) $ end /*q*/ /* [↑] only display the 1st occurrence*/ say /* [↑] process until all classes found*/ say center('classifications for specific numbers', 153, "═") do i=1 for words($L) /*$L: is a list of "special numbers".*/ call classify word($L, i) /*call a subroutine to classify number.*/ end /*i*/ /* [↑] process a list of integers. */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ classify: parse arg a 1 aa; a= abs(a) /*obtain number that's to be classified*/ if #.a\==. then s= #.a /*Was this number been summed before?*/ else s= sigma(a) /*No, then classify number the hard way*/ #.a= s /*define sum of the proper divisors. */ $= s /*define the start of integer sequence.*/ what= 'terminating' /*assume this kind of classification. */ c.= 0 /*clear all cyclic sequences (to zero).*/ c.s= 1 /*set the first cyclic sequence. */ if $==a then what= 'perfect' /*check for a "perfect" number. */ else do t=1 while s>0 /*loop until sum isn't 0 or > big.*/ m= s /*obtain the last number in sequence. */ if #.m==. then s= sigma(m) /*Not defined? Then sum proper divisors*/ else s= #.m /*use the previously found integer. */ if m==s then if m>=0 then do; what= 'aspiring'; leave; end parse var $ . word2 . /*obtain the 2nd number in sequence. */ if word2==a then do; what= 'amicable'; leave; end $= $ s /*append a sum to the integer sequence.*/ if s==a then if t>3 then do; what= 'sociable'; leave; end if c.s then if m>0 then do; what= 'cyclic'  ; leave; end c.s= 1 /*assign another possible cyclic number*/ /* [↓] Rosetta Code task's limit: >16 */ if t>NTlimit then do; what= 'non─terminating'; leave; end if s>big then do; what= 'NON─TERMINATING'; leave; end end /*t*/ /* [↑] only permit within reason. */ if aa>0 then say right(a, digs)':' center(what, digs) $ return /* [↑] only display if AA is positive*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ sigma: procedure expose #. !.; parse arg x; if 11<2 then return 0; odd= x // 2 s= 1 /* [↓] use EVEN or ODD integers. ___*/ do j=2+odd by 1+odd while j*j<x /*divide by all the integers up to √ X */ if x//j==0 then s= s + j + x % j /*add the two divisors to the sum. */ end /*j*/ /* [↓] adjust for square. ___*/ if j*j==x then s= s + j /*Was X a square? If so, add √ X */ #.x= s /*memoize division sum for argument X.*/ return s /*return " " " " " */
http://rosettacode.org/wiki/AKS_test_for_primes
AKS test for primes
The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles. The theorem on which the test is based can be stated as follows:   a number   p {\displaystyle p}   is prime   if and only if   all the coefficients of the polynomial expansion of ( x − 1 ) p − ( x p − 1 ) {\displaystyle (x-1)^{p}-(x^{p}-1)} are divisible by   p {\displaystyle p} . Example Using   p = 3 {\displaystyle p=3} : (x-1)^3 - (x^3 - 1) = (x^3 - 3x^2 + 3x - 1) - (x^3 - 1) = -3x^2 + 3x And all the coefficients are divisible by 3,   so 3 is prime. Note: This task is not the AKS primality test.   It is an inefficient exponential time algorithm discovered in the late 1600s and used as an introductory lemma in the AKS derivation. Task Create a function/subroutine/method that given   p {\displaystyle p}   generates the coefficients of the expanded polynomial representation of   ( x − 1 ) p {\displaystyle (x-1)^{p}} . Use the function to show here the polynomial expansions of   ( x − 1 ) p {\displaystyle (x-1)^{p}}   for   p {\displaystyle p}   in the range   0   to at least   7,   inclusive. Use the previous function in creating another function that when given   p {\displaystyle p}   returns whether   p {\displaystyle p}   is prime using the theorem. Use your test to generate a list of all primes under   35. As a stretch goal,   generate all primes under   50   (needs integers larger than 31-bit). References Agrawal-Kayal-Saxena (AKS) primality test (Wikipedia) Fool-Proof Test for Primes - Numberphile (Video). The accuracy of this video is disputed -- at best it is an oversimplification.
#Maple
Maple
> for xpr in seq( expand( (x-1)^p ), p = 0 .. 7 ) do print( xpr ) end: 1   x - 1   2 x - 2 x + 1   3 2 x - 3 x + 3 x - 1   4 3 2 x - 4 x + 6 x - 4 x + 1   5 4 3 2 x - 5 x + 10 x - 10 x + 5 x - 1   6 5 4 3 2 x - 6 x + 15 x - 20 x + 15 x - 6 x + 1   7 6 5 4 3 2 x - 7 x + 21 x - 35 x + 35 x - 21 x + 7 x - 1  
http://rosettacode.org/wiki/Additive_primes
Additive primes
Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS entry:   A046704 additive primes.   the prime-numbers entry:   additive primes.   the geeks for geeks entry: additive prime number.   the prime-numbers fandom: additive primes.
#TSE_SAL
TSE SAL
    INTEGER PROC FNMathGetSquareRootI( INTEGER xI ) INTEGER squareRootI = 0 IF ( xI > 0 ) WHILE( ( squareRootI * squareRootI ) <= xI ) squareRootI = squareRootI + 1 ENDWHILE squareRootI = squareRootI - 1 ENDIF RETURN( squareRootI ) END // INTEGER PROC FNMathCheckIntegerIsPrimeB( INTEGER nI ) INTEGER I = 0 INTEGER primeB = FALSE INTEGER stopB = FALSE INTEGER restI = 0 INTEGER limitI = 0 primeB = FALSE IF ( nI <= 0 ) RETURN( FALSE ) ENDIF IF ( nI == 1 ) RETURN( FALSE ) ENDIF IF ( nI == 2 ) RETURN( TRUE ) ENDIF IF ( nI == 3 ) RETURN( TRUE ) ENDIF IF ( nI MOD 2 == 0 ) RETURN( FALSE ) ENDIF IF ( ( nI MOD 6 ) <> 1 ) AND ( ( nI MOD 6 ) <> 5 ) RETURN( FALSE ) ENDIF limitI = FNMathGetSquareRootI( nI ) I = 3 REPEAT restI = ( nI MOD I ) IF ( restI == 0 ) primeB = FALSE stopB = TRUE ENDIF IF ( I > limitI ) primeB = TRUE stopB = TRUE ENDIF I = I + 2 UNTIL ( stopB ) RETURN( primeB ) END // INTEGER PROC FNMathCheckIntegerDigitSumI( INTEGER J ) STRING s[255] = Str( J ) STRING cS[255] = "" INTEGER minI = 1 INTEGER maxI = Length( s ) INTEGER I = 0 INTEGER K = 0 FOR I = minI TO maxI cS = s[ I ] K = K + Val( cS ) ENDFOR RETURN( K ) END // INTEGER PROC FNMathCheckIntegerDigitSumIsPrimeB( INTEGER I ) INTEGER J = FNMathCheckIntegerDigitSumI( I ) INTEGER B = FNMathCheckIntegerIsPrimeB( J ) RETURN( B ) END // INTEGER PROC FNMathGetPrimeAdditiveAllToBufferB( INTEGER maxI, INTEGER bufferI ) INTEGER B = FALSE INTEGER B1 = FALSE INTEGER B2 = FALSE INTEGER B3 = FALSE INTEGER minI = 2 INTEGER I = 0 FOR I = minI TO maxI B1 = FNMathCheckIntegerIsPrimeB( I ) B2 = FNMathCheckIntegerDigitSumIsPrimeB( I ) B3 = B1 AND B2 IF ( B3 ) PushPosition() PushBlock() GotoBufferId( bufferI ) AddLine( Str( I ) ) PopBlock() PopPosition() ENDIF ENDFOR B = TRUE RETURN( B ) END // PROC Main() STRING s1[255] = "500" // change this INTEGER bufferI = 0 PushPosition() bufferI = CreateTempBuffer() PopPosition() IF ( NOT ( Ask( " = ", s1, _EDIT_HISTORY_ ) ) AND ( Length( s1 ) > 0 ) ) RETURN() ENDIF Message( FNMathGetPrimeAdditiveAllToBufferB( Val( s1 ), bufferI ) ) // gives e.g. TRUE GotoBufferId( bufferI ) END    
http://rosettacode.org/wiki/Additive_primes
Additive primes
Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS entry:   A046704 additive primes.   the prime-numbers entry:   additive primes.   the geeks for geeks entry: additive prime number.   the prime-numbers fandom: additive primes.
#Swift
Swift
import Foundation   func isPrime(_ n: Int) -> Bool { if n < 2 { return false } if n % 2 == 0 { return n == 2 } if n % 3 == 0 { return n == 3 } var p = 5 while p * p <= n { if n % p == 0 { return false } p += 2 if n % p == 0 { return false } p += 4 } return true }   func digitSum(_ num: Int) -> Int { var sum = 0 var n = num while n > 0 { sum += n % 10 n /= 10 } return sum }   let limit = 500 print("Additive primes less than \(limit):") var count = 0 for n in 1..<limit { if isPrime(digitSum(n)) && isPrime(n) { count += 1 print(String(format: "%3d", n), terminator: count % 10 == 0 ? "\n" : " ") } } print("\n\(count) additive primes found.")
http://rosettacode.org/wiki/Additive_primes
Additive primes
Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS entry:   A046704 additive primes.   the prime-numbers entry:   additive primes.   the geeks for geeks entry: additive prime number.   the prime-numbers fandom: additive primes.
#Vlang
Vlang
fn is_prime(n int) bool { if n < 2 { return false } else if n%2 == 0 { return n == 2 } else if n%3 == 0 { return n == 3 } else { mut d := 5 for d*d <= n { if n%d == 0 { return false } d += 2 if n%d == 0 { return false } d += 4 } return true } }   fn sum_digits(nn int) int { mut n := nn mut sum := 0 for n > 0 { sum += n % 10 n /= 10 } return sum }   fn main() { println("Additive primes less than 500:") mut i := 2 mut count := 0 for { if is_prime(i) && is_prime(sum_digits(i)) { count++ print("${i:3} ") if count%10 == 0 { println('') } } if i > 2 { i += 2 } else { i++ } if i > 499 { break } } println("\n\n$count additive primes found.") }
http://rosettacode.org/wiki/Almost_prime
Almost prime
A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,   where   k = 2 {\displaystyle k=2} ,   are the   semiprimes. Task Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for   1 <= K <= 5 {\displaystyle 1<=K<=5} . Related tasks   Semiprime   Category:Prime Numbers
#Python
Python
from prime_decomposition import decompose from itertools import islice, count try: from functools import reduce except: pass     def almostprime(n, k=2): d = decompose(n) try: terms = [next(d) for i in range(k)] return reduce(int.__mul__, terms, 1) == n except: return False   if __name__ == '__main__': for k in range(1,6): print('%i: %r' % (k, list(islice((n for n in count() if almostprime(n, k)), 10))))
http://rosettacode.org/wiki/Anagrams
Anagrams
When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in them. Related tasks Word plays Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams 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 words = new URL('http://wiki.puzzlers.org/pub/wordlists/unixdict.txt').text.readLines() def groups = words.groupBy{ it.toList().sort() } def bigGroupSize = groups.collect{ it.value.size() }.max() def isBigAnagram = { it.value.size() == bigGroupSize } println groups.findAll(isBigAnagram).collect{ it.value }.collect{ it.join(' ') }.join('\n')
http://rosettacode.org/wiki/Anonymous_recursion
Anonymous recursion
While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects,   and/or the function doesn't have the right arguments and/or return values. So we end up inventing some silly name like   foo2   or   foo_helper.   I have always found it painful to come up with a proper name, and see some disadvantages:   You have to think up a name, which then pollutes the namespace   Function is created which is called from nowhere else   The program flow in the source code is interrupted Some languages allow you to embed recursion directly in-place.   This might work via a label, a local gosub instruction, or some special keyword. Anonymous recursion can also be accomplished using the   Y combinator. Task If possible, demonstrate this by writing the recursive version of the fibonacci function   (see Fibonacci sequence)   which checks for a negative argument before doing the actual recursion.
#Rust
Rust
fn fib(n: i64) -> Option<i64> { // A function declared inside another function does not pollute the outer namespace. fn actual_fib(n: i64) -> i64 { if n < 2 { n } else { actual_fib(n - 1) + actual_fib(n - 2) } }   if n < 0 { None } else { Some(actual_fib(n)) } }   fn main() { println!("Fib(-1) = {:?}", fib(-1)); println!("Fib(0) = {:?}", fib(0)); println!("Fib(1) = {:?}", fib(1)); println!("Fib(2) = {:?}", fib(2)); println!("Fib(3) = {:?}", fib(3)); println!("Fib(4) = {:?}", fib(4)); println!("Fib(5) = {:?}", fib(5)); println!("Fib(10) = {:?}", fib(10)); }   #[test] fn test_fib() { assert_eq!(fib(0).unwrap(), 0); assert_eq!(fib(1).unwrap(), 1); assert_eq!(fib(2).unwrap(), 1); assert_eq!(fib(3).unwrap(), 2); assert_eq!(fib(4).unwrap(), 3); assert_eq!(fib(5).unwrap(), 5); assert_eq!(fib(10).unwrap(), 55); }   #[test] fn test_invalid_argument() { assert_eq!(fib(-1), None); }
http://rosettacode.org/wiki/Amicable_pairs
Amicable pairs
Two integers N {\displaystyle N} and M {\displaystyle M} are said to be amicable pairs if N ≠ M {\displaystyle N\neq M} and the sum of the proper divisors of N {\displaystyle N} ( s u m ( p r o p D i v s ( N ) ) {\displaystyle \mathrm {sum} (\mathrm {propDivs} (N))} ) = M {\displaystyle =M} as well as s u m ( p r o p D i v s ( M ) ) = N {\displaystyle \mathrm {sum} (\mathrm {propDivs} (M))=N} . Example 1184 and 1210 are an amicable pair, with proper divisors:   1, 2, 4, 8, 16, 32, 37, 74, 148, 296, 592   and   1, 2, 5, 10, 11, 22, 55, 110, 121, 242, 605   respectively. Task Calculate and show here the Amicable pairs below 20,000; (there are eight). Related tasks Proper divisors Abundant, deficient and perfect number classifications Aliquot sequence classifications and its amicable classification.
#Raku
Raku
sub propdivsum (\x) { my @l = 1 if x > 1; (2 .. x.sqrt.floor).map: -> \d { unless x % d { @l.push: d; my \y = x div d; @l.push: y if y != d } } sum @l }   (1..20000).race.map: -> $i { my $j = propdivsum($i); say "$i $j" if $j > $i and $i == propdivsum($j); }
http://rosettacode.org/wiki/Animate_a_pendulum
Animate a pendulum
One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display. The classic such physical system is a simple gravity pendulum. Task Create a simple physical model of a pendulum and animate it.
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 OVER 1: CLS 20 LET theta=1 30 LET g=9.81 40 LET l=0.5 50 LET speed=0 100 LET pivotx=120 110 LET pivoty=140 120 LET bobx=pivotx+l*100*SIN (theta) 130 LET boby=pivoty+l*100*COS (theta) 140 GO SUB 1000: PAUSE 1: GO SUB 1000 190 LET accel=g*SIN (theta)/l/100 200 LET speed=speed+accel/100 210 LET theta=theta+speed 220 GO TO 100 1000 PLOT pivotx,pivoty: DRAW bobx-pivotx,boby-pivoty 1010 CIRCLE bobx,boby,3 1020 RETURN
http://rosettacode.org/wiki/Amb
Amb
Define and give an example of the Amb operator. The Amb operator (short for "ambiguous") expresses nondeterminism. This doesn't refer to randomness (as in "nondeterministic universe") but is closely related to the term as it is used in automata theory ("non-deterministic finite automaton"). The Amb operator takes a variable number of expressions (or values if that's simpler in the language) and yields a correct one which will satisfy a constraint in some future computation, thereby avoiding failure. Problems whose solution the Amb operator naturally expresses can be approached with other tools, such as explicit nested iterations over data sets, or with pattern matching. By contrast, the Amb operator appears integrated into the language. Invocations of Amb are not wrapped in any visible loops or other search patterns; they appear to be independent. Essentially Amb(x, y, z) splits the computation into three possible futures: a future in which the value x is yielded, a future in which the value y is yielded and a future in which the value z is yielded. The future which leads to a successful subsequent computation is chosen. The other "parallel universes" somehow go away. Amb called with no arguments fails. For simplicity, one of the domain values usable with Amb may denote failure, if that is convenient. For instance, it is convenient if a Boolean false denotes failure, so that Amb(false) fails, and thus constraints can be expressed using Boolean expressions like Amb(x * y == 8) which unless x and y add to four. A pseudo-code program which satisfies this constraint might look like: let x = Amb(1, 2, 3) let y = Amb(7, 6, 4, 5) Amb(x * y = 8) print x, y The output is 2 4 because Amb(1, 2, 3) correctly chooses the future in which x has value 2, Amb(7, 6, 4, 5) chooses 4 and consequently Amb(x * y = 8) produces a success. Alternatively, failure could be represented using strictly Amb(): unless x * y = 8 do Amb() Or else Amb could take the form of two operators or functions: one for producing values and one for enforcing constraints: let x = Ambsel(1, 2, 3) let y = Ambsel(4, 5, 6) Ambassert(x * y = 8) print x, y where Ambassert behaves like Amb() if the Boolean expression is false, otherwise it allows the future computation to take place, without yielding any value. The task is to somehow implement Amb, and demonstrate it with a program which chooses one word from each of the following four sets of character strings to generate a four-word sentence: "the" "that" "a" "frog" "elephant" "thing" "walked" "treaded" "grows" "slowly" "quickly" The constraint to be satisfied is that the last character of each word (other than the last) is the same as the first character of its successor. The only successful sentence is "that thing grows slowly"; other combinations do not satisfy the constraint and thus fail. The goal of this task isn't to simply process the four lists of words with explicit, deterministic program flow such as nested iteration, to trivially demonstrate the correct output. The goal is to implement the Amb operator, or a facsimile thereof that is possible within the language limitations.
#Picat
Picat
go ?=>  % select which version of amb/2 and joins/2 to test member(Amb,[amb,amb2]), member(Joins,[joins,join2]), println([amb=Amb,joins=Joins]), test_amb(amb,joins, Word1,Word2,Word3,Word4), println([Word1, Word2, Word3, Word4]), nl, fail, % get other solutions nl. go => true.   % Test a combination of amb and joins test_amb(Amb,Joins, Word1,Word2,Word3,Word4) => call(Amb, Word1, ["the","that","a"]), call(Amb, Word2, ["frog","elephant","thing"]), call(Amb, Word3, ["walked","treaded","grows"]), call(Amb, Word4, ["slowly","quickly"]), call(Joins, Word1, Word2), call(Joins, Word2, Word3), call(Joins, Word3, Word4).   % Based on the Prolog solution. amb(E, [E|_]). amb(E, [_|ES]) :- amb(E, ES).   joins(Left, Right) => append(_, [T], Left), append([R], _, Right), ( T != R -> amb(_, [])  ; true ).   % Another approach, using member/2 for % generating the words. amb2([],[]). amb2(Word,Words) :- member(Word,Words).   joins2(Word1,Word2) :- Word1.last() = Word2.first().  
http://rosettacode.org/wiki/Amb
Amb
Define and give an example of the Amb operator. The Amb operator (short for "ambiguous") expresses nondeterminism. This doesn't refer to randomness (as in "nondeterministic universe") but is closely related to the term as it is used in automata theory ("non-deterministic finite automaton"). The Amb operator takes a variable number of expressions (or values if that's simpler in the language) and yields a correct one which will satisfy a constraint in some future computation, thereby avoiding failure. Problems whose solution the Amb operator naturally expresses can be approached with other tools, such as explicit nested iterations over data sets, or with pattern matching. By contrast, the Amb operator appears integrated into the language. Invocations of Amb are not wrapped in any visible loops or other search patterns; they appear to be independent. Essentially Amb(x, y, z) splits the computation into three possible futures: a future in which the value x is yielded, a future in which the value y is yielded and a future in which the value z is yielded. The future which leads to a successful subsequent computation is chosen. The other "parallel universes" somehow go away. Amb called with no arguments fails. For simplicity, one of the domain values usable with Amb may denote failure, if that is convenient. For instance, it is convenient if a Boolean false denotes failure, so that Amb(false) fails, and thus constraints can be expressed using Boolean expressions like Amb(x * y == 8) which unless x and y add to four. A pseudo-code program which satisfies this constraint might look like: let x = Amb(1, 2, 3) let y = Amb(7, 6, 4, 5) Amb(x * y = 8) print x, y The output is 2 4 because Amb(1, 2, 3) correctly chooses the future in which x has value 2, Amb(7, 6, 4, 5) chooses 4 and consequently Amb(x * y = 8) produces a success. Alternatively, failure could be represented using strictly Amb(): unless x * y = 8 do Amb() Or else Amb could take the form of two operators or functions: one for producing values and one for enforcing constraints: let x = Ambsel(1, 2, 3) let y = Ambsel(4, 5, 6) Ambassert(x * y = 8) print x, y where Ambassert behaves like Amb() if the Boolean expression is false, otherwise it allows the future computation to take place, without yielding any value. The task is to somehow implement Amb, and demonstrate it with a program which chooses one word from each of the following four sets of character strings to generate a four-word sentence: "the" "that" "a" "frog" "elephant" "thing" "walked" "treaded" "grows" "slowly" "quickly" The constraint to be satisfied is that the last character of each word (other than the last) is the same as the first character of its successor. The only successful sentence is "that thing grows slowly"; other combinations do not satisfy the constraint and thus fail. The goal of this task isn't to simply process the four lists of words with explicit, deterministic program flow such as nested iteration, to trivially demonstrate the correct output. The goal is to implement the Amb operator, or a facsimile thereof that is possible within the language limitations.
#PicoLisp
PicoLisp
(be amb (@E @Lst) (lst @E @Lst) )   (be joins (@Left @Right) (^ @T (last (chop (-> @Left)))) (^ @R (car (chop (-> @Right)))) (or ((equal @T @R)) ((amb @ NIL)) ) ) # Explicitly using amb fail as required   (be ambExample ((@Word1 @Word2 @Word3 @Word4)) (amb @Word1 ("the" "that" "a")) (amb @Word2 ("frog" "elephant" "thing")) (amb @Word3 ("walked" "treaded" "grows")) (amb @Word4 ("slowly" "quickly")) (joins @Word1 @Word2) (joins @Word2 @Word3) (joins @Word3 @Word4) )
http://rosettacode.org/wiki/Accumulator_factory
Accumulator factory
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created). Rules The detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in small italic text). Before you submit an example, make sure the function Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i). Although these exact function and parameter names need not be used Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) (i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that) Generates functions that return the sum of every number ever passed to them, not just the most recent. (This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.) Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. (Follow your language's conventions here.) Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. (No global variables or other such things.) E.g. if after the example, you added the following code (in a made-up language) where the factory function is called foo: x = foo(1); x(5); foo(3); print x(2.3); It should print 8.3. (There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.) Task Create a function that implements the described rules. It need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them. Where it is not possible to hold exactly to the constraints above, describe the deviations.
#JavaScript
JavaScript
function accumulator(sum) { return function(n) { return sum += n; } } var x = accumulator(1); x(5); console.log(accumulator(3).toString() + '<br>'); console.log(x(2.3));
http://rosettacode.org/wiki/Accumulator_factory
Accumulator factory
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created). Rules The detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in small italic text). Before you submit an example, make sure the function Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i). Although these exact function and parameter names need not be used Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) (i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that) Generates functions that return the sum of every number ever passed to them, not just the most recent. (This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.) Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. (Follow your language's conventions here.) Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. (No global variables or other such things.) E.g. if after the example, you added the following code (in a made-up language) where the factory function is called foo: x = foo(1); x(5); foo(3); print x(2.3); It should print 8.3. (There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.) Task Create a function that implements the described rules. It need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them. Where it is not possible to hold exactly to the constraints above, describe the deviations.
#Jsish
Jsish
/* Accumulator factory, in Jsish */ function accumulator(sum) { return function(n) { return sum += n; }; }   provide('accumulatorFactory', '0.6');   if (Interp.conf('unitTest')) { var x,y; ;x = accumulator(1); ;accumulator; ;x; ;x(5); ;accumulator(3); ;x(2.3);   ;y = accumulator(0); ;y; ;x(1); ;y(2); ;x(3); ;y(4); ;x(5); }   /* =!EXPECTSTART!= x = accumulator(1) ==> "function(n) {\n return sum += n;\n }" accumulator ==> "function accumulator(sum) {\n return function(n) {\n return sum += n;\n };\n}" x ==> "function(n) {\n return sum += n;\n }" x(5) ==> 6 accumulator(3) ==> "function(n) {\n return sum += n;\n }" x(2.3) ==> 8.3 y = accumulator(0) ==> "function(n) {\n return sum += n;\n }" y ==> "function(n) {\n return sum += n;\n }" x(1) ==> 9.3 y(2) ==> 2 x(3) ==> 12.3 y(4) ==> 6 x(5) ==> 17.3 =!EXPECTEND!= */
http://rosettacode.org/wiki/Ackermann_function
Ackermann function
The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { n + 1 if  m = 0 A ( m − 1 , 1 ) if  m > 0  and  n = 0 A ( m − 1 , A ( m , n − 1 ) ) if  m > 0  and  n > 0. {\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}} Its arguments are never negative and it always terminates. Task Write a function which returns the value of A ( m , n ) {\displaystyle A(m,n)} . Arbitrary precision is preferred (since the function grows so quickly), but not required. See also Conway chained arrow notation for the Ackermann function.
#ATS
ATS
fun ackermann {m,n:nat} .<m,n>. (m: int m, n: int n): Nat = case+ (m, n) of | (0, _) => n+1 | (_, 0) =>> ackermann (m-1, 1) | (_, _) =>> ackermann (m-1, ackermann (m, n-1)) // end of [ackermann]
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications
Abundant, deficient and perfect number classifications
These define three classifications of positive integers based on their   proper divisors. Let   P(n)   be the sum of the proper divisors of   n   where the proper divisors are all positive divisors of   n   other than   n   itself. if P(n) < n then n is classed as deficient (OEIS A005100). if P(n) == n then n is classed as perfect (OEIS A000396). if P(n) > n then n is classed as abundant (OEIS A005101). Example 6   has proper divisors of   1,   2,   and   3. 1 + 2 + 3 = 6,   so   6   is classed as a perfect number. Task Calculate how many of the integers   1   to   20,000   (inclusive) are in each of the three classes. Show the results here. Related tasks   Aliquot sequence classifications.   (The whole series from which this task is a subset.)   Proper divisors   Amicable pairs
#CLU
CLU
% Generate proper divisors from 1 to max proper_divisors = proc (max: int) returns (array[int]) divs: array[int] := array[int]$fill(1, max, 0) for i: int in int$from_to(1, max/2) do for j: int in int$from_to_by(i*2, max, i) do divs[j] := divs[j] + i end end return(divs) end proper_divisors   % Classify all the numbers for which we have divisors classify = proc (divs: array[int]) returns (int, int, int) def, per, ab: int def, per, ab := 0, 0, 0 for i: int in array[int]$indexes(divs) do if divs[i]<i then def := def + 1 elseif divs[i]=i then per := per + 1 elseif divs[i]>i then ab := ab + 1 end end return(def, per, ab) end classify   % Find amount of deficient, perfect, and abundant numbers up to 20000 start_up = proc () max = 20000   po: stream := stream$primary_output()   def, per, ab: int := classify(proper_divisors(max)) stream$putl(po, "Deficient: " || int$unparse(def)) stream$putl(po, "Perfect: " || int$unparse(per)) stream$putl(po, "Abundant: " || int$unparse(ab)) end start_up
http://rosettacode.org/wiki/Align_columns
Align columns
Given a text file of many lines, where fields within a line are delineated by a single 'dollar' character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be either left justified, right justified, or center justified within its column. Use the following text to test your programs: Given$a$text$file$of$many$lines,$where$fields$within$a$line$ are$delineated$by$a$single$'dollar'$character,$write$a$program that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$ column$are$separated$by$at$least$one$space. Further,$allow$for$each$word$in$a$column$to$be$either$left$ justified,$right$justified,$or$center$justified$within$its$column. Note that:   The example input texts lines may, or may not, have trailing dollar characters.   All columns should share the same alignment.   Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.   Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.   The minimum space between columns should be computed from the text and not hard-coded.   It is not a requirement to add separating characters between or around columns. 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
#Delphi
Delphi
  USES StdCtrls, Classes, SysUtils, StrUtils, Contnrs;   procedure AlignByColumn(Output: TMemo; Align: TAlignment); const TextToAlign = 'Given$a$text$file$of$many$lines,$where$fields$within$a$line$'#$D#$A + 'are$delineated$by$a$single$''dollar''$character,$write$a$program'#$D#$A + 'that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$'#$D#$A + 'column$are$separated$by$at$least$one$space.'#$D#$A + 'Further,$allow$for$each$word$in$a$column$to$be$either$left$'#$D#$A + 'justified,$right$justified,$or$center$justified$within$its$column.'; var TextLine, TempTString: TStringlist; TextLines: TObjectList; MaxLength, i, j: Byte; OutPutString, EmptyString, Item: String; begin TRY MaxLength := 0; TextLines := TObjectList.Create(True); TextLine := TStringList.Create; TextLine.text := TextToAlign; for i:= 0 to TextLine.Count - 1 do begin TempTString := TStringlist.create; TempTString.text :=AnsiReplaceStr(TextLine[i], '$', #$D#$A); TextLines.Add(TempTString); end; for i := 0 to TextLines.Count - 1 do for j := 0 to TStringList(TextLines.Items[i]).Count - 1 do If Length(TStringList(TextLines.Items[i])[j]) > MaxLength then MaxLength := Length(TStringList(TextLines.Items[i])[j]); If MaxLength > 0 then MaxLength := MaxLength + 2; // Add to empty spaces to it for i := 0 to TextLines.Count - 1 do begin OutPutString := ''; for j := 0 to TStringList(TextLines.Items[i]).Count - 1 do begin EmptyString := StringOfChar(' ', MaxLength); Item := TStringList(TextLines.Items[i])[j]; case Align of taLeftJustify: Move(Item[1], EmptyString[2], Length(Item)); taRightJustify: Move(Item[1], EmptyString[MaxLength - Length(Item) + 1], Length(Item)); taCenter: Move(Item[1], EmptyString[(MaxLength - Length(Item) + 1) div 2 + 1], Length(Item)); end; OutPutString := OutPutString + EmptyString; end; Output.Lines.Add(OutPutString); end; FINALLY FreeAndNil(TextLine); FreeAndNil(TextLines); END; end;  
http://rosettacode.org/wiki/Active_object
Active object
In object-oriented programming an object is active when its state depends on clock. Usually an active object encapsulates a task that updates the object's state. To the outer world the object looks like a normal object with methods that can be called from outside. Implementation of such methods must have a certain synchronization mechanism with the encapsulated task in order to prevent object's state corruption. A typical instance of an active object is an animation widget. The widget state changes with the time, while as an object it has all properties of a normal widget. The task Implement an active integrator object. The object has an input and output. The input can be set using the method Input. The input is a function of time. The output can be queried using the method Output. The object integrates its input over the time and the result becomes the object's output. So if the input is K(t) and the output is S, the object state S is changed to S + (K(t1) + K(t0)) * (t1 - t0) / 2, i.e. it integrates K using the trapeze method. Initially K is constant 0 and S is 0. In order to test the object: set its input to sin (2π f t), where the frequency f=0.5Hz. The phase is irrelevant. wait 2s set the input to constant 0 wait 0.5s Verify that now the object's output is approximately 0 (the sine has the period of 2s). The accuracy of the result will depend on the OS scheduler time slicing and the accuracy of the clock.
#Rust
Rust
#![feature(mpsc_select)]   extern crate num; extern crate schedule_recv;   use num::traits::Zero; use num::Float; use schedule_recv::periodic_ms; use std::f64::consts::PI; use std::ops::Mul; use std::sync::mpsc::{self, SendError, Sender}; use std::sync::{Arc, Mutex}; use std::thread; use std::time::Duration;   pub type Actor<S> = Sender<Box<Fn(u32) -> S + Send>>; pub type ActorResult<S> = Result<(), SendError<Box<Fn(u32) -> S + Send>>>;   /// Rust supports both shared-memory and actor models of concurrency, and the `Integrator` utilizes /// both. We use an `Actor` to send the `Integrator` new functions, while we use a `Mutex` /// (shared-memory concurrency) to hold the result of the integration. /// /// Note that these are not the only options here--there are many, many ways you can deal with /// concurrent access. But when in doubt, a plain old `Mutex` is often a good bet. For example, /// this might look like a good situation for a `RwLock`--after all, there's no reason for a read /// in the main task to block writes. Unfortunately, unless you have significantly more reads than /// writes (which is certainly not the case here), a `Mutex` will usually outperform a `RwLock`. pub struct Integrator<S: 'static, T: Send> { input: Actor<S>, output: Arc<Mutex<T>>, }   /// In Rust, time durations are strongly typed. This is usually exactly what you want, but for a /// problem like this--where the integrated value has unusual (unspecified?) units--it can actually /// be a bit tricky. Right now, `Duration`s can only be multiplied or divided by `i32`s, so in /// order to be able to actually do math with them we say that the type parameter `S` (the result /// of the function being integrated) must yield `T` (the type of the integrated value) when /// multiplied by `f64`. We could possibly replace `f64` with a generic as well, but it would make /// things a bit more complex. impl<S, T> Integrator<S, T> where S: Mul<f64, Output = T> + Float + Zero, T: 'static + Clone + Send + Float, { pub fn new(frequency: u32) -> Integrator<S, T> { // We create a pipe allowing functions to be sent from tx (the sending end) to input (the // receiving end). In order to change the function we are integrating from the task in // which the Integrator lives, we simply send the function through tx. let (tx, input) = mpsc::channel(); // The easiest way to do shared-memory concurrency in Rust is to use atomic reference // counting, or Arc, around a synchronized type (like Mutex<T>). Arc gives you a guarantee // that memory will not be freed as long as there is at least one reference to it. // It is similar to C++'s shared_ptr, but it is guaranteed to be safe and is never // incremented unless explicitly cloned (by default, it is moved). let s: Arc<Mutex<T>> = Arc::new(Mutex::new(Zero::zero())); let integrator = Integrator { input: tx, // Here is the aforementioned clone. We have to do it before s enters the closure, // because once that happens it is moved into the closure (and later, the new task) and // becomes inaccessible to the outside world. output: Arc::clone(&s), }; thread::spawn(move || -> () { // The frequency is how often we want to "tick" as we update our integrated total. In // Rust, timers can yield Receivers that are periodically notified with an empty // message (where the period is the frequency). This is useful because it lets us wait // on either a tick or another type of message (in this case, a request to change the // function we are integrating). let periodic = periodic_ms(frequency); let mut t = 0; let mut k: Box<Fn(u32) -> S + Send> = Box::new(|_| Zero::zero()); let mut k_0: S = Zero::zero(); loop { // Here's the selection we talked about above. Note that we are careful to call // the *non*-failing function, recv(), here. The reason we do this is because // recv() will return Err when the sending end of a channel is dropped. While // this is unlikely to happen for the timer (so again, you could argue for failure // there), it's normal behavior for the sending end of input to be dropped, since // it just happens when the Integrator falls out of scope. So we handle it cleanly // and break out of the loop, rather than failing. select! { res = periodic.recv() => match res { Ok(_) => { t += frequency; let k_1: S = k(t); // Rust Mutexes are a bit different from Mutexes in many other // languages, in that the protected data is actually encapsulated by // the Mutex. The reason for this is that Rust is actually capable of // enforcing (via its borrow checker) the invariant that the contents // of a Mutex may only be read when you have acquired its lock. This // is enforced by way of a MutexGuard, the return value of lock(), // which implements some special traits (Deref and DerefMut) that allow // access to the inner element "through" the guard. The element so // acquired has a lifetime bounded by that of the MutexGuard, the // MutexGuard can only be acquired by taking a lock, and the only way // to release the lock is by letting the MutexGuard fall out of scope, // so it's impossible to access the data incorrectly. There are some // additional subtleties around the actual implementation, but that's // the basic idea. let mut s = s.lock().unwrap(); *s = *s + (k_1 + k_0) * (f64::from(frequency) / 2.); k_0 = k_1; } Err(_) => break, }, res = input.recv() => match res { Ok(k_new) => k = k_new, Err(_) => break, } } } }); integrator }   pub fn input(&self, k: Box<Fn(u32) -> S + Send>) -> ActorResult<S> { // The meat of the work is done in the other thread, so to set the // input we just send along the Sender we set earlier... self.input.send(k) }   pub fn output(&self) -> T { // ...and to read the input, we simply acquire a lock on the output Mutex and return a // copy. Why do we have to copy it? Because, as mentioned above, Rust won't let us // retain access to the interior of the Mutex unless we have possession of its lock. There // are ways and circumstances in which one can avoid this (e.g. by using atomic types) but // a copy is a perfectly reasonable solution as well, and a lot easier to reason about :) *self.output.lock().unwrap() } }   /// This function is fairly straightforward. We create the integrator, set its input function k(t) /// to 2pi * f * t, and then wait as described in the Rosetta stone problem. fn integrate() -> f64 { let object = Integrator::new(10); object .input(Box::new(|t: u32| { let two_seconds_ms = 2 * 1000; let f = 1. / f64::from(two_seconds_ms); (2. * PI * f * f64::from(t)).sin() })) .expect("Failed to set input"); thread::sleep(Duration::from_secs(2)); object.input(Box::new(|_| 0.)).expect("Failed to set input"); thread::sleep(Duration::from_millis(500)); object.output() }   fn main() { println!("{}", integrate()); }   /// Will fail on a heavily loaded machine #[test] #[ignore] fn solution() { // We should just be able to call integrate, but can't represent the closure properly due to // rust-lang/rust issue #17060 if we make frequency or period a variable. // FIXME(pythonesque): When unboxed closures are fixed, fix integrate() to take two arguments. let object = Integrator::new(10); object .input(Box::new(|t: u32| { let two_seconds_ms = 2 * 1000; let f = 1. / (two_seconds_ms / 10) as f64; (2. * PI * f * t as f64).sin() })) .expect("Failed to set input"); thread::sleep(Duration::from_millis(200)); object.input(Box::new(|_| 0.)).expect("Failed to set input"); thread::sleep(Duration::from_millis(100)); assert_eq!(object.output() as u32, 0) }
http://rosettacode.org/wiki/Active_object
Active object
In object-oriented programming an object is active when its state depends on clock. Usually an active object encapsulates a task that updates the object's state. To the outer world the object looks like a normal object with methods that can be called from outside. Implementation of such methods must have a certain synchronization mechanism with the encapsulated task in order to prevent object's state corruption. A typical instance of an active object is an animation widget. The widget state changes with the time, while as an object it has all properties of a normal widget. The task Implement an active integrator object. The object has an input and output. The input can be set using the method Input. The input is a function of time. The output can be queried using the method Output. The object integrates its input over the time and the result becomes the object's output. So if the input is K(t) and the output is S, the object state S is changed to S + (K(t1) + K(t0)) * (t1 - t0) / 2, i.e. it integrates K using the trapeze method. Initially K is constant 0 and S is 0. In order to test the object: set its input to sin (2π f t), where the frequency f=0.5Hz. The phase is irrelevant. wait 2s set the input to constant 0 wait 0.5s Verify that now the object's output is approximately 0 (the sine has the period of 2s). The accuracy of the result will depend on the OS scheduler time slicing and the accuracy of the clock.
#Scala
Scala
object ActiveObject {   class Integrator {   import java.util._ import scala.actors.Actor._   case class Pulse(t: Double) case class Input(k: Double => Double) case object Output case object Bye   val timer = new Timer(true) var k: Double => Double = (_ => 0.0) var s: Double = 0.0 var t0: Double = 0.0   val handler = actor { loop { react { case Pulse(t1) => s += (k(t1) + k(t0)) * (t1 - t0) / 2.0; t0 = t1 case Input(k) => this.k = k case Output => reply(s) case Bye => timer.cancel; exit } } }   timer.scheduleAtFixedRate(new TimerTask { val start = System.currentTimeMillis def run { handler ! Pulse((System.currentTimeMillis - start) / 1000.0) } }, 0, 10) // send Pulse every 10 ms   def input(k: Double => Double) = handler ! Input(k) def output = handler !? Output def bye = handler ! Bye }   def main(args: Array[String]) { val integrator = new Integrator integrator.input(t => Math.sin(2.0 * Math.Pi * 0.5 * t)) Thread.sleep(2000) integrator.input(_ => 0.0) Thread.sleep(500) println(integrator.output) integrator.bye } }
http://rosettacode.org/wiki/Aliquot_sequence_classifications
Aliquot sequence classifications
An aliquot sequence of a positive integer K is defined recursively as the first member being K and subsequent members being the sum of the Proper divisors of the previous term. If the terms eventually reach 0 then the series for K is said to terminate. There are several classifications for non termination: If the second term is K then all future terms are also K and so the sequence repeats from the first term with period 1 and K is called perfect. If the third term would be repeating K then the sequence repeats with period 2 and K is called amicable. If the Nth term would be repeating K for the first time, with N > 3 then the sequence repeats with period N - 1 and K is called sociable. Perfect, amicable and sociable numbers eventually repeat the original number K; there are other repetitions... Some K have a sequence that eventually forms a periodic repetition of period 1 but of a number other than K, for example 95 which forms the sequence 95, 25, 6, 6, 6, ... such K are called aspiring. K that have a sequence that eventually forms a periodic repetition of period >= 2 but of a number other than K, for example 562 which forms the sequence 562, 284, 220, 284, 220, ... such K are called cyclic. And finally: Some K form aliquot sequences that are not known to be either terminating or periodic; these K are to be called non-terminating. For the purposes of this task, K is to be classed as non-terminating if it has not been otherwise classed after generating 16 terms or if any term of the sequence is greater than 2**47 = 140,737,488,355,328. Task Create routine(s) to generate the aliquot sequence of a positive integer enough to classify it according to the classifications given above. Use it to display the classification and sequences of the numbers one to ten inclusive. Use it to show the classification and sequences of the following integers, in order: 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, and optionally 15355717786080. Show all output on this page. Related tasks   Abundant, deficient and perfect number classifications. (Classifications from only the first two members of the whole sequence).   Proper divisors   Amicable pairs
#Ring
Ring
  # Project : Aliquot sequence classnifications   see "Rosetta Code - aliquot sequence classnifications" + nl while true see "enter an integer: " give k k=fabs(floor(number(k))) if k=0 exit ok printas(k) end see "program complete."   func printas(k) length=52 aseq = list(length) n=k classn=0 priorn = 0 inc = 0 for element=2 to length aseq[element]=pdtotal(n) see aseq[element] + " " + nl if aseq[element]=0 see " terminating" + nl classn=1 exit ok if aseq[element]=k and element=2 see " perfect" + nl classn=2 exit ok if aseq[element]=k and element=3 see " amicable" + nl classn=3 exit ok if aseq[element]=k and element>3 see " sociable" + nl classn=4 exit ok if aseq[element]!=k and aseq[element-1]=aseq[element] see " aspiring" + nl classn=5 exit ok if aseq[element]!=k and element>2 and aseq[element-2]= aseq[element] see " cyclic" + nl classn=6 exit ok n=aseq[element] if n>priorn priorn=n inc=inc+1 but n<=priorn inc=0 priorn=0 ok if inc=11 or n>30000000 exit ok next if classn=0 see " non-terminating" + nl ok   func pdtotal(n) pdtotal = 0 for y=2 to n if (n % y)=0 pdtotal=pdtotal+(n/y) ok next return pdtotal  
http://rosettacode.org/wiki/AKS_test_for_primes
AKS test for primes
The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles. The theorem on which the test is based can be stated as follows:   a number   p {\displaystyle p}   is prime   if and only if   all the coefficients of the polynomial expansion of ( x − 1 ) p − ( x p − 1 ) {\displaystyle (x-1)^{p}-(x^{p}-1)} are divisible by   p {\displaystyle p} . Example Using   p = 3 {\displaystyle p=3} : (x-1)^3 - (x^3 - 1) = (x^3 - 3x^2 + 3x - 1) - (x^3 - 1) = -3x^2 + 3x And all the coefficients are divisible by 3,   so 3 is prime. Note: This task is not the AKS primality test.   It is an inefficient exponential time algorithm discovered in the late 1600s and used as an introductory lemma in the AKS derivation. Task Create a function/subroutine/method that given   p {\displaystyle p}   generates the coefficients of the expanded polynomial representation of   ( x − 1 ) p {\displaystyle (x-1)^{p}} . Use the function to show here the polynomial expansions of   ( x − 1 ) p {\displaystyle (x-1)^{p}}   for   p {\displaystyle p}   in the range   0   to at least   7,   inclusive. Use the previous function in creating another function that when given   p {\displaystyle p}   returns whether   p {\displaystyle p}   is prime using the theorem. Use your test to generate a list of all primes under   35. As a stretch goal,   generate all primes under   50   (needs integers larger than 31-bit). References Agrawal-Kayal-Saxena (AKS) primality test (Wikipedia) Fool-Proof Test for Primes - Numberphile (Video). The accuracy of this video is disputed -- at best it is an oversimplification.
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
Print["powers of (x-1)"] (x - 1)^( Range[0, 7]) // Expand // TableForm Print["primes under 50"] poly[p_] := (x - 1)^p - (x^p - 1) // Expand; coefflist[p_Integer] := Coefficient[poly[p], x, #] & /@ Range[0, p - 1]; AKSPrimeQ[p_Integer] := (Mod[coefflist[p] , p] // Union) == {0}; Select[Range[1, 50], AKSPrimeQ]
http://rosettacode.org/wiki/Additive_primes
Additive primes
Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS entry:   A046704 additive primes.   the prime-numbers entry:   additive primes.   the geeks for geeks entry: additive prime number.   the prime-numbers fandom: additive primes.
#VTL-2
VTL-2
10 M=499 20 :1)=1 30 P=2 40 :P)=0 50 P=P+1 60 #=M>P*40 70 P=2 80 C=P*2 90 :C)=1 110 C=C+P 120 #=M>C*90 130 P=P+1 140 #=M/2>P*80 150 P=2 160 N=0 170 #=:P)*290 180 S=0 190 K=P 200 K=K/10 210 S=S+% 220 #=0<K*200 230 #=:S)*290 240 ?=P 250 $=9 260 N=N+1 270 #=N/10*0+%=0=0*290 280 ?="" 290 P=P+1 300 #=M>P*170 310 ?="" 320 ?="There are "; 330 ?=N 340 ?=" additive primes below "; 350 ?=M+1
http://rosettacode.org/wiki/Additive_primes
Additive primes
Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS entry:   A046704 additive primes.   the prime-numbers entry:   additive primes.   the geeks for geeks entry: additive prime number.   the prime-numbers fandom: additive primes.
#Wren
Wren
import "/math" for Int import "/fmt" for Fmt   var sumDigits = Fn.new { |n| var sum = 0 while (n > 0) { sum = sum + (n % 10) n = (n/10).floor } return sum }   System.print("Additive primes less than 500:") var primes = Int.primeSieve(499) var count = 0 for (p in primes) { if (Int.isPrime(sumDigits.call(p))) { count = count + 1 Fmt.write("$3d ", p) if (count % 10 == 0) System.print() } } System.print("\n\n%(count) additive primes found.")
http://rosettacode.org/wiki/Almost_prime
Almost prime
A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,   where   k = 2 {\displaystyle k=2} ,   are the   semiprimes. Task Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for   1 <= K <= 5 {\displaystyle 1<=K<=5} . Related tasks   Semiprime   Category:Prime Numbers
#Quackery
Quackery
[ stack ] is quantity ( --> s ) [ stack ] is factors ( --> s )   [ factors put quantity put [] 1 [ over size quantity share != while 1+ dup primefactors size factors share = if [ tuck join swap ] again ] drop factors release quantity release ] is almostprimes ( n n --> [ )   5 times [ 10 i^ 1+ dup echo sp almostprimes echo cr ]
http://rosettacode.org/wiki/Almost_prime
Almost prime
A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,   where   k = 2 {\displaystyle k=2} ,   are the   semiprimes. Task Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for   1 <= K <= 5 {\displaystyle 1<=K<=5} . Related tasks   Semiprime   Category:Prime Numbers
#R
R
#=============================================================== # Find k-Almost-primes # R implementation #=============================================================== #--------------------------------------------------------------- # Function for prime factorization from Rosetta Code #---------------------------------------------------------------   findfactors <- function(n) { d <- c() div <- 2; nxt <- 3; rest <- n while( rest != 1 ) { while( rest%%div == 0 ) { d <- c(d, div) rest <- floor(rest / div) } div <- nxt nxt <- nxt + 2 } d }   #--------------------------------------------------------------- # Find k-Almost-primes #---------------------------------------------------------------   almost_primes <- function(n = 10, k = 5) {   # Set up matrix for storing of the results   res <- matrix(NA, nrow = k, ncol = n) rownames(res) <- paste("k = ", 1:k, sep = "") colnames(res) <- rep("", n)   # Loop over k   for (i in 1:k) {   tmp <- 1   while (any(is.na(res[i, ]))) { # Keep looping if there are still missing entries in the result-matrix if (length(findfactors(tmp)) == i) { # Check number of factors res[i, which.max(is.na(res[i, ]))] <- tmp } tmp <- tmp + 1 } } print(res) }
http://rosettacode.org/wiki/Anagrams
Anagrams
When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in them. Related tasks Word plays Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams 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 Data.List   groupon f x y = f x == f y   main = do f <- readFile "./../Puzzels/Rosetta/unixdict.txt" let words = lines f wix = groupBy (groupon fst) . sort $ zip (map sort words) words mxl = maximum $ map length wix mapM_ (print . map snd) . filter ((==mxl).length) $ wix
http://rosettacode.org/wiki/Anonymous_recursion
Anonymous recursion
While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects,   and/or the function doesn't have the right arguments and/or return values. So we end up inventing some silly name like   foo2   or   foo_helper.   I have always found it painful to come up with a proper name, and see some disadvantages:   You have to think up a name, which then pollutes the namespace   Function is created which is called from nowhere else   The program flow in the source code is interrupted Some languages allow you to embed recursion directly in-place.   This might work via a label, a local gosub instruction, or some special keyword. Anonymous recursion can also be accomplished using the   Y combinator. Task If possible, demonstrate this by writing the recursive version of the fibonacci function   (see Fibonacci sequence)   which checks for a negative argument before doing the actual recursion.
#Scala
Scala
def Y[A, B](f: (A ⇒ B) ⇒ (A ⇒ B)): A ⇒ B = f(Y(f))(_)   def fib(n: Int): Option[Int] = if (n < 0) None else Some(Y[Int, Int](f ⇒ i ⇒ if (i < 2) 1 else f(i - 1) + f(i - 2))(n))   -2 to 5 map (n ⇒ (n, fib(n))) foreach println
http://rosettacode.org/wiki/Amicable_pairs
Amicable pairs
Two integers N {\displaystyle N} and M {\displaystyle M} are said to be amicable pairs if N ≠ M {\displaystyle N\neq M} and the sum of the proper divisors of N {\displaystyle N} ( s u m ( p r o p D i v s ( N ) ) {\displaystyle \mathrm {sum} (\mathrm {propDivs} (N))} ) = M {\displaystyle =M} as well as s u m ( p r o p D i v s ( M ) ) = N {\displaystyle \mathrm {sum} (\mathrm {propDivs} (M))=N} . Example 1184 and 1210 are an amicable pair, with proper divisors:   1, 2, 4, 8, 16, 32, 37, 74, 148, 296, 592   and   1, 2, 5, 10, 11, 22, 55, 110, 121, 242, 605   respectively. Task Calculate and show here the Amicable pairs below 20,000; (there are eight). Related tasks Proper divisors Abundant, deficient and perfect number classifications Aliquot sequence classifications and its amicable classification.
#REBOL
REBOL
;- based on Lua code ;-)   sum-of-divisors: func[n /local sum][ sum: 1 ; using `to-integer` for compatibility with Rebol2 for d 2 (to-integer square-root n) 1 [ if 0 = remainder n d [ sum: n / d + sum + d ] ] sum ]   for n 2 20000 1 [ if n < m: sum-of-divisors n [ if n = sum-of-divisors m [ print [n tab m] ] ] ]
http://rosettacode.org/wiki/Amb
Amb
Define and give an example of the Amb operator. The Amb operator (short for "ambiguous") expresses nondeterminism. This doesn't refer to randomness (as in "nondeterministic universe") but is closely related to the term as it is used in automata theory ("non-deterministic finite automaton"). The Amb operator takes a variable number of expressions (or values if that's simpler in the language) and yields a correct one which will satisfy a constraint in some future computation, thereby avoiding failure. Problems whose solution the Amb operator naturally expresses can be approached with other tools, such as explicit nested iterations over data sets, or with pattern matching. By contrast, the Amb operator appears integrated into the language. Invocations of Amb are not wrapped in any visible loops or other search patterns; they appear to be independent. Essentially Amb(x, y, z) splits the computation into three possible futures: a future in which the value x is yielded, a future in which the value y is yielded and a future in which the value z is yielded. The future which leads to a successful subsequent computation is chosen. The other "parallel universes" somehow go away. Amb called with no arguments fails. For simplicity, one of the domain values usable with Amb may denote failure, if that is convenient. For instance, it is convenient if a Boolean false denotes failure, so that Amb(false) fails, and thus constraints can be expressed using Boolean expressions like Amb(x * y == 8) which unless x and y add to four. A pseudo-code program which satisfies this constraint might look like: let x = Amb(1, 2, 3) let y = Amb(7, 6, 4, 5) Amb(x * y = 8) print x, y The output is 2 4 because Amb(1, 2, 3) correctly chooses the future in which x has value 2, Amb(7, 6, 4, 5) chooses 4 and consequently Amb(x * y = 8) produces a success. Alternatively, failure could be represented using strictly Amb(): unless x * y = 8 do Amb() Or else Amb could take the form of two operators or functions: one for producing values and one for enforcing constraints: let x = Ambsel(1, 2, 3) let y = Ambsel(4, 5, 6) Ambassert(x * y = 8) print x, y where Ambassert behaves like Amb() if the Boolean expression is false, otherwise it allows the future computation to take place, without yielding any value. The task is to somehow implement Amb, and demonstrate it with a program which chooses one word from each of the following four sets of character strings to generate a four-word sentence: "the" "that" "a" "frog" "elephant" "thing" "walked" "treaded" "grows" "slowly" "quickly" The constraint to be satisfied is that the last character of each word (other than the last) is the same as the first character of its successor. The only successful sentence is "that thing grows slowly"; other combinations do not satisfy the constraint and thus fail. The goal of this task isn't to simply process the four lists of words with explicit, deterministic program flow such as nested iteration, to trivially demonstrate the correct output. The goal is to implement the Amb operator, or a facsimile thereof that is possible within the language limitations.
#PL.2FI
PL/I
*process or(!) source attributes xref; amb: Proc Options(main); /********************************************************************* * 25.08.2013 Walter Pachl *********************************************************************/ Dcl w(4,10) Char(40) Var Init('the','that','a','if',(6)(1)' ', 'frog','elephant','thing',(7)(1)' ', 'walked','treaded','grows','trots',(6)(1)' ', 'slowly','quickly',(8)(1)' '); Dcl ns Char(40) Var; Dcl (i,k,j,ii,jj,m,n) Bin Fixed(31); n=hbound(w,1); /* number of sets */ m=hbound(w,2); /* max number of words in set */ Call show; /* show the input */ Do i=1 To n-1; /* loop over sets */ k=i+1; /* the following set */ Do ii=1 To m; /* loop over elements in set k*/ If words(w(i,ii))=i Then Do; /* a sentence part found */ Do jj=1 To m; /* loop over following words */ If right(w(i,ii),1)=left(w(k,jj),1) Then Do; /* fitting */ ns=w(i,ii)!!' '!!w(k,jj); /* build new sentence (part) */ If words(ns)=k Then /* 'complete' part */ Call add(k,ns); /* add to set k */ End; End; End; End; Do jj=1 To m; /* show the results */ If words(w(4,jj))=4 Then put edit('--> ',w(4,jj))(Skip,a,a); End;   add: Proc(ni,s); /********************************************************************* * add a sentence (part) to set ni *********************************************************************/ Dcl (i,ni) Bin Fixed(31); Dcl s Char(40) Var; Do i=1 To m While(w(ni,i)>''); /* look for an empty slot */ End; w(ni,i)=s; /* add the sentence (part) */ End;   words: Proc(s) Returns(Bin Fixed(31)); /********************************************************************* * return the number of blank separated words in s *********************************************************************/ Dcl s Char(40) Var; Dcl nw Bin Fixed(31) Init(0); Dcl i Bin Fixed(31) Init(1); If s>'' Then Do; nw=1; Do i=1 To length(s); If substr(s,i,1)=' ' Then nw+=1; End; End; Return(nw); End;   show: Proc; /********************************************************************* * show the input sets *********************************************************************/ Dcl (i,j,mm) Bin Fixed(31) Init(0); Dcl l(4) Bin Fixed(31) Init((4)0); Do i=1 To n; Do j=1 To m; If w(i,j)>'' Then Do; mm=max(mm,j); /* max number of words in any set */ l(i)=max(l(i),length(w(i,j))); /* max word length in set i */ End; End; End; Put Edit('Input:')(Skip,a); Do j=1 To mm; /* output lines */ Put Skip; Do i=1 To n; Put Edit(w(i,j),' ')(a(l(i)),a); End; End; Put Skip; End;   End;
http://rosettacode.org/wiki/Accumulator_factory
Accumulator factory
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created). Rules The detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in small italic text). Before you submit an example, make sure the function Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i). Although these exact function and parameter names need not be used Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) (i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that) Generates functions that return the sum of every number ever passed to them, not just the most recent. (This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.) Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. (Follow your language's conventions here.) Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. (No global variables or other such things.) E.g. if after the example, you added the following code (in a made-up language) where the factory function is called foo: x = foo(1); x(5); foo(3); print x(2.3); It should print 8.3. (There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.) Task Create a function that implements the described rules. It need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them. Where it is not possible to hold exactly to the constraints above, describe the deviations.
#Julia
Julia
function accumulator(i) f(n) = i += n return f end   x = accumulator(1) @show x(5)   accumulator(3) @show x(2.3)
http://rosettacode.org/wiki/Accumulator_factory
Accumulator factory
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created). Rules The detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in small italic text). Before you submit an example, make sure the function Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i). Although these exact function and parameter names need not be used Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) (i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that) Generates functions that return the sum of every number ever passed to them, not just the most recent. (This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.) Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. (Follow your language's conventions here.) Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. (No global variables or other such things.) E.g. if after the example, you added the following code (in a made-up language) where the factory function is called foo: x = foo(1); x(5); foo(3); print x(2.3); It should print 8.3. (There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.) Task Create a function that implements the described rules. It need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them. Where it is not possible to hold exactly to the constraints above, describe the deviations.
#Kotlin
Kotlin
// version 1.1   fun foo(n: Double): (d: Double) -> Double { var nn = n return { nn += it; nn } }   fun foo(n: Int): (i: Int) -> Int { var nn = n return { nn += it; nn } }   fun main(args: Array<String>) { val x = foo(1.0) // calls 'Double' overload x(5.0) foo(3.0) println(x(2.3)) val y = foo(1) // calls 'Int' overload y(5) foo(5) println(y(2)) }
http://rosettacode.org/wiki/Ackermann_function
Ackermann function
The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { n + 1 if  m = 0 A ( m − 1 , 1 ) if  m > 0  and  n = 0 A ( m − 1 , A ( m , n − 1 ) ) if  m > 0  and  n > 0. {\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}} Its arguments are never negative and it always terminates. Task Write a function which returns the value of A ( m , n ) {\displaystyle A(m,n)} . Arbitrary precision is preferred (since the function grows so quickly), but not required. See also Conway chained arrow notation for the Ackermann function.
#AutoHotkey
AutoHotkey
A(m, n) { If (m > 0) && (n = 0) Return A(m-1,1) Else If (m > 0) && (n > 0) Return A(m-1,A(m, n-1)) Else If (m=0) Return n+1 }   ; Example: MsgBox, % "A(1,2) = " A(1,2)
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications
Abundant, deficient and perfect number classifications
These define three classifications of positive integers based on their   proper divisors. Let   P(n)   be the sum of the proper divisors of   n   where the proper divisors are all positive divisors of   n   other than   n   itself. if P(n) < n then n is classed as deficient (OEIS A005100). if P(n) == n then n is classed as perfect (OEIS A000396). if P(n) > n then n is classed as abundant (OEIS A005101). Example 6   has proper divisors of   1,   2,   and   3. 1 + 2 + 3 = 6,   so   6   is classed as a perfect number. Task Calculate how many of the integers   1   to   20,000   (inclusive) are in each of the three classes. Show the results here. Related tasks   Aliquot sequence classifications.   (The whole series from which this task is a subset.)   Proper divisors   Amicable pairs
#Common_Lisp
Common Lisp
(defun number-class (n) (let ((divisor-sum (sum-divisors n))) (cond ((< divisor-sum n) :deficient) ((= divisor-sum n) :perfect) ((> divisor-sum n) :abundant))))   (defun sum-divisors (n) (loop :for i :from 1 :to (/ n 2) :when (zerop (mod n i)) :sum i))   (defun classification () (loop :for n :from 1 :to 20000 :for class := (number-class n) :count (eq class :deficient) :into deficient :count (eq class :perfect) :into perfect :count (eq class :abundant) :into abundant :finally (return (values deficient perfect abundant))))
http://rosettacode.org/wiki/Align_columns
Align columns
Given a text file of many lines, where fields within a line are delineated by a single 'dollar' character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be either left justified, right justified, or center justified within its column. Use the following text to test your programs: Given$a$text$file$of$many$lines,$where$fields$within$a$line$ are$delineated$by$a$single$'dollar'$character,$write$a$program that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$ column$are$separated$by$at$least$one$space. Further,$allow$for$each$word$in$a$column$to$be$either$left$ justified,$right$justified,$or$center$justified$within$its$column. Note that:   The example input texts lines may, or may not, have trailing dollar characters.   All columns should share the same alignment.   Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.   Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.   The minimum space between columns should be computed from the text and not hard-coded.   It is not a requirement to add separating characters between or around columns. 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
#E
E
pragma.enable("accumulator")   def left(width, word) { return word + " " * (width - word.size()) }   def center(width, word) { def leftCount := (width - word.size()) // 2 return " " * leftCount + word + " " * (width - word.size() - leftCount) }   def right(width, word) { return " " * (width - word.size()) + word }   def alignColumns(align, text) { def split := accum [] for line in text.split("\n") { _.with(line.split("$")) } var widths := [] for line in split { for i => word in line { widths with= (i, widths.fetch(i, fn{0}).max(word.size())) } } return accum "" for line in split { _ + accum "" for i => word in line { _ + align(widths[i] + 1, word) } + "\n" } }
http://rosettacode.org/wiki/Active_object
Active object
In object-oriented programming an object is active when its state depends on clock. Usually an active object encapsulates a task that updates the object's state. To the outer world the object looks like a normal object with methods that can be called from outside. Implementation of such methods must have a certain synchronization mechanism with the encapsulated task in order to prevent object's state corruption. A typical instance of an active object is an animation widget. The widget state changes with the time, while as an object it has all properties of a normal widget. The task Implement an active integrator object. The object has an input and output. The input can be set using the method Input. The input is a function of time. The output can be queried using the method Output. The object integrates its input over the time and the result becomes the object's output. So if the input is K(t) and the output is S, the object state S is changed to S + (K(t1) + K(t0)) * (t1 - t0) / 2, i.e. it integrates K using the trapeze method. Initially K is constant 0 and S is 0. In order to test the object: set its input to sin (2π f t), where the frequency f=0.5Hz. The phase is irrelevant. wait 2s set the input to constant 0 wait 0.5s Verify that now the object's output is approximately 0 (the sine has the period of 2s). The accuracy of the result will depend on the OS scheduler time slicing and the accuracy of the clock.
#Smalltalk
Smalltalk
  Object subclass:#Integrator instanceVariableNames:'tickRate input s thread' classVariableNames:'' poolDictionaries:'' category:'Rosetta'   instance methods:   input:aFunctionOfT input := aFunctionOfT.   startWithTickRate:r "setup and start sampling" tickRate := r. s := 0. thread := [ self integrateLoop ] fork.   stop "stop and return the 'final' output" thread terminate. ^ s   integrateLoop "no need for any locks - the assignment to s is atomic in Smallalk; its either done or not, when terminated, so who cares"   |tBegin tPrev tNow kPrev kNow deltaT delta|   tBegin := tPrev := Timestamp nowWithMilliseconds. kPrev := input value:0.   [true] whileTrue:[ Delay waitForSeconds: tickRate. tNow := Timestamp nowWithMilliseconds. kNow := input value:(tNow millisecondDeltaFrom:tBegin) / 1000.   deltaT := (tNow millisecondDeltaFrom:tPrev) / 1000. delta := (kPrev + kNow) * deltaT / 2.   s := s + delta. tPrev := tNow. kPrev := kNow. ].   class methods:   example #( 0.5 0.1 0.05 0.01 0.005 0.001 0.0005 ) do:[:sampleRate | |i|   i := Integrator new. i input:[:t | (2 * Float pi * 0.5 * t) sin]. i startWithTickRate:sampleRate.   Delay waitForSeconds:2. i input:[:t | 0]. Delay waitForSeconds:0.5.   Transcript show:'Sample rate: '; showCR:sampleRate; showCR:(i stop). ].  
http://rosettacode.org/wiki/Aliquot_sequence_classifications
Aliquot sequence classifications
An aliquot sequence of a positive integer K is defined recursively as the first member being K and subsequent members being the sum of the Proper divisors of the previous term. If the terms eventually reach 0 then the series for K is said to terminate. There are several classifications for non termination: If the second term is K then all future terms are also K and so the sequence repeats from the first term with period 1 and K is called perfect. If the third term would be repeating K then the sequence repeats with period 2 and K is called amicable. If the Nth term would be repeating K for the first time, with N > 3 then the sequence repeats with period N - 1 and K is called sociable. Perfect, amicable and sociable numbers eventually repeat the original number K; there are other repetitions... Some K have a sequence that eventually forms a periodic repetition of period 1 but of a number other than K, for example 95 which forms the sequence 95, 25, 6, 6, 6, ... such K are called aspiring. K that have a sequence that eventually forms a periodic repetition of period >= 2 but of a number other than K, for example 562 which forms the sequence 562, 284, 220, 284, 220, ... such K are called cyclic. And finally: Some K form aliquot sequences that are not known to be either terminating or periodic; these K are to be called non-terminating. For the purposes of this task, K is to be classed as non-terminating if it has not been otherwise classed after generating 16 terms or if any term of the sequence is greater than 2**47 = 140,737,488,355,328. Task Create routine(s) to generate the aliquot sequence of a positive integer enough to classify it according to the classifications given above. Use it to display the classification and sequences of the numbers one to ten inclusive. Use it to show the classification and sequences of the following integers, in order: 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, and optionally 15355717786080. Show all output on this page. Related tasks   Abundant, deficient and perfect number classifications. (Classifications from only the first two members of the whole sequence).   Proper divisors   Amicable pairs
#Ruby
Ruby
def aliquot(n, maxlen=16, maxterm=2**47) return "terminating", [0] if n == 0 s = [] while (s << n).size <= maxlen and n < maxterm n = n.proper_divisors.inject(0, :+) if s.include?(n) case n when s[0] case s.size when 1 then return "perfect", s when 2 then return "amicable", s else return "sociable of length #{s.size}", s end when s[-1] then return "aspiring", s else return "cyclic back to #{n}", s end elsif n == 0 then return "terminating", s << 0 end end return "non-terminating", s end   for n in 1..10 puts "%20s: %p" % aliquot(n) end puts for n in [11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, 15355717786080] puts "%20s: %p" % aliquot(n) end
http://rosettacode.org/wiki/AKS_test_for_primes
AKS test for primes
The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles. The theorem on which the test is based can be stated as follows:   a number   p {\displaystyle p}   is prime   if and only if   all the coefficients of the polynomial expansion of ( x − 1 ) p − ( x p − 1 ) {\displaystyle (x-1)^{p}-(x^{p}-1)} are divisible by   p {\displaystyle p} . Example Using   p = 3 {\displaystyle p=3} : (x-1)^3 - (x^3 - 1) = (x^3 - 3x^2 + 3x - 1) - (x^3 - 1) = -3x^2 + 3x And all the coefficients are divisible by 3,   so 3 is prime. Note: This task is not the AKS primality test.   It is an inefficient exponential time algorithm discovered in the late 1600s and used as an introductory lemma in the AKS derivation. Task Create a function/subroutine/method that given   p {\displaystyle p}   generates the coefficients of the expanded polynomial representation of   ( x − 1 ) p {\displaystyle (x-1)^{p}} . Use the function to show here the polynomial expansions of   ( x − 1 ) p {\displaystyle (x-1)^{p}}   for   p {\displaystyle p}   in the range   0   to at least   7,   inclusive. Use the previous function in creating another function that when given   p {\displaystyle p}   returns whether   p {\displaystyle p}   is prime using the theorem. Use your test to generate a list of all primes under   35. As a stretch goal,   generate all primes under   50   (needs integers larger than 31-bit). References Agrawal-Kayal-Saxena (AKS) primality test (Wikipedia) Fool-Proof Test for Primes - Numberphile (Video). The accuracy of this video is disputed -- at best it is an oversimplification.
#Nim
Nim
  from math import binom import strutils   # Table of unicode superscript characters. const Exponents: array[0..9, string] = ["⁰", "¹", "²", "³", "⁴", "⁵", "⁶", "⁷", "⁸", "⁹"]   iterator coeffs(n: int): int = ## Yield the coefficients of the expansion of (x - 1)ⁿ. var sign = 1 for k in 0..n: yield binom(n, k) * sign sign = -sign   iterator polyExpansion(n: int): tuple[c, e: int] = ## Yield the coefficients and the exponents of the expansion of (x - 1)ⁿ. var e = n for c in coeffs(n): yield(c, e) dec e   proc termString(c, e: int): string = ## Return the string for the term c * e^n. if e == 0: result.addInt(c) else: if c != 1: result.addInt(c) result.add('x') if e != 1: result.add(Exponents[e])   proc polyString(n: int): string = ## Return the string for the expansion of (x - 1)ⁿ. for (c, e) in polyExpansion(n): if c < 0: result.add(" - ") elif e != n: result.add(" + ") result.add(termString(abs(c), e))   proc isPrime(n: int): bool = ## Check if a number is prime using the polynome expansion. result = true for (c, e) in polyExpansion(n): if e in 1..(n-1): # xⁿ and 1 are eliminated by the subtraction. if c mod n != 0: return false   #---------------------------------------------------------------------------------------------------   echo "Polynome expansions:" for p in 0..9: echo "(x - 1)$1 = $2".format(Exponents[p], polyString(p))   var primes: string for p in 2..34: if p.isPrime(): primes.addSep(", ", 0) primes.addInt(p) echo "\nPrimes under 35: ", primes   for p in 35..50: if p.isPrime(): primes.add(", ") primes.addInt(p) echo "\nPrimes under 50: ", primes  
http://rosettacode.org/wiki/Additive_primes
Additive primes
Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS entry:   A046704 additive primes.   the prime-numbers entry:   additive primes.   the geeks for geeks entry: additive prime number.   the prime-numbers fandom: additive primes.
#XPL0
XPL0
func IsPrime(N); \Return 'true' if N is a prime number int N, I; [if N <= 1 then return false; for I:= 2 to sqrt(N) do if rem(N/I) = 0 then return false; return true; ];   func SumDigits(N); \Return the sum of the digits in N int N, Sum; [Sum:= 0; repeat N:= N/10; Sum:= Sum + rem(0); until N=0; return Sum; ];   int Count, N; [Count:= 0; for N:= 0 to 500-1 do if IsPrime(N) & IsPrime(SumDigits(N)) then [IntOut(0, N); Count:= Count+1; if rem(Count/10) = 0 then CrLf(0) else ChOut(0, 9\tab\); ]; CrLf(0); IntOut(0, Count); Text(0, " additive primes found below 500. "); ]
http://rosettacode.org/wiki/Additive_primes
Additive primes
Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS entry:   A046704 additive primes.   the prime-numbers entry:   additive primes.   the geeks for geeks entry: additive prime number.   the prime-numbers fandom: additive primes.
#Yabasic
Yabasic
// Rosetta Code problem: http://rosettacode.org/wiki/Additive_primes // by Galileo, 06/2022   limit = 500   dim flags(limit)   for i = 2 to limit for k = i*i to limit step i flags(k) = 1 next if flags(i) = 0 primes$ = primes$ + str$(i) + " " next   dim prim$(1)   n = token(primes$, prim$())   for i = 1 to n sum = 0 num$ = prim$(i) for j = 1 to len(num$) sum = sum + val(mid$(num$, j, 1)) next if instr(primes$, str$(sum) + " ") print prim$(i), " "; : count = count + 1 next   print "\nFound: ", count
http://rosettacode.org/wiki/Almost_prime
Almost prime
A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,   where   k = 2 {\displaystyle k=2} ,   are the   semiprimes. Task Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for   1 <= K <= 5 {\displaystyle 1<=K<=5} . Related tasks   Semiprime   Category:Prime Numbers
#Racket
Racket
#lang racket (require (only-in math/number-theory factorize))   (define ((k-almost-prime? k) n) (= k (for/sum ((f (factorize n))) (cadr f))))   (define KAP-table-values (for/list ((k (in-range 1 (add1 5)))) (define kap? (k-almost-prime? k)) (for/list ((j (in-range 10)) (i (sequence-filter kap? (in-naturals 1)))) i)))   (define (format-table t) (define longest-number-length (add1 (order-of-magnitude (argmax order-of-magnitude (cons (length t) (apply append t)))))) (define (fmt-val v) (~a v #:width longest-number-length #:align 'right)) (string-join (for/list ((r t) (k (in-naturals 1))) (string-append (format "║ k = ~a║ " (fmt-val k)) (string-join (for/list ((c r)) (fmt-val c)) "| ") "║")) "\n"))   (displayln (format-table KAP-table-values))
http://rosettacode.org/wiki/Almost_prime
Almost prime
A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,   where   k = 2 {\displaystyle k=2} ,   are the   semiprimes. Task Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for   1 <= K <= 5 {\displaystyle 1<=K<=5} . Related tasks   Semiprime   Category:Prime Numbers
#Raku
Raku
sub is-k-almost-prime($n is copy, $k) returns Bool { loop (my ($p, $f) = 2, 0; $f < $k && $p*$p <= $n; $p++) { $n /= $p, $f++ while $n %% $p; } $f + ($n > 1) == $k; }   for 1 .. 5 -> $k { say ~.[^10] given grep { is-k-almost-prime($_, $k) }, 2 .. * }
http://rosettacode.org/wiki/Anagrams
Anagrams
When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in them. Related tasks Word plays Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams 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
procedure main(args) every writeSet(!getLongestAnagramSets()) end   procedure getLongestAnagramSets() wordSets := table() longestWSet := 0 longSets := set()   every word := !&input do { wChars := csort(word) /wordSets[wChars] := set() insert(wordSets[wChars], word)   if 1 < *wordSets[wChars} == longestWSet then insert(longSets, wordSets[wChars]) if 1 < *wordSets[wChars} > longestWSet then { longestWSet := *wordSets[wChars} longSets := set([wordSets[wChars]]) } }   return longSets end   procedure writeSet(words) every writes("\t"|!words," ") write() end   procedure csort(w) every (s := "") ||:= (find(c := !cset(w),w),c) return s end
http://rosettacode.org/wiki/Anonymous_recursion
Anonymous recursion
While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects,   and/or the function doesn't have the right arguments and/or return values. So we end up inventing some silly name like   foo2   or   foo_helper.   I have always found it painful to come up with a proper name, and see some disadvantages:   You have to think up a name, which then pollutes the namespace   Function is created which is called from nowhere else   The program flow in the source code is interrupted Some languages allow you to embed recursion directly in-place.   This might work via a label, a local gosub instruction, or some special keyword. Anonymous recursion can also be accomplished using the   Y combinator. Task If possible, demonstrate this by writing the recursive version of the fibonacci function   (see Fibonacci sequence)   which checks for a negative argument before doing the actual recursion.
#Scheme
Scheme
(define (fibonacci n) (if (> 0 n) "Error: argument must not be negative." (let aux ((a 1) (b 0) (count n)) (if (= count 0) b (aux (+ a b) a (- count 1))))))   (map fibonacci '(1 2 3 4 5 6 7 8 9 10))