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 ...
#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)...
#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($"Ab...
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, o...
#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 ...
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 sync...
#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) ...
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 s...
#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); " :"; PrintAliquotClassifie...
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 ...
#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...
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.   ...
#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 "" ...
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.   ...
#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 {\displaystyl...
#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...
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 {\displaystyl...
#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++. ...
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 ...
#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 ...
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. ...
#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 uni...
#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();...
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 f...
#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 ...
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 ...
#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 ]...
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 *...
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 v...
#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([["t...
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 accumulat...
#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 ...
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 accumulat...
#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) ...
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 ...
#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)...
#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 , perf...
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, o...
#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] = to...
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 sync...
#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) ...
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 sync...
#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\T...
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 s...
#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)]))))   ;; initial...
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 ...
#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...
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.   ...
#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) { ...
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 {\displaystyl...
#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 ...
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 ...
#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)); ...
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 f...
#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 ...
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 ...
#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, ...
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 v...
#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; exi...
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 accumulat...
#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 accumulat...
#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 ...
#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...
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)...
#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...
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, o...
#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 ...
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 sync...
#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 ...
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 s...
#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) { 'aspi...
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 ...
#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; " ...
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.   ...
#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...
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.   ...
#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); ...
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.   ...
#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 {\displaystyl...
#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...
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 {\displaystyl...
#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   De...
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 ...
#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 != ...
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 f...
#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 ...
#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)) ...
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 ...
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 v...
#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 i...
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 accumulat...
#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...
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 ...
#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)...
#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...
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, o...
#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$separat...
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 sync...
#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...
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 sync...
#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; ...
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 s...
#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 1...
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 ...
#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 ...
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.   ...
#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...
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.   ...
#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 =...
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.   ...
#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 ==...
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 {\displaystyl...
#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...
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 ...
#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{...
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 f...
#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 { ...
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 ...
#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 G...
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 v...
#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...
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 v...
#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 @W...
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 accumulat...
#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 accumulat...
#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...
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 ...
#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)...
#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 p...
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, o...
#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$colum...
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 sync...
#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...
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 sync...
#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 ...
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 s...
#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)...
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 ...
#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.   ...
#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 ?=...
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.   ...
#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.isP...
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 {\displaystyl...
#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 ...
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 {\displaystyl...
#R
R
#=============================================================== # Find k-Almost-primes # R implementation #=============================================================== #--------------------------------------------------------------- # Function for prime factorization from Rosetta Code #-----------------------------...
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 ...
#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 f...
#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 ...
#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-d...
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 v...
#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...
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 accumulat...
#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 accumulat...
#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)) va...
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 ...
#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)...
#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...
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, o...
#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()) + wor...
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 sync...
#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 := ...
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 s...
#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...
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 ...
#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)...
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.   ...
#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...
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.   ...
#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 ...
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 {\displaystyl...
#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 ...
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 {\displaystyl...
#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 ...
#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)   ...
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 f...
#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))