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/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... | #Octave | Octave | # not a function file:
1;
function fun = foo(init)
currentSum = init;
fun = @(add) currentSum = currentSum + add; currentSum;
endfunction
x = foo(1);
x(5);
foo(3);
disp(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
... | #beeswax | beeswax |
>M?f@h@gMf@h3yzp if m>0 and n>0 => replace m,n with m-1,m,n-1
>@h@g'b?1f@h@gM?f@hzp if m>0 and n=0 => replace m,n with m-1,1
_ii>Ag~1?~Lpz1~2h@g'd?g?Pfzp if m=0 => replace m,n with n+1
>I;
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)... | #Elena | Elena | import extensions;
classifyNumbers(int bound, ref int abundant, ref int deficient, ref int perfect)
{
int a := 0;
int d := 0;
int p := 0;
int[] sum := new int[](bound + 1);
for(int divisor := 1, divisor <= bound / 2, divisor += 1)
{
for(int i := divisor + divisor, i <= bound, i += di... |
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... | #Fortran | Fortran |
SUBROUTINE RAKE(IN,M,X,WAY) !Casts forth text in fixed-width columns.
Collates column widths so that each column is wide enough for its widest member.
INTEGER IN !Fingers the input file.
INTEGER M !Maximum record length thereof.
CHARACTER*1 X !The delimiter, possibly a comma.
INTE... |
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... | #Yabasic | Yabasic | // Rosetta Code problem: http://rosettacode.org/wiki/Aliquot_sequence_classifications
// by Galileo, 05/2022
sub sumFactors(n)
local i, s
for i = 1 to n / 2
if not mod(n, i) s = s + i
next
return s
end sub
sub printSeries(arr(), size, ty$)
local i
print "Integer: ", arr(0), ", Ty... |
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 ... | #Picat | Picat |
pascal([]) = [1].
pascal(L) = [1|sum_adj(L)].
sum_adj(Row) = Next =>
Next = L,
while (Row = [A,B|_])
L = [A+B|Rest],
L := Rest,
Row := tail(Row)
end,
L = Row.
show_x(0) = "".
show_x(1) = "x".
show_x(N) = S, N > 1 => S = [x, '^' | to_string(N)].
show_term(Coef, Exp) = cond... |
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... | #uBasic.2F4tH | uBasic/4tH | Local(3)
For c@ = 1 To 5
Print "k = ";c@;": ";
b@=0
For a@ = 2 Step 1 While b@ < 10
If FUNC(_kprime (a@,c@)) Then
b@ = b@ + 1
Print " ";a@;
EndIf
Next
Print
Next
End
_kprime Param(2)
Local(2)
d@ = 0
For c@ = 2 Step 1 While (d@ < b@) * ((c@ * c@) < (a@ + 1))
Do Whi... |
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... | #VBA | VBA | Private Function kprime(ByVal n As Integer, k As Integer) As Boolean
Dim p As Integer, factors As Integer
p = 2
factors = 0
Do While factors < k And p * p <= n
Do While n Mod p = 0
n = n / p
factors = factors + 1
Loop
p = p + 1
Loop
factors = facto... |
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
... | #Kotlin | Kotlin | import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.URL
import kotlin.math.max
fun main() {
val url = URL("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt")
val isr = InputStreamReader(url.openStream())
val reader = BufferedReader(isr)
val anagrams = mutableMapOf<String,... |
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... | #Tailspin | Tailspin | proc fib n {
# sanity checks
if {[incr n 0] < 0} {error "argument may not be negative"}
apply {x {
if {$x < 2} {return $x}
# Extract the lambda term from the stack introspector for brevity
set f [lindex [info level 0] 1]
expr {[apply $f [incr x -1]] + [apply $f [incr x -1]]}
}} $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
... | #Sidef | Sidef | func propdivsum(n) {
n.sigma - n
}
for i in (1..20000) {
var j = propdivsum(i)
say "#{i} #{j}" if (j>i && i==propdivsum(j))
} |
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... | #Rust | Rust | use std::ops::Add;
struct Amb<'a> {
list: Vec<Vec<&'a str>>,
}
fn main() {
let amb = Amb {
list: vec![
vec!["the", "that", "a"],
vec!["frog", "elephant", "thing"],
vec!["walked", "treaded", "grows"],
vec!["slowly", "quickly"],
],
};
match a... |
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... | #Oforth | Oforth | : foo( n -- bl )
#[ n swap + dup ->n ] ; |
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... | #ooRexx | ooRexx |
x = .accumulator~new(1) -- new accumulator with initial value of "1"
x~call(5)
x~call(2.3)
say "Accumulator value is now" x -- displays current value
-- an accumulator class instance can be instantiated and
-- used to sum up a series of numbers
::class accumulator
::method init -- instance initializer...se... |
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
... | #Befunge | Befunge | &>&>vvg0>#0\#-:#1_1v
@v:\<vp0 0:-1<\+<
^>00p>:#^_$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)... | #Elixir | Elixir | defmodule Proper do
def divisors(1), do: []
def divisors(n), do: [1 | divisors(2,n,:math.sqrt(n))] |> Enum.sort
defp divisors(k,_n,q) when k>q, do: []
defp divisors(k,n,q) when rem(n,k)>0, do: divisors(k+1,n,q)
defp divisors(k,n,q) when k * k == n, do: [k | divisors(k+1,n,q)]
defp divisors(k,n,q) ... |
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... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Sub Split(s As String, sep As String, result() As String)
Dim As Integer i, j, count = 0
Dim temp As String
Dim As Integer position(Len(s) + 1)
position(0) = 0
For i = 0 To Len(s) - 1
For j = 0 To Len(sep) - 1
If s[i] = sep[j] Then
count += 1
position(count) = i ... |
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... | #zkl | zkl | fcn properDivs(n){ [1.. (n + 1)/2 + 1].filter('wrap(x){ n%x==0 and n!=x }) }
fcn aliquot(k){ //-->Walker
Walker(fcn(rk){ k:=rk.value; if(k)rk.set(properDivs(k).sum()); k }.fp(Ref(k)))
}(10).walk(15).println(); |
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 ... | #PicoLisp | PicoLisp | (de pascal (N)
(let D 1
(make
(for X (inc N)
(link D)
(setq D
(*/ D (- (inc N) X) (- X)) ) ) ) ) )
(for (X 0 (> 10 X) (inc X))
(println X '-> (pascal X) ) )
(println
(filter
'((X)
(fully
'((Y) (=0 (% Y X)))
(cdr (h... |
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 ... | #PL.2FI | PL/I |
AKS: procedure options (main, reorder); /* 16 September 2015, derived from Fortran */
/* Coefficients of polynomial expansion */
declare coeffs(*) fixed (31) controlled;
declare n fixed(3);
/* Point #2 */
do n = 0 to 7;
call polynomial_expansion(n, coeffs);
put edit ( '(x - 1)^', trim(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... | #VBScript | VBScript |
For k = 1 To 5
count = 0
increment = 1
WScript.StdOut.Write "K" & k & ": "
Do Until count = 10
If PrimeFactors(increment) = k Then
WScript.StdOut.Write increment & " "
count = count + 1
End If
increment = increment + 1
Loop
WScript.StdOut.WriteLine
Next
Function PrimeFactors(n)
PrimeFactors = 0
... |
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
... | #Lasso | Lasso | local(
anagrams = map,
words = include_url('http://wiki.puzzlers.org/pub/wordlists/unixdict.txt')->split('\n'),
key,
max = 0,
findings = array
)
with word in #words do {
#key = #word -> split('') -> sort& -> join('')
if(not(#anagrams >> #key)) => {
#anagrams -> insert(#key = array)
}
#anagrams -> find(#k... |
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... | #Tcl | Tcl | proc fib n {
# sanity checks
if {[incr n 0] < 0} {error "argument may not be negative"}
apply {x {
if {$x < 2} {return $x}
# Extract the lambda term from the stack introspector for brevity
set f [lindex [info level 0] 1]
expr {[apply $f [incr x -1]] + [apply $f [incr x -1]]}
}} $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
... | #Swift | Swift | import func Darwin.sqrt
func sqrt(x:Int) -> Int { return Int(sqrt(Double(x))) }
func properDivs(n: Int) -> [Int] {
if n == 1 { return [] }
var result = [Int]()
for div in filter (1...sqrt(n), { n % $0 == 0 }) {
result.append(div)
if n/div != div && n/div != n { result.append(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... | #Scala | Scala | object Amb {
def amb(wss: List[List[String]]): Option[String] = {
def _amb(ws: List[String], wss: List[List[String]]): Option[String] = wss match {
case Nil => ((Some(ws.head): Option[String]) /: ws.tail)((a, w) => a match {
case Some(x) => if (x.last == w.head) Some(x + " " + w) else None
... |
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... | #OxygenBasic | OxygenBasic |
Class AccumFactory
'=================
double v
method constructor()
end method
method destructor()
end method
method Accum(double n) as AccumFactory
new AccumFactory af
af.v=v+n
return af
end method
method FloatValue() as double
return v
end method
method IntValue() as sys
return v
... |
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... | #Oz | Oz | declare
fun {Acc Init}
State = {NewCell Init}
in
fun {$ X}
OldState
in
{Exchange State OldState} = {Sum OldState X}
end
end
fun {Sum A B}
if {All [A B] Int.is} then A+B
else {ToFloat A}+{ToFloat B}
end
end
fun {ToFloat X}
if {Float.is X} then 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
... | #BQN | BQN | A ← {
A 0‿n: n+1;
A m‿0: A (m-1)‿1;
A m‿n: 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)... | #Erlang | Erlang |
-module(properdivs).
-export([divs/1,sumdivs/1,class/1]).
divs(0) -> [];
divs(1) -> [];
divs(N) -> lists:sort(divisors(1,N)).
divisors(1,N) ->
divisors(2,N,math:sqrt(N),[1]).
divisors(K,_N,Q,L) when K > Q -> L;
divisors(K,N,_Q,L) when N rem K =/= 0 ->
divisors(K+1,N,_Q,L);
divisors(K,N,_Q,L) when K ... |
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... | #FutureBasic | FutureBasic |
include "NSLog.incl"
local fn AlignColumn
'~'1
NSUInteger i
CFStringRef testStr = @"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$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... | #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 PRINT "Number classification sequence"
20 INPUT "Enter a number (0 to end): ";k: IF k>0 THEN GO SUB 2000: PRINT k;" ";s$: GO TO 20
40 STOP
1000 REM sumprop
1010 IF oldk=1 THEN LET newk=0: RETURN
1020 LET sum=1
1030 LET root=SQR oldk
1040 FOR i=2 TO root-0.1
1050 IF oldk/i=INT (oldk/i) THEN LET sum=sum+i+oldk/i
106... |
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 ... | #Prolog | Prolog |
prime(P) :-
pascal([1,P|Xs]),
append(Xs, [1], Rest),
forall( member(X,Xs), 0 is X mod 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... | #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Class KPrime
Public K As Integer
Public Function IsKPrime(number As Integer) As Boolean
Dim primes = 0
Dim p = 2
While p * p <= number AndAlso primes < K
While number Mod p = 0 AndAlso primes < K
number = numb... |
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
... | #Liberty_BASIC | Liberty BASIC | ' count the word list
open "unixdict.txt" for input as #1
while not(eof(#1))
line input #1,null$
numWords=numWords+1
wend
close #1
'import to an array appending sorted letter set
open "unixdict.txt" for input as #1
dim wordList$(numWords,3)
dim chrSort$(45)
wordNum=1
while wordNum<numWords
line input #1,a... |
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... | #True_BASIC | True BASIC | FUNCTION Fibonacci (num)
IF num < 0 THEN
PRINT "Invalid argument: ";
LET Fibonacci = num
END IF
IF num < 2 THEN
LET Fibonacci = num
ELSE
LET Fibonacci = Fibonacci(num - 1) + Fibonacci(num - 2)
END IF
END FUNCTION
PRINT Fibonacci(20)
PRINT Fibonacci(30)
PRINT Fibonacci... |
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
... | #tbas | tbas |
dim sums(20000)
sub sum_proper_divisors(n)
dim sum = 0
dim i
if n > 1 then
for i = 1 to (n \ 2)
if n %% i = 0 then
sum = sum + i
end if
next
end if
return sum
end sub
dim i, j
for i = 1 to 20000
sums(i) = sum_proper_divisors(i)
for j = i-1 to 2 by -1
if sums(i) = j and sums(j) = i then
... |
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... | #Scheme | Scheme | (define fail
(lambda ()
(error "Amb tree exhausted")))
(define-syntax amb
(syntax-rules ()
((AMB) (FAIL)) ; Two shortcuts.
((AMB expression) expression)
((AMB expression ...)
(LET ((FAIL-SAVE FAIL))
((CALL-WITH-CURRENT-CONTINUATION ; Capture a continuati... |
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... | #PARI.2FGP | PARI/GP | stack = List([1]);
factory(b,c=0) = my(a=stack[1]++);listput(stack,c);(b)->stack[a]+=b;
foo(f) = factory(0, f); \\ initialize the factory |
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... | #Perl | Perl | sub accumulator {
my $sum = shift;
sub { $sum += shift }
}
my $x = accumulator(1);
$x->(5);
accumulator(3);
print $x->(2.3), "\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
... | #Bracmat | Bracmat | ( Ack
= m n
. !arg:(?m,?n)
& ( !m:0&!n+1
| !n:0&Ack$(!m+-1,1)
| Ack$(!m+-1,Ack$(!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)... | #F.23 | F# |
let mutable a=0
let mutable b=0
let mutable c=0
let mutable d=0
let mutable e=0
let mutable f=0
for i=1 to 20000 do
b <- 0
f <- i/2
for j=1 to f do
if i%j=0 then
b <- b+i
if b<i then
c <- c+1
if b=i then
d <- d+1
if b>i then
e <- e+1
printfn " defic... |
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... | #Gambas | Gambas | Public Sub Main() 'Written in Gambas 3.9.2 as a Command line Application - 15/03/2017
Dim siCount, siCounter, siLength As Short 'Counters
Dim siLongest As Short = -1 'To stor... |
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 ... | #PureBasic | PureBasic | EnableExplicit
Define vzr.b = -1, vzc.b = ~vzr, nMAX.i = 10, n.i , k.i
Procedure coeff(nRow.i, Array pd.i(2))
Define n.i, k.i
For n=1 To nRow
For k=0 To n
If k=0 Or k=n : pd(n,k)=1 : Continue : EndIf
pd(n,k)=pd(n-1,k-1)+pd(n-1,k)
Next
Next
EndProcedure
Procedure.b isPrime(n.i, Array pd.i(2... |
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... | #Vlang | Vlang | fn k_prime(n int, k int) bool {
mut nf := 0
mut nn := n
for i in 2 .. nn+1 {
for nn % i == 0 {
if nf == k {
return false
}
nf++
nn/=i
}
}
return nf == k
}
fn gen(k int, n int) []int {
mut r := []int{len:n}
mut ... |
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... | #Wren | Wren | var kPrime = Fn.new { |n, k|
var nf = 0
var i = 2
while (i <= n) {
while (n%i == 0) {
if (nf == k) return false
nf = nf + 1
n = (n/i).floor
}
i = i + 1
}
return nf == k
}
var gen = Fn.new { |k, n|
var r = List.filled(n, 0)
n = 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
... | #LiveCode | LiveCode | on mouseUp
put mostCommonAnagrams(url "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt")
end mouseUp
function mostCommonAnagrams X
put 0 into maxCount
repeat for each word W in X
get sortChars(W)
put W & comma after A[it]
add 1 to C[it]
if C[it] >= maxCount then
if C[it] ... |
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... | #TXR | TXR | (defmacro recursive ((. parm-init-pairs) . body)
(let ((hidden-name (gensym "RECURSIVE-")))
^(macrolet ((recurse (. args) ^(,',hidden-name ,*args)))
(labels ((,hidden-name (,*[mapcar first parm-init-pairs]) ,*body))
(,hidden-name ,*[mapcar second parm-init-pairs])))))
(defun fib (number)
(if (... |
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
... | #Tcl | Tcl | proc properDivisors {n} {
if {$n == 1} return
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
}
}
}
return [list $sum $divs]
}
proc amicablePa... |
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... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
const type: setListType is array array string;
const func array string: amb (in string: word1, in setListType: listOfSets) is func
result
var array string: ambResult is 0 times "";
local
var string: word2 is "";
begin
for word2 range listOfSets[1] do
if length(ambRe... |
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... | #SETL | SETL | program amb;
sets := unstr('[{the that a} {frog elephant thing} {walked treaded grows} {slowly quickly}]');
words := [amb(words): words in sets];
if exists lWord = words(i), rWord in {words(i+1)} |
lWord(#lWord) /= rWord(1) then
fail;
end if;
proc amb(words);
return arb {word in words | ok};
end pro... |
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... | #Phix | Phix | sequence accumulators = {}
function accumulate(integer id, atom v)
accumulators[id] += v
return accumulators[id]
end function
constant r_accumulate = routine_id("accumulate")
function accumulator_factory(atom initv=0)
accumulators = append(accumulators,initv)
return {r_accumulate,length(accumulators... |
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
... | #Brat | Brat | ackermann = { m, n |
when { m == 0 } { n + 1 }
{ m > 0 && n == 0 } { ackermann(m - 1, 1) }
{ m > 0 && n > 0 } { ackermann(m - 1, ackermann(m, n - 1)) }
}
p ackermann 3, 4 #Prints 125 |
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)... | #Factor | Factor |
USING: fry math.primes.factors math.ranges ;
: psum ( n -- m ) divisors but-last sum ;
: pcompare ( n -- <=> ) dup psum swap <=> ;
: classify ( -- seq ) 20,000 [1,b] [ pcompare ] map ;
: pcount ( <=> -- n ) '[ _ = ] count ;
classify [ +lt+ pcount "Deficient: " write . ]
[ +eq+ pcount "Perfect: " ... |
http://rosettacode.org/wiki/Align_columns | Align columns | Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, o... | #Go | Go | package main
import (
"fmt"
"strings"
)
const 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$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$e... |
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 ... | #Python | Python | def expand_x_1(n):
# This version uses a generator and thus less computations
c =1
for i in range(n//2+1):
c = c*(n-i)//(i+1)
yield c
def aks(p):
if p==2:
return True
for i in expand_x_1(p):
if i % p:
# we stop without computing all possible solutions
ret... |
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... | #XBasic | XBasic |
' Almost prime
PROGRAM "almostprime"
VERSION "0.0002"
DECLARE FUNCTION Entry()
INTERNAL FUNCTION KPrime(n%%, k%%)
FUNCTION Entry()
FOR k@@ = 1 TO 5
PRINT "k ="; k@@; ":";
i%% = 2
c%% = 0
DO WHILE c%% < 10
IFT KPrime(i%%, k@@) THEN
PRINT FORMAT$(" ###", i%%);
INC c%%
E... |
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
... | #Lua | Lua | function sort(word)
local bytes = {word:byte(1, -1)}
table.sort(bytes)
return string.char(table.unpack(bytes))
end
-- Read in and organize the words.
-- word_sets[<alphabetized_letter_list>] = {<words_with_those_letters>}
local word_sets = {}
local max_size = 0
for word in io.lines('unixdict.txt') do
local ke... |
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... | #UNIX_Shell | UNIX Shell | fib() {
if test 0 -gt "$1"; then
echo "fib: fib of negative" 1>&2
return 1
else
(
fib2() {
if test 2 -gt "$1"; then
echo "$1"
else
echo $(( $(fib2 $(($1 - 1)) ) + $(fib2 $(($1 - 2)) ) ))
fi
}
fib2 "$1"
)
fi
} |
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
... | #Transd | Transd |
#lang transd
MainModule : {
_start: (lambda
(with sum 0 d 0 f Filter( from: 1 to: 20000 apply: (lambda
(= sum 1)
(for i in Range(2 (to-Int (sqrt @it))) do
(if (not (mod @it i))
(= d (/ @it i)) (+= sum i)
... |
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... | #Smalltalk | Smalltalk | Object subclass:#Amb
instanceVariableNames:''
classVariableNames:''
poolDictionaries:''
category:'Rosetta'
!
Smalltalk::Notification subclass:#FoundSolution
instanceVariableNames:''
classVariableNames:''
poolDictionaries:''
privateIn:Amb
!
!Amb::FoundSol... |
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... | #PHP | PHP | <?php
function accumulator($start){
return create_function('$x','static $v='.$start.';return $v+=$x;');
}
$acc = accumulator(5);
echo $acc(5), "\n"; //prints 10
echo $acc(10), "\n"; //prints 20
?> |
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... | #PicoLisp | PicoLisp | (de accumulator (Sum)
(curry (Sum) (N)
(inc 'Sum N) ) )
(def 'a (accumulator 7))
(a 1) # Output: -> 8
(a 2) # Output: -> 10
(a -5) # Output: -> 5 |
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
... | #C | C | #include <stdio.h>
int ackermann(int m, int n)
{
if (!m) return n + 1;
if (!n) return ackermann(m - 1, 1);
return ackermann(m - 1, ackermann(m, n - 1));
}
int main()
{
int m, n;
for (m = 0; m <= 4; m++)
for (n = 0; n < 6 - m; n++)
print... |
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)... | #Forth | Forth | CREATE A 0 ,
: SLOT ( x y -- 0|1|2) OVER OVER < -ROT > - 1+ ;
: CLASSIFY ( n -- n') \ 0 == deficient, 1 == perfect, 2 == abundant
DUP A ! \ we'll be accessing this often, so save somewhere convenient
2 / >R \ upper bound
1 \ starting sum, 1 is always a divisor
2 \ current check
BEGIN ... |
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... | #Groovy | Groovy | def alignColumns = { align, rawText ->
def lines = rawText.tokenize('\n')
def words = lines.collect { it.tokenize(/\$/) }
def maxLineWords = words.collect {it.size()}.max()
words = words.collect { line -> line + [''] * (maxLineWords - line.size()) }
def columnWidths = words.transpose().collect{ colu... |
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 ... | #R | R | AKS<-function(p){
i<-2:p-1
l<-unique(factorial(p) / (factorial(p-i) * factorial(i)))
if(all(l%%p==0)){
print(noquote("It is prime."))
}else{
print(noquote("It isn't prime."))
}
} |
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 ... | #Racket | Racket | #lang racket
(require math/number-theory)
;; 1. coefficients of expanded polynomial (x-1)^p
;; produces a vector because in-vector can provide a start
;; and stop (of 1 and p) which allow us to drop the (-1)^p
;; and the x^p terms, respectively.
;;
;; (vector-ref (coefficients p) e) is the coefficient 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... | #XPL0 | XPL0 | func Factors(N); \Return number of (prime) factors in N
int N, F, C;
[C:= 0; F:= 2;
repeat if rem(N/F) = 0 then
[C:= C+1;
N:= N/F;
]
else F:= F+1;
until F > N;
return C;
];
int K, C, N;
[for K:= 1 to 5 do
[C:= 0;
N:= 2;
IntOut(0, 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... | #Yabasic | Yabasic | // Returns boolean indicating whether n is k-almost prime
sub almostPrime(n, k)
local divisor, count
divisor = 2
while(count < (k + 1) and n <> 1)
if not mod(n, divisor) then
n = n / divisor
count = count + 1
else
divisor = divisor + 1
end if
... |
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
... | #M4 | M4 | divert(-1)
changequote(`[',`]')
define([for],
[ifelse($#,0,[[$0]],
[ifelse(eval($2<=$3),1,
[pushdef([$1],$2)$4[]popdef([$1])$0([$1],incr($2),$3,[$4])])])])
define([_bar],include(t.txt))
define([eachlineA],
[ifelse(eval($2>0),1,
[$3(substr([$1],0,$2))[]eachline(substr([$1],incr($2)),[$3])])])
define([e... |
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... | #Ursala | Ursala | #import nat
fib =
~&izZB?( # test the sign bit of the argument
<'fib of negative'>!%, # throw an exception if it's negative
{0,1}^?<a( # test the argument to a recursively defined function
~&a, # if the argument was a member of {0,1}, return it
s... |
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
... | #uBasic.2F4tH | uBasic/4tH | Input "Limit: ";l
Print "Amicable pairs < ";l
For n = 1 To l
m = FUNC(_SumDivisors (n))-n
If m = 0 Then Continue ' No division by zero, please
p = FUNC(_SumDivisors (m))-m
If (n=p) * (n<m) Then Print n;" and ";m
Next
End
_LeastPower Param(2)
Local(1)
c@ = a@
Do While (b@ % c@) = 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... | #Tcl | Tcl | set amb {
{the that a}
{frog elephant thing}
{walked treaded grows}
{slowly quickly}
}
proc joins {a b} {
expr {[string index $a end] eq [string index $b 0]}
}
foreach i [lindex $amb 0] {
foreach j [lindex $amb 1] {
if ![joins $i $j] continue
foreach k [lindex $amb ... |
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... | #Pony | Pony |
use "assert"
class Accumulator
var value:(I64|F64)
new create(v:(I64|F64))=>
value=v
fun ref apply(v:(I64|F64)=I64(0)):(I64|F64)=>
value=match value
| let x:I64=>match v
| let y:I64=>x+y
| let y:F64=>x.f64()+y
end
| let x:F64=>match v
... |
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... | #PostScript | PostScript | /mk-acc { % accumulator generator
{0 add 0 0 2 index put}
7 array copy
dup 0 4 -1 roll put
dup dup 2 exch put
cvx
} def
% Examples (= is a printing command in PostScript):
/a 1 mk-acc def % create accumulator #1, name it a
5 a = % add 5 to 1, print it
10 mk-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
... | #C.23 | C# | using System;
class Program
{
public static long Ackermann(long m, long n)
{
if(m > 0)
{
if (n > 0)
return Ackermann(m - 1, Ackermann(m, n - 1));
else if (n == 0)
return Ackermann(m - 1, 1);
}
else if(m == 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)... | #Fortran | Fortran | Inspecting sums of proper divisors for 1 to 20000
Deficient 15043
Perfect! 4
Abundant 4953
|
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... | #Harbour | Harbour |
PROCEDURE Main()
LOCAL a := { "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$o... |
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 ... | #Raku | Raku | constant expansions = [1], [1,-1], -> @prior { [|@prior,0 Z- 0,|@prior] } ... *;
sub polyprime($p where 2..*) { so expansions[$p].[1 ..^ */2].all %% $p }
# Showing the expansions:
say ' p: (x-1)ᵖ';
say '-----------';
sub super ($n) {
$n.trans: '0123456789'
=> '⁰¹²³⁴⁵⁶⁷⁸⁹';
}
for ^13 -> $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... | #zkl | zkl | primes:=Utils.Generator(Import("sieve").postponed_sieve);
(p10:=ar:=primes.walk(10)).println();
do(4){
(ar=([[(x,y);ar;p10;'*]] : Utils.Helpers.listUnique(_).sort()[0,10])).println();
} |
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... | #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 FOR k=1 TO 5
20 PRINT k;":";
30 LET c=0: LET i=1
40 IF c=10 THEN GO TO 100
50 LET i=i+1
60 GO SUB 1000
70 IF r THEN PRINT " ";i;: LET c=c+1
90 GO TO 40
100 PRINT
110 NEXT k
120 STOP
1000 REM kprime
1010 LET p=2: LET n=i: LET f=0
1020 IF f=k OR (p*p)>n THEN GO TO 1100
1030 IF n/p=INT (n/p) THEN LET n=n/p: LET f=f+1... |
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
... | #Maple | Maple |
words := HTTP:-Get( "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt" )[2]: # ignore errors
use StringTools, ListTools in
T := Classify( Sort, map( Trim, Split( words ) ) )
end use:
L := convert( T, 'list' ):
m := max( map( nops, L ) ); # what is the largest set?
A := select( s -> evalb( nops( s ) = m ), L ); #... |
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... | #UTFool | UTFool |
···
http://rosettacode.org/wiki/Anonymous_recursion
···
⟦import java.util.function.UnaryOperator;⟧
■ AnonymousRecursion
§ static
▶ main
• args⦂ String[]
if 0 > Integer.valueOf args[0]
System.out.println "negative argument"
else
System.out.println *UnaryOperator⟨Integer⟩° ■
... |
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
... | #UTFool | UTFool |
···
http://rosettacode.org/wiki/Amicable_pairs
···
■ AmicablePairs
§ static
▶ main
• args⦂ String[]
∀ n ∈ 1…20000
m⦂ int: sumPropDivs n
if m < n = sumPropDivs m
System.out.println "⸨m⸩ ; ⸨n⸩"
▶ sumPropDivs⦂ int
• n⦂ int
m⦂ int: 1
∀ i ∈ √n ⋯> 1
m... |
http://rosettacode.org/wiki/Amb | Amb | Define and give an example of the Amb operator.
The Amb operator (short for "ambiguous") expresses nondeterminism. This doesn't refer to randomness (as in "nondeterministic universe") but is closely related to the term as it is used in automata theory ("non-deterministic finite automaton").
The Amb operator takes a v... | #TUSCRIPT | TUSCRIPT | $$ MODE TUSCRIPT
set1="the'that'a"
set2="frog'elephant'thing"
set3="walked'treaded'grows"
set4="slowly'quickly"
LOOP w1=set1
lastw1=EXTRACT (w1,-1,0)
LOOP w2=set2
IF (w2.sw.$lastw1) THEN
lastw2=EXTRACT (w2,-1,0)
LOOP w3=set3
IF (w3.sw.$lastw2) THEN
lastw3=EXTRACT (w3,-1,0)
LOOP w4=set4
IF (w4.sw.$last... |
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... | #TXR | TXR | (defmacro amb-scope (. forms)
^(block amb-scope ,*forms)) |
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... | #PowerShell | PowerShell |
function Get-Accumulator ([double]$Start)
{
{param([double]$Plus) return $script:Start += $Plus}.GetNewClosure()
}
|
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... | #Prolog | Prolog | :- use_module(library(lambda)).
define_g(N, G) :-
put_attr(V, user, N),
G = V +\X^Y^(get_attr(V, user, N1),
Y is X + N1,
put_attr(V, user, Y)).
accumulator :-
define_g(1, G),
format('Code of g : ~w~n', [G]),
call(G, 5, S),
writeln(S),
call(G, 2.3, R1),
writeln(R1). |
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
... | #C.2B.2B | C++ | #include <iostream>
unsigned int ackermann(unsigned int m, unsigned int n) {
if (m == 0) {
return n + 1;
}
if (n == 0) {
return ackermann(m - 1, 1);
}
return ackermann(m - 1, ackermann(m, n - 1));
}
int main() {
for (unsigned int m = 0; m < 4; ++m) {
for (unsigned int n = 0; n < 10; ++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)... | #FreeBASIC | FreeBASIC |
' FreeBASIC v1.05.0 win64
Function SumProperDivisors(number As Integer) As Integer
If number < 2 Then Return 0
Dim sum As Integer = 0
For i As Integer = 1 To number \ 2
If number Mod i = 0 Then sum += i
Next
Return sum
End Function
Dim As Integer sum, deficient, perfect, abundant
For n As Integer ... |
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... | #Haskell | Haskell | import Data.List (unfoldr, transpose)
import Control.Arrow (second)
dat =
"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\n" ++
"are$delineated$by$a$single$'dollar'$character,$write$a$program\n" ++
"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\n" ++
"column$are$separated$by$... |
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 ... | #REXX | REXX | /* REXX ---------------------------------------------------------------
* 09.02.2014 Walter Pachl
* 22.02.2014 WP fix 'accounting' problem (courtesy GS)
*--------------------------------------------------------------------*/
c.=1
Numeric Digits 100
limit=200
pl=''
mmm=0
Do p=3 To limit
pm1=p-1
c.p.1=1
c.p.p=1
D... |
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
... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | list=Import["http://wiki.puzzlers.org/pub/wordlists/unixdict.txt","Lines"];
text={#,StringJoin@@Sort[Characters[#]]}&/@list;
text=SortBy[text,#[[2]]&];
splits=Split[text,#1[[2]]==#2[[2]]&][[All,All,1]];
maxlen=Max[Length/@splits];
Select[splits,Length[#]==maxlen&] |
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... | #VBA | VBA |
Sub Main()
Debug.Print F(-10)
Debug.Print F(10)
End Sub
Private Function F(N As Long) As Variant
If N < 0 Then
F = "Error. Negative argument"
ElseIf N <= 1 Then
F = N
Else
F = F(N - 1) + F(N - 2)
End If
End Function |
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
... | #VBA | VBA | Option Explicit
Public Sub AmicablePairs()
Dim a(2 To 20000) As Long, c As New Collection, i As Long, j As Long, t#
t = Timer
For i = LBound(a) To UBound(a)
'collect the sum of the proper divisors
'of each numbers between 2 and 20000
a(i) = S(i)
Next
'Double Loops to test the a... |
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... | #uBasic.2F4tH | uBasic/4tH | ' set up the arrays
Push Dup("the"), Dup("that"), Dup("a") : a = FUNC(_Ambsel (0))
Push Dup("frog"), Dup("elephant"), Dup("thing") : b = FUNC(_Ambsel (a))
Push Dup("walked"), Dup("treaded"), Dup("grows") : c = FUNC(_Ambsel (b))
Push Dup("slowly"), Dup("quickly") ... |
http://rosettacode.org/wiki/Accumulator_factory | Accumulator factory | A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulat... | #Python | Python | >>> def accumulator(sum):
def f(n):
f.sum += n
return f.sum
f.sum = sum
return f
>>> x = accumulator(1)
>>> x(5)
6
>>> x(2.3)
8.3000000000000007
>>> x = accumulator(1)
>>> x(5)
6
>>> x(2.3)
8.3000000000000007
>>> x2 = accumulator(3)
>>> x2(5)
8
>>> x2(3.3)
11.300000000000001
>>> x(0)
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... | #Quackery | Quackery | [ tuck tally share ]this[ swap ] is accumulate ( n s --> [ n )
[ [ stack ] copy tuck put nested
' accumulate nested join ] is factory ( 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
... | #Chapel | Chapel | proc A(m:int, n:int):int {
if m == 0 then
return n + 1;
else if n == 0 then
return A(m - 1, 1);
else
return 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)... | #Frink | Frink |
d = new dict
for n = 1 to 20000
{
s = sum[allFactors[n, true, false, true], 0]
rel = s <=> n
d.increment[rel, 1]
}
println["Deficient: " + d@(-1)]
println["Perfect: " + d@0]
println["Abundant: " + d@1]
|
Subsets and Splits
Rosetta Code COBOL Python Hard Tasks
Identifies and retrieves challenging tasks that exist in both COBOL and Python, revealing cross-language programming patterns and difficulty levels for comparative analysis.
Rosetta Code Task Comparisons
Identifies tasks common to both COBOL and Python languages that are described as having difficulty levels, revealing cross-language task similarities and providing useful comparative programming examples.
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.