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/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 ...
#ReScript
ReScript
let isqrt = (v) => { Belt.Float.toInt( sqrt(Belt.Int.toFloat(v))) }   let sum_divs = (n) => { let sum = ref(1) for d in 2 to isqrt(n) { if mod(n, d) == 0 { sum.contents = sum.contents + (n / d + d) } } sum.contents }   { for n in 2 to 20000 { let m = sum_divs(n) if (m > n) { ...
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...
#Prolog
Prolog
amb(E, [E|_]). amb(E, [_|ES]) :- amb(E, ES).   joins(Left, Right) :- append(_, [T], Left), append([R], _, Right), ( T \= R -> amb(_, []) % (explicitly using amb fail as required) ; true ).   amb_example([Word1, Word2, Word3, Word4]) :- amb(Word1, ["the","that","a"]), amb(Word2, ["frog","elephant","thing"])...
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...
#Lambdatalk
Lambdatalk
  {def acc {lambda {:a :n} {+ {A.toS {A.addlast! :n :a}}}}} -> acc   1) using a global:   {def A {A.new 1}} -> A {acc {A} 5} -> 6 {acc {A} 2.3} -> 8.3   2) inside a local context:   {let { {:a {A.new 1}} } {br}{acc :a 5} {br}{acc :a 2.3} } -> 6 8.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...
#LFE
LFE
  (defun accum (m) (lambda (n) (let ((sum (+ m n))) `(#(func ,(accum sum)) #(sum ,sum)))))  
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 ...
#AutoIt
AutoIt
Func Ackermann($m, $n) If ($m = 0) Then Return $n+1 Else If ($n = 0) Then Return Ackermann($m-1, 1) Else return Ackermann($m-1, Ackermann($m, $n-1)) EndIf EndIf EndFunc
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)...
#Cowgol
Cowgol
include "cowgol.coh";   const MAXIMUM := 20000;   var p: uint16[MAXIMUM+1]; var i: uint16; var j: uint16;   MemZero(&p as [uint8], @bytesof p); i := 1; while i <= MAXIMUM/2 loop j := i+i; while j <= MAXIMUM loop p[j] := p[j]+i; j := j+i; end loop; i := i+1; end loop;   var def: uint16 :=...
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...
#Elixir
Elixir
defmodule Align do def columns(text, alignment) do fieldsbyrow = String.split(text, "\n", trim: true) |> Enum.map(fn row -> String.split(row, "$", trim: true) end) maxfields = Enum.map(fieldsbyrow, fn field -> length(field) end) |> Enum.max colwidths = Enum.map(fieldsbyrow, fn field -> f...
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...
#SuperCollider
SuperCollider
  ( a = TaskProxy { |envir| envir.use { ~integral = 0; ~time = 0; ~prev = 0; ~running = true; loop { ~val = ~input.(~time); ~integral = ~integral + (~val + ~prev * ~dt / 2); ~prev = ~val; ~time = ~time + ~dt; ~dt.wait; } } }; )   // run the test ( fork { a.set(\dt, 0.0001); a.set(\input,...
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...
#Swift
Swift
// For NSObject, NSTimeInterval and NSThread import Foundation // For PI and sin import Darwin   class ActiveObject:NSObject {   let sampling = 0.1 var K: (t: NSTimeInterval) -> Double var S: Double var t0, t1: NSTimeInterval var thread = NSThread()   func integrateK() { t0 = t1 ...
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...
#Rust
Rust
#[derive(Debug)] enum AliquotType { Terminating, Perfect, Amicable, Sociable, Aspiring, Cyclic, NonTerminating }   fn classify_aliquot(num: i64) -> (AliquotType, Vec<i64>) { let limit = 1i64 << 47; //140737488355328 let mut terms = Some(num).into_iter().collect::<Vec<_>>(); for i in 0..16 { let n = ...
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 ...
#Objeck
Objeck
class AksTest { @c : static : Int[];   function : Main(args : String[]) ~ Nil { @c := Int->New[100];   for(n := 0; n < 10; n++;) { Coef(n); "(x-1)^ {$n} = "->Print(); Show(n); '\n'->Print(); };   "\nPrimes:"->PrintLine(); for(n := 2; n <= 63; n++;) { if(IsPrime(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...
#REXX
REXX
/*REXX program computes and displays the first N K─almost primes from 1 ──► K. */ parse arg N K . /*get optional arguments from the C.L. */ if N=='' | N=="," then N=10 /*N not specified? Then use default.*/ if K=='' | K=="," then K= 5 ...
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 ...
#J
J
(#~ a: ~: {:"1) (]/.~ /:~&>) <;._2 ] 1!:1 <'unixdict.txt' +-----+-----+-----+-----+-----+ |abel |able |bale |bela |elba | +-----+-----+-----+-----+-----+ |alger|glare|lager|large|regal| +-----+-----+-----+-----+-----+ |angel|angle|galen|glean|lange| +-----+-----+-----+-----+-----+ |caret|carte|cater|crate|trace| +--...
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...
#Seed7
Seed7
$ include "seed7_05.s7i";   const func integer: fib (in integer: x) is func result var integer: fib is 0; local const func integer: fib1 (in integer: n) is func result var integer: fib1 is 0; begin if n < 2 then fib1 := n; else fib1 := fib1(n-2) + fib1...
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 ...
#REXX
REXX
  /*REXX*/   Call time 'R' Do x=1 To 20000 pd=proper_divisors(x) sumpd.x=sum(pd) End Say 'sum(pd) computed in' time('E') 'seconds' Call time 'R' Do x=1 To 20000 /* If x//1000=0 Then Say x time() */ Do y=x+1 To 20000 If y=sumpd.x &, x=sumpd.y Then Say x y 'found after' time('E') 'seconds' En...
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...
#PureBasic
PureBasic
Procedure Words_Ok(String1.s, String2.s) If Mid(String1,Len(String1),1)=Mid(String2,1,1) ProcedureReturn #True EndIf ProcedureReturn #False EndProcedure   Procedure.s Amb(Array A.s(1), Array B.s(1), Array C.s(1), Array D.s(1)) Protected a, b, c, d For a=0 To ArraySize(A()) For b=0 To ArraySize(B()) ...
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...
#Lua
Lua
function acc(init) init = init or 0 return function(delta) init = init + (delta or 0) return init 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 accumulat...
#M2000_Interpreter
M2000 Interpreter
\\ M2000 Interpreter \\ accumulator factory foo=lambda acc=0 (n as double=0) -> { \\ interpreter place this: read n as double=0 as first line of lambda function if n=0 then =acc : exit acc+=n \\ acc passed as a closuer to lambda (a copy of acc in the result lambda function) =lambda acc ->...
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 ...
#AWK
AWK
function ackermann(m, n) { if ( m == 0 ) { return n+1 } if ( n == 0 ) { return ackermann(m-1, 1) } return ackermann(m-1, ackermann(m, n-1)) }   BEGIN { for(n=0; n < 7; n++) { for(m=0; m < 4; m++) { print "A(" m "," n ") = " ackermann(m,n) } } }
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)...
#D
D
void main() /*@safe*/ { import std.stdio, std.algorithm, std.range;   static immutable properDivs = (in uint n) pure nothrow @safe /*@nogc*/ => iota(1, (n + 1) / 2 + 1).filter!(x => n % x == 0 && n != x);   enum Class { deficient, perfect, abundant }   static Class classify(in uint n) pure nothr...
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...
#Erlang
Erlang
  -module (align_columns).   -export([align_left/0, align_right/0, align_center/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...
#Tcl
Tcl
package require Tcl 8.6 oo::class create integrator { variable e sum delay tBase t0 k0 aid constructor {{interval 1}} { set delay $interval set tBase [clock microseconds] set t0 0 set e { 0.0 } set k0 0.0 set sum 0.0 set aid [after $delay [namespace code {my Step}]] } destructor { after cancel $...
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...
#Scala
Scala
def createAliquotSeq(n: Long, step: Int, list: List[Long]): (String, List[Long]) = { val sum = properDivisors(n).sum if (sum == 0) ("terminate", list ::: List(sum)) else if (step >= 16 || sum > 140737488355328L) ("non-term", list) else { list.indexOf(sum) match { case -1 => createAli...
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 ...
#OCaml
OCaml
#require "gen" #require "zarith" open Z let range ?(step=one) i j = if i = j then Gen.empty else Gen.unfold (fun k -> if compare i j = compare k j then Some (k, (add step k)) else None) i   (* kth coefficient of (x - 1)^n *) let coeff n k = let numer = Gen.fold mul one (range n (sub n k) ~step:minus_one) in ...
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...
#Ring
Ring
  for ap = 1 to 5 see "k = " + ap + ":" aList = [] for n = 1 to 200 num = 0 for nr = 1 to n if n%nr=0 and isPrime(nr)=1 num = num + 1 pr = nr while true pr = pr * nr if n%pr = 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...
#Ruby
Ruby
require 'prime'   def almost_primes(k=2) return to_enum(:almost_primes, k) unless block_given? 1.step {|n| yield n if n.prime_division.sum( &:last ) == k } end   (1..5).each{|k| puts almost_primes(k).take(10).join(", ")}
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 ...
#Java
Java
import java.net.*; import java.io.*; import java.util.*;   public class WordsOfEqChars { public static void main(String[] args) throws IOException { URL url = new URL("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt"); InputStreamReader isr = new InputStreamReader(url.openStream()); Buff...
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...
#Sidef
Sidef
func fib(n) { return NaN if (n < 0)   func (n) { n < 2 ? n  : (__FUNC__(n-1) + __FUNC__(n-2)) }(n) }
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 ...
#Ring
Ring
  size = 18500 for n = 1 to size m = amicable(n) if m>n and amicable(m)=n see "" + n + " and " + m + nl ok next see "OK" + nl   func amicable nr sum = 1 for d = 2 to sqrt(nr) if nr % d = 0 sum = sum + d sum = sum + nr / d ok next return sum  
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...
#Python
Python
import itertools as _itertools   class Amb(object): def __init__(self): self._names2values = {} # set of values for each global name self._func = None # Boolean constraint function self._valueiterator = None # itertools.product of names values self._funcarg...
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...
#Maple
Maple
AccumulatorFactory := proc( initial := 0 ) local total := initial; proc( val := 1 ) total := total + val end end proc:
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...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
accFactory[initial_] := Module[{total = initial}, Function[x, total += x] ] x=accFactory[1]; x[5.0]; accFactory[3]; x[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 ...
#Babel
Babel
main: {((0 0) (0 1) (0 2) (0 3) (0 4) (1 0) (1 1) (1 2) (1 3) (1 4) (2 0) (2 1) (2 2) (2 3) (3 0) (3 1) (3 2) (4 0))   { dup "A(" << { %d " " . << } ... ") = " << reverse give ack  %d cr << } ... }   ack!: { dup zero? { <-> dup ...
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)...
#Delphi
Delphi
/* Fill a given array such that for each N, * P[n] is the sum of proper divisors of N */ proc nonrec propdivs([*] word p) void: word i, j, max; max := dim(p,1)-1; for i from 0 upto max do p[i] := 0 od; for i from 1 upto max/2 do for j from i*2 by i upto max do p[j] := p[j] + i ...
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...
#Euphoria
Euphoria
constant data = { "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$c...
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...
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Sub Main() Using active As New Integrator active.Operation = Function(t As Double) Math.Sin(2 * Math.PI * 0.5 * t) Threading.Thread.Sleep(TimeSpan.FromSeconds(2)) Console.WriteLine(active.Value) active.Operation = Function(t As Double) 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...
#Swift
Swift
extension BinaryInteger { @inlinable public func factors(sorted: Bool = true) -> [Self] { let maxN = Self(Double(self).squareRoot()) var res = Set<Self>()   for factor in stride(from: 1, through: maxN, by: 1) where self % factor == 0 { res.insert(factor) res.insert(self / factor) }   ...
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 ...
#Oforth
Oforth
import: mapping   : nextCoef( prev -- [] ) | i | Array new 0 over dup prev size 1- loop: i [ prev at(i) prev at(i 1+) - over add ] 0 over add ;   : coefs( n -- [] ) [ 0, 1, 0 ] #nextCoef times(n) extract(2, n 2 + ) ;   : prime?( n -- b) coefs( n ) extract(2, n) conform?( #[n mod 0 == ] ) ;   : aks | i...
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...
#Rust
Rust
fn is_kprime(n: u32, k: u32) -> bool { let mut primes = 0; let mut f = 2; let mut rem = n; while primes < k && rem > 1{ while (rem % f) == 0 && rem > 1{ rem /= f; primes += 1; } f += 1; } rem == 1 && primes == k }   struct KPrimeGen { k: u32, ...
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...
#Scala
Scala
def isKPrime(n: Int, k: Int, d: Int = 2): Boolean = (n, k, d) match { case (n, k, _) if n == 1 => k == 0 case (n, _, d) if n % d == 0 => isKPrime(n / d, k - 1, d) case (_, _, _) => isKPrime(n, k, d + 1) }   def kPrimeStream(k: Int): Stream[Int] = { def loop(n: Int): Stream[Int] = if (isKPrime(n,...
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 ...
#JavaScript
JavaScript
var fs = require('fs'); var words = fs.readFileSync('unixdict.txt', 'UTF-8').split('\n');   var i, item, max = 0, anagrams = {};   for (i = 0; i < words.length; i += 1) { var key = words[i].split('').sort().join(''); if (!anagrams.hasOwnProperty(key)) {//check if property exists on current obj only anagra...
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...
#Smalltalk
Smalltalk
  myMethodComputingFib:arg |_|   ^ (_ := [:n | n <= 1 ifTrue:[n] ifFalse:[(_ value:(n - 1))+(_ value:(n - 2))]] ) value:arg.
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 ...
#Ruby
Ruby
h = {} (1..20_000).each{|n| h[n] = n.proper_divisors.sum } h.select{|k,v| h[v] == k && k < v}.each do |key,val| # k<v filters out doubles and perfects puts "#{key} and #{val}" end  
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...
#R
R
checkSentence <- function(sentence){ # Input: character vector # Output: whether the sentence formed by the elements of the vector is valid for (index in 1:(length(sentence)-1)){ first.word <- sentence[index] second.word <- sentence[index+1]   last.letter <- substr(first.word, nchar(first.word), nchar(f...
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...
#Racket
Racket
  #lang racket   ;; A quick `amb' implementation (same as in the Twelve Statements task) (define failures null)   (define (fail) (if (pair? failures) ((first failures)) (error "no more choices!")))   (define (amb/thunks choices) (let/cc k (set! failures (cons k failures))) (if (pair? choices) (let ([choice (f...
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...
#Mercury
Mercury
:- module accum. :- interface.   :- typeclass addable(T) where [ func T + T = T ].   :- impure func gen(T) = (impure (func(T)) = T) <= addable(T).   :- implementation. :- import_module bt_array, univ, int.   :- mutable(states, bt_array(univ), make_empty_array(0), ground, [untrailed]).   gen(N) = F :- some [!S] ...
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...
#Nemerle
Nemerle
def Foo(n) { mutable value : object = n; fun (i : object) { match(i) { |x is int => match(value) { |y is int => value = x + y; |y is double => value = x + y; } |x is double => match(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 ...
#BASIC
BASIC
100 DIM R%(2900),M(2900),N(2900) 110 FOR M = 0 TO 3 120 FOR N = 0 TO 4 130 GOSUB 200"ACKERMANN 140 PRINT "ACK("M","N") = "ACK 150 NEXT N, M 160 END   200 M(SP) = M 210 N(SP) = N   REM A(M - 1, A(M, N - 1)) 220 IF M > 0 AND N > 0 THEN N = N - 1 : R%(SP) = 0 : SP = SP + 1 : GOTO 200   REM A(M - 1, 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)...
#Draco
Draco
/* Fill a given array such that for each N, * P[n] is the sum of proper divisors of N */ proc nonrec propdivs([*] word p) void: word i, j, max; max := dim(p,1)-1; for i from 0 upto max do p[i] := 0 od; for i from 1 upto max/2 do for j from i*2 by i upto max do p[j] := p[j] + i ...
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...
#F.23
F#
open System open System.IO   let tableFromPath path = let lines = [ for line in File.ReadAllLines(path) -> (line.TrimEnd('$').Split('$')) ] let width = List.fold (fun max (line : string[]) -> if max < line.Length then line.Length else max) 0 lines List.map (fun (a : string[]) -> (List.init width (fu...
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...
#Wren
Wren
import "scheduler" for Scheduler import "timer" for Timer   var Interval = 0   class Integrator { construct new() { _sum = 0 }   input(k) { _k = k _v0 = k.call(0) _t = 0 _running = true integrate_() }   output { _sum }   stop() { _running =...
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...
#Tcl
Tcl
proc ProperDivisors {n} { if {$n == 1} {return 0} set divs 1 set sum 1 for {set i 2} {$i*$i <= $n} {incr i} { if {! ($n % $i)} { lappend divs $i incr sum $i if {$i*$i<$n} { lappend divs [set d [expr {$n / $i}]] incr sum $d ...
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 ...
#PARI.2FGP
PARI/GP
getPoly(n)=('x-1)^n; vector(8,n,getPoly(n-1)) AKS_slow(n)=my(P=getPoly(n));for(i=1,n-1,if(polcoeff(P,i)%n,return(0))); 1; AKS(n)=my(X=('x-1)*Mod(1,n));X^n=='x^n-1; select(AKS, [1..50])
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...
#Seed7
Seed7
$ include "seed7_05.s7i";   const func boolean: kprime (in var integer: number, in integer: k) is func result var boolean: kprime is FALSE; local var integer: p is 2; var integer: f is 0; begin while f < k and p * p <= number do while number rem p = 0 do number := number div p; ...
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...
#SequenceL
SequenceL
import <Utilities/Conversion.sl>; import <Utilities/Sequence.sl>;   main(args(2)) := let result := firstNKPrimes(1 ... 5, 10);   output[i] := "k = " ++ intToString(i) ++ ": " ++ delimit(intToString(result[i]), ' '); in delimit(output, '\n');   firstNKPrimes(k, N) := firstNKPrimesHelper(k, N, 2, []);   firstNKPr...
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 ...
#jq
jq
def anagrams: (reduce .[] as $word ( {table: {}, max: 0}; # state ($word | explode | sort | implode) as $hash | .table[$hash] += [ $word ] | .max = ([ .max, ( .table[$hash] | length) ] | max ) )) | .max as $max | .table | .[] | select(length == $max) ;   # The task: split("\n") | anagr...
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...
#Sparkling
Sparkling
function(n, f) { return f(n, f); }(10, function(n, f) { return n < 2 ? 1 : f(n - 1, f) + f(n - 2, f); })  
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 ...
#Run_BASIC
Run BASIC
size = 18500 for n = 1 to size m = amicable(n) if m > n and amicable(m) = n then print n ; " and " ; m next   function amicable(nr) amicable = 1 for d = 2 to sqr(nr) if nr mod d = 0 then amicable = amicable + d + nr / d next end function
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...
#Raku
Raku
  #| an array of four words, that have more possible values. #| Normally we would want `any' to signify we want any of the values, but well negate later and thus we need `all' my @a = (all «the that a»), (all «frog elephant thing»), (all «walked treaded grows»), (all «slowly quickly»);   sub test (Str $l, Str $r) { ...
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...
#NewLisp
NewLisp
(define (sum (x 0)) (inc 0 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...
#NGS
NGS
{ F Acc(start:Int) { sum = start F acc(i:Int) { sum = sum + i sum } }   acc = Acc(10) echo(acc(5)) echo(acc(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 ...
#Batch_File
Batch File
::Ackermann.cmd @echo off set depth=0 :ack if %1==0 goto m0 if %2==0 goto n0   :else set /a n=%2-1 set /a depth+=1 call :ack %1 %n% set t=%errorlevel% set /a depth-=1 set /a m=%1-1 set /a depth+=1 call :ack %m% %t% set t=%errorlevel% set /a depth-=1 if %depth%==0 ( exit %t% ) else ( exit /b %t% )   :m0 set/a n=%2+1 if ...
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)...
#Dyalect
Dyalect
func sieve(bound) { var (a, d, p) = (0, 0, 0) var sum = Array.Empty(bound + 1, 0)   for divisor in 1..(bound / 2) { var i = divisor + divisor while i <= bound { sum[i] += divisor i += divisor } } for i in 1..bound { if sum[i] < i { ...
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...
#Factor
Factor
USING: fry io kernel math math.functions math.order sequences splitting strings ; IN: rosetta.column-aligner   CONSTANT: example-text "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$e...
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...
#zkl
zkl
class Integrator{ // continuously integrate a function `K`, at each `interval` seconds' fcn init(f,interval=1e-4){ var _interval=interval, K=Ref(f), S=Ref(0.0), run=True; self.launch(); // start me as a thread } fcn liftoff{ // entry point for the thread start:=Time.Clock.timef; // float...
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...
#VBA
VBA
Option Explicit   Private Type Aliquot Sequence() As Double Classification As String End Type   Sub Main() Dim result As Aliquot, i As Long, j As Double, temp As String 'display the classification and sequences of the numbers one to ten inclusive For j = 1 To 10 result = Aliq(j) temp = vbNullString...
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 ...
#Pascal
Pascal
  const pasTriMax = 61;   type TPasTri = array[0 .. pasTriMax] of UInt64;   var pasTri: TPasTri;   procedure PascalTriangle(n: LongWord); // Calculate the n'th line 0.. middle var j, k: LongWord; begin pasTri[0] := 1; j := 1; while j <= n do begin Inc(j); k := j div 2; pasTri[k] := pasTri[k ...
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...
#Sidef
Sidef
func is_k_almost_prime(n, k) { for (var (p, f) = (2, 0); (f < k) && (p*p <= n); ++p) { (n /= p; ++f) while (p `divides` n) } n > 1 ? (f.inc == k) : (f == k) }   { |k| var x = 10 say gather { { |i| if (is_k_almost_prime(i, k)) { take(i) --x ...
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 ...
#Jsish
Jsish
/* Anagrams, in Jsish */ var datafile = 'unixdict.txt'; if (console.args[0] == '-more' && Interp.conf('maxArrayList') > 500000) datafile = '/usr/share/dict/words';   var words = File.read(datafile).split('\n'); puts(words.length, 'words');   var i, item, max = 0, anagrams = {};   for (i = 0; i < words.length; i += ...
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...
#Standard_ML
Standard ML
fun fix f x = f (fix f) x   fun fib n = if n < 0 then raise Fail "Negative" else fix (fn fib => (fn 0 => 0 | 1 => 1 | n => fib (n-1) + fib (n-2))) n
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 ...
#Rust
Rust
fn sum_of_divisors(val: u32) -> u32 { (1..val/2+1).filter(|n| val % n == 0) .fold(0, |sum, n| sum + n) }   fn main() { let iter = (1..20_000).map(|i| (i, sum_of_divisors(i))) .filter(|&(i, div_sum)| i > div_sum);   for (i, sum1) in iter { if sum_of_divisors(...
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...
#Red
Red
Red ["Amb operator"]   findblock: function [ blk [block!] ][ foreach w blk [ if all [word? w block? get w] [return w] if block? w [findblock w] ] ]   amb: function [ cond [block!] ][ either b: findblock cond [ foreach a get b [ cond2: replace/all/deep copy/deep cond b a if amb cond2 [set b a return tru...
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...
#Nim
Nim
  proc accumulator[T: SomeNumber](x: T): auto = var sum = float(x) result = proc (n: float): float = sum += n result = sum   let acc = accumulator(1) echo acc(5) # 6 discard accumulator(3) # Create another accumulator. echo acc(2.3) # 8.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...
#Nit
Nit
# The `accumulator factory` task. # # Nit has no first-class function. # A class is used to store the state. module accumulator_factory   class Accumulator # The accumulated sum # Numeric is used, so Int and Float are accepted private var sum: Numeric fun call(n: Numeric): Numeric do # `add` is the safe `+` meth...
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 ...
#bc
bc
define ack(m, n) { if ( m == 0 ) return (n+1); if ( n == 0 ) return (ack(m-1, 1)); return (ack(m-1, ack(m, n-1))); }   for (n=0; n<7; n++) { for (m=0; m<4; m++) { print "A(", m, ",", n, ") = ", ack(m,n), "\n"; } } quit
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)...
#EchoLisp
EchoLisp
  (lib 'math) ;; sum-divisors function   (define-syntax-rule (++ a) (set! a (1+ a)))   (define (abondance (N 20000)) (define-values (delta abondant deficient perfect) '(0 0 0 0)) (for ((n (in-range 1 (1+ N)))) (set! delta (- (sum-divisors n) n)) (cond ((< delta 0) (++ deficient)) ((> delta 0) (++ abon...
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...
#FBSL
FBSL
#APPTYPE CONSOLE   DIM s = "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...
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...
#Vlang
Vlang
import math const threshold = u64(1) << 47   fn index_of(s []u64, search u64) int { for i, e in s { if e == search { return i } } return -1 }   fn contains(s []u64, search u64) bool { return index_of(s, search) > -1 }   fn max_of(i1 int, i2 int) int { if i1 > i2 { ...
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 ...
#Perl
Perl
use strict; use warnings; # Select one of these lines. Math::BigInt is in core, but quite slow. use Math::BigInt; sub binomial { Math::BigInt->new(shift)->bnok(shift) } # use Math::Pari "binomial"; # use ntheory "binomial";   sub binprime { my $p = shift; return 0 unless $p >= 2; # binomial is symmetric, so onl...
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...
#Swift
Swift
struct KPrimeGen: Sequence, IteratorProtocol { let k: Int private(set) var n: Int   private func isKPrime() -> Bool { var primes = 0 var f = 2 var rem = n   while primes < k && rem > 1 { while rem % f == 0 && rem > 1 { rem /= f primes += 1 }   f += 1 }   r...
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...
#Tcl
Tcl
package require Tcl 8.6 package require math::numtheory   proc firstNprimes n { for {set result {};set i 2} {[llength $result] < $n} {incr i} { if {[::math::numtheory::isprime $i]} { lappend result $i } } return $result }   proc firstN_KalmostPrimes {n k} { set p [firstNprimes $n] set i [lrep...
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 ...
#Julia
Julia
url = "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt" wordlist = open(readlines, download(url))   wsort(word::AbstractString) = join(sort(collect(word)))   function anagram(wordlist::Vector{<:AbstractString}) dict = Dict{String, Set{String}}() for word in wordlist sorted = wsort(word) push...
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...
#SuperCollider
SuperCollider
  ( f = { |n| if(n >= 0) { if(n < 2) { n } { thisFunction.(n-1) + thisFunction.(n-2) } } }; (0..20).collect(f) )  
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 ...
#Scala
Scala
def properDivisors(n: Int) = (1 to n/2).filter(i => n % i == 0) val divisorsSum = (1 to 20000).map(i => i -> properDivisors(i).sum).toMap val result = divisorsSum.filter(v => v._1 < v._2 && divisorsSum.get(v._2) == Some(v._1))   println( result mkString ", " )
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...
#REXX
REXX
/*REXX program demonstrates the Amd operator, choosing a word from each set. */ @.1 = "the that a" @.2 = "frog elephant thing" @.3 = "walked treaded grows" @.4 = "slowly quickly" @.0 = 4 /*de...
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...
#Objeck
Objeck
bundle Default { class Accumulator { @sum : Float;   New(sum : Float) { @sum := sum; }   method : public : Call(n : Float) ~ Float { @sum += n; return @sum; }   function : Main(args : String[]) ~ Nil { x := Accumulator->New(1.0); x->Call(5.0 ); x->Call(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...
#Objective-C
Objective-C
#import <Foundation/Foundation.h>   typedef double (^Accumulator)(double);   Accumulator accumulator_factory(double initial) { __block double sum = initial; Accumulator acc = ^(double n){ return sum += n; }; return acc; }   int main (int argc, const char * argv[]) { @autoreleasepool {   ...
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 ...
#BCPL
BCPL
GET "libhdr"   LET ack(m, n) = m=0 -> n+1, n=0 -> ack(m-1, 1), ack(m-1, ack(m, n-1))   LET start() = VALOF { FOR i = 0 TO 6 FOR m = 0 TO 3 DO writef("ack(%n, %n) = %n*n", m, n, ack(m,n)) RESULTIS 0 }
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)...
#Ela
Ela
open monad io number list   divisors n = filter ((0 ==) << (n `mod`)) [1 .. (n `div` 2)] classOf n = compare (sum $ divisors n) n   do let classes = map classOf [1 .. 20000] let printRes w c = putStrLn $ w ++ (show << length $ filter (== c) classes) printRes "deficient: " LT printRes "perfect: " EQ printRe...
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...
#Forth
Forth
\ align columns   : split ( addr len char -- addr len1 addr len-len1 ) >r 2dup r> scan 2swap 2 pick - ;   variable column   : for-each-line ( file len xt -- ) >r begin #lf split r@ execute 1 /string dup 0<= until 2drop rdrop ;   : for-each-field ( line len xt -- ) 0 column ! >r begin '$ split r@ execute 1 colum...
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...
#Wren
Wren
import "/fmt" for Conv, Fmt import "/math" for Int, Nums import "/seq" for Lst   class Classification { construct new(seq, aliquot) { _seq = seq _aliquot = aliquot } seq { _seq} aliquot { _aliquot } }   var THRESHOLD = 2.pow(47)   var classifySequence = Fn.new { |k| if (k <= 0) Fiber...
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 ...
#Phix
Phix
-- demo/rosetta/AKSprimes.exw -- Does not work for primes above 53, which is actually beyond the original task anyway. -- Translated from the C version, just about everything is (working) out-by-1, what fun. sequence c = repeat(0,100) procedure coef(integer n) -- out-by-1, ie coef(1)==^0, coef(2)==^1, coef(3)==^2 e...
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...
#Tiny_BASIC
Tiny BASIC
  REM Almost prime LET K=1 10 IF K>5 THEN END PRINT "k = ",K,":" LET I=2 LET C=0 20 IF C>=10 THEN GOTO 40 LET N=I GOSUB 500 IF P=0 THEN GOTO 30 PRINT I LET C=C+1 30 LET I=I+1 GOTO 20 40 LET K=K+1 GOTO 10   REM Check if N is a K prime (result: P) 500 LET F=0 LE...
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...
#TypeScript
TypeScript
// Almost prime   function isKPrime(n: number, k: number): bool { var f = 0; for (var i = 2; i <= n; i++) while (n % i == 0) { if (f == k) return false; ++f; n = Math.floor(n / i); } return f == k; }   for (var k = 1; k <= 5; k++) { process.stdout.write(`k = ${k}:`); var i =...
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 ...
#K
K
{x@&a=|/a:#:'x}{x g@&1<#:'g:={x@<x}'x}0::`unixdict.txt
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...
#Swift
Swift
let fib: Int -> Int = { func f(n: Int) -> Int { assert(n >= 0, "fib: no negative numbers") return n < 2 ? 1 : f(n-1) + f(n-2) } return f }()   print(fib(8))
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 ...
#Scheme
Scheme
  (import (scheme base) (scheme inexact) (scheme write) (only (srfi 1) fold))   ;; return a list of the proper-divisors of n (define (proper-divisors n) (let ((root (sqrt n))) (let loop ((divisors (list 1)) (i 2)) (if (> i root) divisors (loop (if (zero...
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...
#Ring
Ring
  # Project : Amb   set1 = ["the","that","a"] set2 = ["frog","elephant","thing"] set3 = ["walked","treaded","grows"] set4 = ["slowly","quickly"] text = amb(set1,set2,set3,set4) if text != "" see "Correct sentence would be: " + nl + text + nl else see "Failed to fine a correct sentence." ok   func wordsok(strin...
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...
#Ruby
Ruby
require "continuation"   class Amb class ExhaustedError < RuntimeError; end   def initialize @fail = proc { fail ExhaustedError, "amb tree exhausted" } end   def choose(*choices) prev_fail = @fail callcc { |sk| choices.each { |choice| callcc { |fk| @fail = proc { @fail = prev_fail ...
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...
#OCaml
OCaml
let accumulator sum0 = let sum = ref sum0 in fun n -> sum := !sum +. n; !sum;;   let _ = let x = accumulator 1.0 in ignore (x 5.0); let _ = accumulator 3.0 in Printf.printf "%g\n" (x 2.3) ;;