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/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part", where the imaginary part is the number to be multiplied by
i
{\displaystyle i}
.
Task
Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.)
Print the results for each operation tested.
Optional: Show complex conjugation.
By definition, the complex conjugate of
a
+
b
i
{\displaystyle a+bi}
is
a
−
b
i
{\displaystyle a-bi}
Some languages have complex number libraries available. If your language does, show the operations. If your language does not, also show the definition of this type.
| #Nim | Nim |
import complex
var a: Complex = (1.0,1.0)
var b: Complex = (3.1415,1.2)
echo("a : " & $a)
echo("b : " & $b)
echo("a + b: " & $(a + b))
echo("a * b: " & $(a * b))
echo("1/a : " & $(1/a))
echo("-a : " & $(-a))
|
http://rosettacode.org/wiki/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part", where the imaginary part is the number to be multiplied by
i
{\displaystyle i}
.
Task
Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.)
Print the results for each operation tested.
Optional: Show complex conjugation.
By definition, the complex conjugate of
a
+
b
i
{\displaystyle a+bi}
is
a
−
b
i
{\displaystyle a-bi}
Some languages have complex number libraries available. If your language does, show the operations. If your language does not, also show the definition of this type.
| #Oberon-2 | Oberon-2 |
MODULE Complex;
IMPORT Files,Out;
TYPE
Complex* = POINTER TO ComplexDesc;
ComplexDesc = RECORD
r-,i-: REAL;
END;
PROCEDURE (CONST x: Complex) Add*(CONST y: Complex): Complex;
BEGIN
RETURN New(x.r + y.r,x.i + y.i)
END Add;
PROCEDURE (CONST x: Complex) Sub*(CONST y: Complex): Complex;
BEGIN
RETURN New(x.r - y.r,x.i - y.i)
END Sub;
PROCEDURE (CONST x: Complex) Mul*(CONST y: Complex): Complex;
BEGIN
RETURN New(x.r*y.r - x.i*y.i,x.r*y.i + x.i*y.r)
END Mul;
PROCEDURE (CONST x: Complex) Div*(CONST y: Complex): Complex;
VAR
d: REAL;
BEGIN
d := y.r * y.r + y.i * y.i;
RETURN New((x.r*y.r + x.i*y.i)/d,(x.i*y.r - x.r*y.i)/d)
END Div;
(* Reciprocal *)
PROCEDURE (CONST x: Complex) Rec*(): Complex;
VAR
d: REAL;
BEGIN
d := x.r * x.r + y.i * y.i;
RETURN New(x.r/d,(-1.0 * x.i)/d);
END Rec;
(* Conjugate *)
PROCEDURE (x: Complex) Con*(): Complex;
BEGIN
RETURN New(x.r, (-1.0) * x.i);
END Con;
PROCEDURE (x: Complex) Out(out : Files.File);
BEGIN
Files.WriteString(out,"(");
Files.WriteReal(out,x.r);
Files.WriteString(out,",");
Files.WriteReal(out,x.i);
Files.WriteString(out,"i)")
END Out;
PROCEDURE New(x,y: REAL): Complex;
VAR
r: Complex;
BEGIN
NEW(r);r.r := x;r.i := y;
RETURN r
END New;
VAR
r,x,y: Complex;
BEGIN
x := New(1.5,3);
y := New(1.0,1.0);
Out.String("x: ");x.Out(Files.stdout);Out.Ln;
Out.String("y: ");y.Out(Files.stdout);Out.Ln;
r := x.Add(y);
Out.String("x + y: ");r.Out(Files.stdout);Out.Ln;
r := x.Sub(y);
Out.String("x - y: ");r.Out(Files.stdout);Out.Ln;
r := x.Mul(y);
Out.String("x * y: ");r.Out(Files.stdout);Out.Ln;
r := x.Div(y);
Out.String("x / y: ");r.Out(Files.stdout);Out.Ln;
r := y.Rec();
Out.String("1 / y: ");r.Out(Files.stdout);Out.Ln;
r := x.Con();
Out.String("x': ");r.Out(Files.stdout);Out.Ln;
END Complex.
|
http://rosettacode.org/wiki/Arithmetic/Rational | Arithmetic/Rational | Task
Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language.
Example
Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number).
Further define the appropriate rational unary operators abs and '-', with the binary operators for addition '+', subtraction '-', multiplication '×', division '/', integer division '÷', modulo division, the comparison operators (e.g. '<', '≤', '>', & '≥') and equality operators (e.g. '=' & '≠').
Define standard coercion operators for casting int to frac etc.
If space allows, define standard increment and decrement operators (e.g. '+:=' & '-:=' etc.).
Finally test the operators:
Use the new type frac to find all perfect numbers less than 219 by summing the reciprocal of the factors.
Related task
Perfect Numbers
| #Perl | Perl | use bigrat;
foreach my $candidate (2 .. 2**19) {
my $sum = 1 / $candidate;
foreach my $factor (2 .. sqrt($candidate)+1) {
if ($candidate % $factor == 0) {
$sum += 1 / $factor + 1 / ($candidate / $factor);
}
}
if ($sum->denominator() == 1) {
print "Sum of recipr. factors of $candidate = $sum exactly ", ($sum == 1 ? "perfect!" : ""), "\n";
}
} |
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geometric mean of two numbers.
The arithmetic-geometric mean of two numbers can be (usefully) denoted as
a
g
m
(
a
,
g
)
{\displaystyle \mathrm {agm} (a,g)}
, and is equal to the limit of the sequence:
a
0
=
a
;
g
0
=
g
{\displaystyle a_{0}=a;\qquad g_{0}=g}
a
n
+
1
=
1
2
(
a
n
+
g
n
)
;
g
n
+
1
=
a
n
g
n
.
{\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.}
Since the limit of
a
n
−
g
n
{\displaystyle a_{n}-g_{n}}
tends (rapidly) to zero with iterations, this is an efficient method.
Demonstrate the function by calculating:
a
g
m
(
1
,
1
/
2
)
{\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})}
Also see
mathworld.wolfram.com/Arithmetic-Geometric Mean
| #Relation | Relation |
function agm(x,y)
set a = x
set g = y
while abs(a - g) > 0.00000000001
set an = (a + g)/2
set gn = sqrt(a * g)
set a = an
set g = gn
set i = i + 1
end while
set result = g
end function
set x = 1
set y = 1/sqrt(2)
echo (x + y)/2
echo sqrt(x+y)
echo agm(x,y)
|
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geometric mean of two numbers.
The arithmetic-geometric mean of two numbers can be (usefully) denoted as
a
g
m
(
a
,
g
)
{\displaystyle \mathrm {agm} (a,g)}
, and is equal to the limit of the sequence:
a
0
=
a
;
g
0
=
g
{\displaystyle a_{0}=a;\qquad g_{0}=g}
a
n
+
1
=
1
2
(
a
n
+
g
n
)
;
g
n
+
1
=
a
n
g
n
.
{\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.}
Since the limit of
a
n
−
g
n
{\displaystyle a_{n}-g_{n}}
tends (rapidly) to zero with iterations, this is an efficient method.
Demonstrate the function by calculating:
a
g
m
(
1
,
1
/
2
)
{\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})}
Also see
mathworld.wolfram.com/Arithmetic-Geometric Mean
| #REXX | REXX | /*REXX program calculates the AGM (arithmetic─geometric mean) of two (real) numbers. */
parse arg a b digs . /*obtain optional numbers from the C.L.*/
if digs=='' | digs=="," then digs= 120 /*No DIGS specified? Then use default.*/
numeric digits digs /*REXX will use lots of decimal digits.*/
if a=='' | a=="," then a= 1 /*No A specified? Then use the default*/
if b=='' | b=="," then b= 1 / sqrt(2) /* " B " " " " " */
call AGM a,b /*invoke the AGM function. */
say '1st # =' a /*display the A value. */
say '2nd # =' b /* " " B " */
say ' AGM =' agm(a, b) /* " " AGM " */
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
agm: procedure: parse arg x,y; if x=y then return x /*is this an equality case?*/
if y=0 then return 0 /*is Y equal to zero ? */
if x=0 then return y/2 /* " X " " " */
d= digits() /*obtain the current decimal digits. */
numeric digits d + 5 /*add 5 more digs to ensure convergence*/
tiny= '1e-' || (digits() - 1) /*construct a pretty tiny REXX number. */
ox= x + 1 /*ensure that the old X ¬= new X. */
do while ox\=x & abs(ox)>tiny /*compute until the old X ≡ new X. */
ox= x; oy= y /*save the old value of X and Y. */
x= (ox + oy) * .5 /*compute " new " " X. */
y= sqrt(ox * oy) /* " " " " " Y. */
end /*while*/
numeric digits d /*restore the original decimal digits. */
return x / 1 /*normalize X to new " " */
/*──────────────────────────────────────────────────────────────────────────────────────*/
sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); m.=9; numeric form; h=d+6
numeric digits; parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g *.5'e'_ % 2
do j=0 while h>9; m.j=h; h=h % 2 + 1; end /*j*/
do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/; return g |
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, you may also try something like:
x = 0
y = 0
z = x**y
say 'z=' z
Show the result here.
And of course use any symbols or notation that is supported in your computer programming language for exponentiation.
See also
The Wiki entry: Zero to the power of zero.
The Wiki entry: History of differing points of view.
The MathWorld™ entry: exponent laws.
Also, in the above MathWorld™ entry, see formula (9):
x
0
=
1
{\displaystyle x^{0}=1}
.
The OEIS entry: The special case of zero to the zeroth power
| #EchoLisp | EchoLisp |
;; trying the 16 combinations
;; all return the integer 1
(lib 'bigint)
(define zeroes '(integer: 0 inexact=float: 0.000 complex: 0+0i bignum: #0))
(for* ((z1 zeroes) (z2 zeroes)) (write (expt z1 z2)))
→ 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
|
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, you may also try something like:
x = 0
y = 0
z = x**y
say 'z=' z
Show the result here.
And of course use any symbols or notation that is supported in your computer programming language for exponentiation.
See also
The Wiki entry: Zero to the power of zero.
The Wiki entry: History of differing points of view.
The MathWorld™ entry: exponent laws.
Also, in the above MathWorld™ entry, see formula (9):
x
0
=
1
{\displaystyle x^{0}=1}
.
The OEIS entry: The special case of zero to the zeroth power
| #Eiffel | Eiffel | print (0^0) |
http://rosettacode.org/wiki/Arithmetic_evaluation | Arithmetic evaluation | Create a program which parses and evaluates arithmetic expressions.
Requirements
An abstract-syntax tree (AST) for the expression must be created from parsing the input.
The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.)
The expression will be a string or list of symbols like "(1+3)*7".
The four symbols + - * / must be supported as binary operators with conventional precedence rules.
Precedence-control parentheses must also be supported.
Note
For those who don't remember, mathematical precedence is as follows:
Parentheses
Multiplication/Division (left to right)
Addition/Subtraction (left to right)
C.f
24 game Player.
Parsing/RPN calculator algorithm.
Parsing/RPN to infix conversion.
| #Pascal | Pascal | sub ev
# Evaluates an arithmetic expression like "(1+3)*7" and returns
# its value.
{my $exp = shift;
# Delete all meaningless characters. (Scientific notation,
# infinity, and not-a-number aren't supported.)
$exp =~ tr {0-9.+-/*()} {}cd;
return ev_ast(astize($exp));}
{my $balanced_paren_regex;
$balanced_paren_regex = qr
{\( ( [^()]+ | (??{$balanced_paren_regex}) )+ \)}x;
# ??{ ... } interpolates lazily (only when necessary),
# permitting recursion to arbitrary depths.
sub astize
# Constructs an abstract syntax tree by recursively
# transforming textual arithmetic expressions into array
# references of the form [operator, left oprand, right oprand].
{my $exp = shift;
# If $exp is just a number, return it as-is.
$exp =~ /[^0-9.]/ or return $exp;
# If parentheses surround the entire expression, get rid of
# them.
$exp = substr($exp, 1, -1)
while $exp =~ /\A($balanced_paren_regex)\z/;
# Replace stuff in parentheses with placeholders.
my @paren_contents;
$exp =~ s {($balanced_paren_regex)}
{push(@paren_contents, $1);
"[p$#paren_contents]"}eg;
# Scan for operators in order of increasing precedence,
# preferring the rightmost.
$exp =~ m{(.+) ([+-]) (.+)}x or
$exp =~ m{(.+) ([*/]) (.+)}x or
# The expression must've been malformed somehow.
# (Note that unary minus isn't supported.)
die "Eh?: [$exp]\n";
my ($op, $lo, $ro) = ($2, $1, $3);
# Restore the parenthetical expressions.
s {\[p(\d+)\]} {($paren_contents[$1])}eg
foreach $lo, $ro;
# And recurse.
return [$op, astize($lo), astize($ro)];}}
{my %ops =
('+' => sub {$_[0] + $_[1]},
'-' => sub {$_[0] - $_[1]},
'*' => sub {$_[0] * $_[1]},
'/' => sub {$_[0] / $_[1]});
sub ev_ast
# Evaluates an abstract syntax tree of the form returned by
# &astize.
{my $ast = shift;
# If $ast is just a number, return it as-is.
ref $ast or return $ast;
# Otherwise, recurse.
my ($op, @operands) = @$ast;
$_ = ev_ast($_) foreach @operands;
return $ops{$op}->(@operands);}} |
http://rosettacode.org/wiki/Zeckendorf_arithmetic | Zeckendorf arithmetic | This task is a total immersion zeckendorf task; using decimal numbers will attract serious disapprobation.
The task is to implement addition, subtraction, multiplication, and division using Zeckendorf number representation. Optionally provide decrement, increment and comparitive operation functions.
Addition
Like binary 1 + 1 = 10, note carry 1 left. There the similarity ends. 10 + 10 = 101, note carry 1 left and 1 right. 100 + 100 = 1001, note carry 1 left and 2 right, this is the general case.
Occurrences of 11 must be changed to 100. Occurrences of 111 may be changed from the right by replacing 11 with 100, or from the left converting 111 to 100 + 100;
Subtraction
10 - 1 = 1. The general rule is borrow 1 right carry 1 left. eg:
abcde
10100 -
1000
_____
100 borrow 1 from a leaves 100
+ 100 add the carry
_____
1001
A larger example:
abcdef
100100 -
1000
______
1*0100 borrow 1 from b
+ 100 add the carry
______
1*1001
Sadly we borrowed 1 from b which didn't have it to lend. So now b borrows from a:
1001
+ 1000 add the carry
____
10100
Multiplication
Here you teach your computer its zeckendorf tables. eg. 101 * 1001:
a = 1 * 101 = 101
b = 10 * 101 = a + a = 10000
c = 100 * 101 = b + a = 10101
d = 1000 * 101 = c + b = 101010
1001 = d + a therefore 101 * 1001 =
101010
+ 101
______
1000100
Division
Lets try 1000101 divided by 101, so we can use the same table used for multiplication.
1000101 -
101010 subtract d (1000 * 101)
_______
1000 -
101 b and c are too large to subtract, so subtract a
____
1 so 1000101 divided by 101 is d + a (1001) remainder 1
Efficient algorithms for Zeckendorf arithmetic is interesting. The sections on addition and subtraction are particularly relevant for this task.
| #C.23 | C# | using System;
using System.Text;
namespace ZeckendorfArithmetic {
class Zeckendorf : IComparable<Zeckendorf> {
private static readonly string[] dig = { "00", "01", "10" };
private static readonly string[] dig1 = { "", "1", "10" };
private int dVal = 0;
private int dLen = 0;
public Zeckendorf() : this("0") {
// empty
}
public Zeckendorf(string x) {
int q = 1;
int i = x.Length - 1;
dLen = i / 2;
while (i >= 0) {
dVal += (x[i] - '0') * q;
q *= 2;
i--;
}
}
private void A(int n) {
int i = n;
while (true) {
if (dLen < i) dLen = i;
int j = (dVal >> (i * 2)) & 3;
switch (j) {
case 0:
case 1:
return;
case 2:
if (((dVal >> ((i + 1) * 2)) & 1) != 1) return;
dVal += 1 << (i * 2 + 1);
return;
case 3:
int temp = 3 << (i * 2);
temp ^= -1;
dVal = dVal & temp;
B((i + 1) * 2);
break;
}
i++;
}
}
private void B(int pos) {
if (pos == 0) {
Inc();
return;
}
if (((dVal >> pos) & 1) == 0) {
dVal += 1 << pos;
A(pos / 2);
if (pos > 1) A(pos / 2 - 1);
}
else {
int temp = 1 << pos;
temp ^= -1;
dVal = dVal & temp;
B(pos + 1);
B(pos - (pos > 1 ? 2 : 1));
}
}
private void C(int pos) {
if (((dVal >> pos) & 1) == 1) {
int temp = 1 << pos;
temp ^= -1;
dVal = dVal & temp;
return;
}
C(pos + 1);
if (pos > 0) {
B(pos - 1);
}
else {
Inc();
}
}
public Zeckendorf Inc() {
dVal++;
A(0);
return this;
}
public Zeckendorf Copy() {
Zeckendorf z = new Zeckendorf {
dVal = dVal,
dLen = dLen
};
return z;
}
public void PlusAssign(Zeckendorf other) {
for (int gn = 0; gn < (other.dLen + 1) * 2; gn++) {
if (((other.dVal >> gn) & 1) == 1) {
B(gn);
}
}
}
public void MinusAssign(Zeckendorf other) {
for (int gn = 0; gn < (other.dLen + 1) * 2; gn++) {
if (((other.dVal >> gn) & 1) == 1) {
C(gn);
}
}
while ((((dVal >> dLen * 2) & 3) == 0) || (dLen == 0)) {
dLen--;
}
}
public void TimesAssign(Zeckendorf other) {
Zeckendorf na = other.Copy();
Zeckendorf nb = other.Copy();
Zeckendorf nt;
Zeckendorf nr = new Zeckendorf();
for (int i = 0; i < (dLen + 1) * 2; i++) {
if (((dVal >> i) & 1) > 0) {
nr.PlusAssign(nb);
}
nt = nb.Copy();
nb.PlusAssign(na);
na = nt.Copy();
}
dVal = nr.dVal;
dLen = nr.dLen;
}
public int CompareTo(Zeckendorf other) {
return dVal.CompareTo(other.dVal);
}
public override string ToString() {
if (dVal == 0) {
return "0";
}
int idx = (dVal >> (dLen * 2)) & 3;
StringBuilder sb = new StringBuilder(dig1[idx]);
for (int i = dLen - 1; i >= 0; i--) {
idx = (dVal >> (i * 2)) & 3;
sb.Append(dig[idx]);
}
return sb.ToString();
}
}
class Program {
static void Main(string[] args) {
Console.WriteLine("Addition:");
Zeckendorf g = new Zeckendorf("10");
g.PlusAssign(new Zeckendorf("10"));
Console.WriteLine(g);
g.PlusAssign(new Zeckendorf("10"));
Console.WriteLine(g);
g.PlusAssign(new Zeckendorf("1001"));
Console.WriteLine(g);
g.PlusAssign(new Zeckendorf("1000"));
Console.WriteLine(g);
g.PlusAssign(new Zeckendorf("10101"));
Console.WriteLine(g);
Console.WriteLine();
Console.WriteLine("Subtraction:");
g = new Zeckendorf("1000");
g.MinusAssign(new Zeckendorf("101"));
Console.WriteLine(g);
g = new Zeckendorf("10101010");
g.MinusAssign(new Zeckendorf("1010101"));
Console.WriteLine(g);
Console.WriteLine();
Console.WriteLine("Multiplication:");
g = new Zeckendorf("1001");
g.TimesAssign(new Zeckendorf("101"));
Console.WriteLine(g);
g = new Zeckendorf("101010");
g.PlusAssign(new Zeckendorf("101"));
Console.WriteLine(g);
}
}
} |
http://rosettacode.org/wiki/Zumkeller_numbers | Zumkeller numbers | Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the divisors are partitioned, only that the two partition sums are equal.
E.G.
6 is a Zumkeller number; The divisors {1 2 3 6} can be partitioned into two groups {1 2 3} and {6} that both sum to 6.
10 is not a Zumkeller number; The divisors {1 2 5 10} can not be partitioned into two groups in any way that will both sum to the same value.
12 is a Zumkeller number; The divisors {1 2 3 4 6 12} can be partitioned into two groups {1 3 4 6} and {2 12} that both sum to 14.
Even Zumkeller numbers are common; odd Zumkeller numbers are much less so. For values below 10^6, there is at least one Zumkeller number in every 12 consecutive integers, and the vast majority of them are even. The odd Zumkeller numbers are very similar to the list from the task Abundant odd numbers; they are nearly the same except for the further restriction that the abundance (A(n) = sigma(n) - 2n), must be even: A(n) mod 2 == 0
Task
Write a routine (function, procedure, whatever) to find Zumkeller numbers.
Use the routine to find and display here, on this page, the first 220 Zumkeller numbers.
Use the routine to find and display here, on this page, the first 40 odd Zumkeller numbers.
Optional, stretch goal: Use the routine to find and display here, on this page, the first 40 odd Zumkeller numbers that don't end with 5.
See Also
OEIS:A083207 - Zumkeller numbers to get an impression of different partitions OEIS:A083206 Zumkeller partitions
OEIS:A174865 - Odd Zumkeller numbers
Related Tasks
Abundant odd numbers
Abundant, deficient and perfect number classifications
Proper divisors , Factors of an integer | #C.2B.2B | C++ | #include <iostream>
#include <cmath>
#include <vector>
#include <algorithm>
#include <iomanip>
#include <numeric>
using namespace std;
// Returns n in binary right justified with length passed and padded with zeroes
const uint* binary(uint n, uint length);
// Returns the sum of the binary ordered subset of rank r.
// Adapted from Sympy implementation.
uint sum_subset_unrank_bin(const vector<uint>& d, uint r);
vector<uint> factors(uint x);
bool isPrime(uint number);
bool isZum(uint n);
ostream& operator<<(ostream& os, const vector<uint>& zumz) {
for (uint i = 0; i < zumz.size(); i++) {
if (i % 10 == 0)
os << endl;
os << setw(10) << zumz[i] << ' ';
}
return os;
}
int main() {
cout << "First 220 Zumkeller numbers:" << endl;
vector<uint> zumz;
for (uint n = 2; zumz.size() < 220; n++)
if (isZum(n))
zumz.push_back(n);
cout << zumz << endl << endl;
cout << "First 40 odd Zumkeller numbers:" << endl;
vector<uint> zumz2;
for (uint n = 2; zumz2.size() < 40; n++)
if (n % 2 && isZum(n))
zumz2.push_back(n);
cout << zumz2 << endl << endl;
cout << "First 40 odd Zumkeller numbers not ending in 5:" << endl;
vector<uint> zumz3;
for (uint n = 2; zumz3.size() < 40; n++)
if (n % 2 && (n % 10) != 5 && isZum(n))
zumz3.push_back(n);
cout << zumz3 << endl << endl;
return 0;
}
// Returns n in binary right justified with length passed and padded with zeroes
const uint* binary(uint n, uint length) {
uint* bin = new uint[length]; // array to hold result
fill(bin, bin + length, 0); // fill with zeroes
// convert n to binary and store right justified in bin
for (uint i = 0; n > 0; i++) {
uint rem = n % 2;
n /= 2;
if (rem)
bin[length - 1 - i] = 1;
}
return bin;
}
// Returns the sum of the binary ordered subset of rank r.
// Adapted from Sympy implementation.
uint sum_subset_unrank_bin(const vector<uint>& d, uint r) {
vector<uint> subset;
// convert r to binary array of same size as d
const uint* bits = binary(r, d.size() - 1);
// get binary ordered subset
for (uint i = 0; i < d.size() - 1; i++)
if (bits[i])
subset.push_back(d[i]);
delete[] bits;
return accumulate(subset.begin(), subset.end(), 0u);
}
vector<uint> factors(uint x) {
vector<uint> result;
// this will loop from 1 to int(sqrt(x))
for (uint i = 1; i * i <= x; i++) {
// Check if i divides x without leaving a remainder
if (x % i == 0) {
result.push_back(i);
if (x / i != i)
result.push_back(x / i);
}
}
// return the sorted factors of x
sort(result.begin(), result.end());
return result;
}
bool isPrime(uint number) {
if (number < 2) return false;
if (number == 2) return true;
if (number % 2 == 0) return false;
for (uint i = 3; i * i <= number; i += 2)
if (number % i == 0) return false;
return true;
}
bool isZum(uint n) {
// if prime it ain't no zum
if (isPrime(n))
return false;
// get sum of divisors
const auto d = factors(n);
uint s = accumulate(d.begin(), d.end(), 0u);
// if sum is odd or sum < 2*n it ain't no zum
if (s % 2 || s < 2 * n)
return false;
// if we get here and n is odd or n has at least 24 divisors it's a zum!
// Valid for even n < 99504. To test n beyond this bound, comment out this condition.
// And wait all day. Thanks to User:Horsth for taking the time to find this bound!
if (n % 2 || d.size() >= 24)
return true;
if (!(s % 2) && d[d.size() - 1] <= s / 2)
for (uint x = 2; (uint) log2(x) < (d.size() - 1); x++) // using log2 prevents overflow
if (sum_subset_unrank_bin(d, x) == s / 2)
return true; // congratulations it's a zum num!!
// if we get here it ain't no zum
return false;
} |
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included) | Arbitrary-precision integers (included) | Using the in-built capabilities of your language, calculate the integer value of:
5
4
3
2
{\displaystyle 5^{4^{3^{2}}}}
Confirm that the first and last twenty digits of the answer are:
62060698786608744707...92256259918212890625
Find and show the number of decimal digits in the answer.
Note: Do not submit an implementation of arbitrary precision arithmetic. The intention is to show the capabilities of the language as supplied. If a language has a single, overwhelming, library of varied modules that is endorsed by its home site – such as CPAN for Perl or Boost for C++ – then that may be used instead.
Strictly speaking, this should not be solved by fixed-precision numeric libraries where the precision has to be manually set to a large value; although if this is the only recourse then it may be used with a note explaining that the precision must be set manually to a large enough value.
Related tasks
Long multiplication
Exponentiation order
exponentiation operator
Exponentiation with infix operators in (or operating on) the base
| #Alore | Alore | def Main()
var len as Int
var result as Str
result = Str(5**4**3**2)
len = result.length()
Print(len)
Print(result[:20])
Print(result[len-20:])
end |
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included) | Arbitrary-precision integers (included) | Using the in-built capabilities of your language, calculate the integer value of:
5
4
3
2
{\displaystyle 5^{4^{3^{2}}}}
Confirm that the first and last twenty digits of the answer are:
62060698786608744707...92256259918212890625
Find and show the number of decimal digits in the answer.
Note: Do not submit an implementation of arbitrary precision arithmetic. The intention is to show the capabilities of the language as supplied. If a language has a single, overwhelming, library of varied modules that is endorsed by its home site – such as CPAN for Perl or Boost for C++ – then that may be used instead.
Strictly speaking, this should not be solved by fixed-precision numeric libraries where the precision has to be manually set to a large value; although if this is the only recourse then it may be used with a note explaining that the precision must be set manually to a large enough value.
Related tasks
Long multiplication
Exponentiation order
exponentiation operator
Exponentiation with infix operators in (or operating on) the base
| #Arturo | Arturo | num: to :string 5^4^3^2
print [first.n: 20 num ".." last.n: 20 num "=>" size num "digits"] |
http://rosettacode.org/wiki/Zhang-Suen_thinning_algorithm | Zhang-Suen thinning algorithm | This is an algorithm used to thin a black and white i.e. one bit per pixel images.
For example, with an input image of:
################# #############
################## ################
################### ##################
######## ####### ###################
###### ####### ####### ######
###### ####### #######
################# #######
################ #######
################# #######
###### ####### #######
###### ####### #######
###### ####### ####### ######
######## ####### ###################
######## ####### ###### ################## ######
######## ####### ###### ################ ######
######## ####### ###### ############# ######
It produces the thinned output:
# ########## #######
## # #### #
# # ##
# # #
# # #
# # #
############ #
# # #
# # #
# # #
# # #
# ##
# ############
### ###
Algorithm
Assume black pixels are one and white pixels zero, and that the input image is a rectangular N by M array of ones and zeroes.
The algorithm operates on all black pixels P1 that can have eight neighbours.
The neighbours are, in order, arranged as:
P9 P2 P3
P8 P1 P4
P7 P6 P5
Obviously the boundary pixels of the image cannot have the full eight neighbours.
Define
A
(
P
1
)
{\displaystyle A(P1)}
= the number of transitions from white to black, (0 -> 1) in the sequence P2,P3,P4,P5,P6,P7,P8,P9,P2. (Note the extra P2 at the end - it is circular).
Define
B
(
P
1
)
{\displaystyle B(P1)}
= The number of black pixel neighbours of P1. ( = sum(P2 .. P9) )
Step 1
All pixels are tested and pixels satisfying all the following conditions (simultaneously) are just noted at this stage.
(0) The pixel is black and has eight neighbours
(1)
2
<=
B
(
P
1
)
<=
6
{\displaystyle 2<=B(P1)<=6}
(2) A(P1) = 1
(3) At least one of P2 and P4 and P6 is white
(4) At least one of P4 and P6 and P8 is white
After iterating over the image and collecting all the pixels satisfying all step 1 conditions, all these condition satisfying pixels are set to white.
Step 2
All pixels are again tested and pixels satisfying all the following conditions are just noted at this stage.
(0) The pixel is black and has eight neighbours
(1)
2
<=
B
(
P
1
)
<=
6
{\displaystyle 2<=B(P1)<=6}
(2) A(P1) = 1
(3) At least one of P2 and P4 and P8 is white
(4) At least one of P2 and P6 and P8 is white
After iterating over the image and collecting all the pixels satisfying all step 2 conditions, all these condition satisfying pixels are again set to white.
Iteration
If any pixels were set in this round of either step 1 or step 2 then all steps are repeated until no image pixels are so changed.
Task
Write a routine to perform Zhang-Suen thinning on an image matrix of ones and zeroes.
Use the routine to thin the following image and show the output here on this page as either a matrix of ones and zeroes, an image, or an ASCII-art image of space/non-space characters.
00000000000000000000000000000000
01111111110000000111111110000000
01110001111000001111001111000000
01110000111000001110000111000000
01110001111000001110000000000000
01111111110000001110000000000000
01110111100000001110000111000000
01110011110011101111001111011100
01110001111011100111111110011100
00000000000000000000000000000000
Reference
Zhang-Suen Thinning Algorithm, Java Implementation by Nayef Reza.
"Character Recognition Systems: A Guide for Students and Practitioners" By Mohamed Cheriet, Nawwaf Kharma, Cheng-Lin Liu, Ching Suen
| #Go | Go | package main
import (
"bytes"
"fmt"
"strings"
)
var in = `
00000000000000000000000000000000
01111111110000000111111110000000
01110001111000001111001111000000
01110000111000001110000111000000
01110001111000001110000000000000
01111111110000001110000000000000
01110111100000001110000111000000
01110011110011101111001111011100
01110001111011100111111110011100
00000000000000000000000000000000`
func main() {
b := wbFromString(in, '1')
b.zhangSuen()
fmt.Println(b)
}
const (
white = 0
black = 1
)
type wbArray [][]byte // elements are white or black.
// parameter blk is character to read as black. otherwise kinda rigid,
// expects ascii, leading newline, no trailing newline,
// takes color from low bit of character.
func wbFromString(s string, blk byte) wbArray {
lines := strings.Split(s, "\n")[1:]
b := make(wbArray, len(lines))
for i, sl := range lines {
bl := make([]byte, len(sl))
for j := 0; j < len(sl); j++ {
bl[j] = sl[j] & 1
}
b[i] = bl
}
return b
}
// rigid again, hard coded to output space for white, # for black,
// no leading or trailing newline.
var sym = [2]byte{
white: ' ',
black: '#',
}
func (b wbArray) String() string {
b2 := bytes.Join(b, []byte{'\n'})
for i, b1 := range b2 {
if b1 > 1 {
continue
}
b2[i] = sym[b1]
}
return string(b2)
}
// neighbor offsets
var nb = [...][2]int{
2: {-1, 0}, // p2 offsets
3: {-1, 1}, // ...
4: {0, 1},
5: {1, 1},
6: {1, 0},
7: {1, -1},
8: {0, -1},
9: {-1, -1}, // p9 offsets
}
func (b wbArray) reset(en []int) (rs bool) {
var r, c int
var p [10]byte
readP := func() {
for nx := 1; nx <= 9; nx++ {
n := nb[nx]
p[nx] = b[r+n[0]][c+n[1]]
}
}
shiftRead := func() {
n := nb[3]
p[9], p[2], p[3] = p[2], p[3], b[r+n[0]][c+n[1]]
n = nb[4]
p[8], p[1], p[4] = p[1], p[4], b[r+n[0]][c+n[1]]
n = nb[5]
p[7], p[6], p[5] = p[6], p[5], b[r+n[0]][c+n[1]]
}
// returns "A", count of white->black transitions in circuit of neighbors
// of an interior pixel b[r][c]
countA := func() (ct byte) {
bit := p[9]
for nx := 2; nx <= 9; nx++ {
last := bit
bit = p[nx]
if last == white {
ct += bit
}
}
return ct
}
// returns "B", count of black pixels neighboring interior pixel b[r][c].
countB := func() (ct byte) {
for nx := 2; nx <= 9; nx++ {
ct += p[nx]
}
return ct
}
lastRow := len(b) - 1
lastCol := len(b[0]) - 1
mark := make([][]bool, lastRow)
for r = range mark {
mark[r] = make([]bool, lastCol)
}
for r = 1; r < lastRow; r++ {
c = 1
readP()
for { // column loop
m := false
// test for failure of any of the five conditions,
if !(p[1] == black) {
goto markDone
}
if b1 := countB(); !(2 <= b1 && b1 <= 6) {
goto markDone
}
if !(countA() == 1) {
goto markDone
}
{
e1, e2 := p[en[1]], p[en[2]]
if !(p[en[0]]&e1&e2 == 0) {
goto markDone
}
if !(e1&e2&p[en[3]] == 0) {
goto markDone
}
}
// no conditions failed, mark this pixel for reset
m = true
rs = true // and mark that image changes
markDone:
mark[r][c] = m
c++
if c == lastCol {
break
}
shiftRead()
}
}
if rs {
for r = 1; r < lastRow; r++ {
for c = 1; c < lastCol; c++ {
if mark[r][c] {
b[r][c] = white
}
}
}
}
return rs
}
var step1 = []int{2, 4, 6, 8}
var step2 = []int{4, 2, 8, 6}
func (b wbArray) zhangSuen() {
for {
rs1 := b.reset(step1)
rs2 := b.reset(step2)
if !rs1 && !rs2 {
break
}
}
} |
http://rosettacode.org/wiki/Zeckendorf_number_representation | Zeckendorf number representation | Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series.
Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13.
The decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100.
10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that no two consecutive Fibonacci numbers can be used which leads to the former unique solution.
Task
Generate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order.
The intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task.
Also see
OEIS A014417 for the the sequence of required results.
Brown's Criterion - Numberphile
Related task
Fibonacci sequence
| #CLU | CLU | % Get list of distinct Fibonacci numbers up to N
fibonacci = proc (n: int) returns (array[int])
list: array[int] := array[int]$[]
a: int := 1
b: int := 2
while a <= n do
array[int]$addh(list,a)
a, b := b, a+b
end
return(list)
end fibonacci
% Find the Zeckendorf representation of N
zeckendorf = proc (n: int) returns (string) signals (negative)
if n<0 then signal negative end
if n=0 then return("0") end
fibs: array[int] := fibonacci(n)
result: array[char] := array[char]$[]
while ~array[int]$empty(fibs) do
fib: int := array[int]$remh(fibs)
if fib <= n then
n := n - fib
array[char]$addh(result,'1')
else
array[char]$addh(result,'0')
end
end
return(string$ac2s(result))
end zeckendorf
% Print the Zeckendorf representations of 0 to 20
start_up = proc ()
po: stream := stream$primary_output()
for i: int in int$from_to(0,20) do
stream$putright(po, int$unparse(i), 2)
stream$puts(po, ": ")
stream$putl(po, zeckendorf(i))
end
end start_up |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Befunge | Befunge | >"d">:00p1-:>:::9%\9/9+g2%!\:9v
$.v_^#!$::$_^#`"c":+g00p+9/9\%<
::<_@#`$:\*:+55:+1p27g1g+9/9\%9
|
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #Dyalect | Dyalect | //Dyalect supports dynamic arrays
var empty = []
var xs = [1, 2, 3]
//Add elements to an array
empty.Add(0)
empty.AddRange(xs)
//Access array elements
var x = xs[2]
xs[2] = x * x |
http://rosettacode.org/wiki/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part", where the imaginary part is the number to be multiplied by
i
{\displaystyle i}
.
Task
Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.)
Print the results for each operation tested.
Optional: Show complex conjugation.
By definition, the complex conjugate of
a
+
b
i
{\displaystyle a+bi}
is
a
−
b
i
{\displaystyle a-bi}
Some languages have complex number libraries available. If your language does, show the operations. If your language does not, also show the definition of this type.
| #OCaml | OCaml | open Complex
let print_complex z =
Printf.printf "%f + %f i\n" z.re z.im
let () =
let a = { re = 1.0; im = 1.0 }
and b = { re = 3.14159; im = 1.25 } in
print_complex (add a b);
print_complex (mul a b);
print_complex (inv a);
print_complex (neg a);
print_complex (conj a) |
http://rosettacode.org/wiki/Arithmetic/Rational | Arithmetic/Rational | Task
Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language.
Example
Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number).
Further define the appropriate rational unary operators abs and '-', with the binary operators for addition '+', subtraction '-', multiplication '×', division '/', integer division '÷', modulo division, the comparison operators (e.g. '<', '≤', '>', & '≥') and equality operators (e.g. '=' & '≠').
Define standard coercion operators for casting int to frac etc.
If space allows, define standard increment and decrement operators (e.g. '+:=' & '-:=' etc.).
Finally test the operators:
Use the new type frac to find all perfect numbers less than 219 by summing the reciprocal of the factors.
Related task
Perfect Numbers
| #Phix | Phix | with javascript_semantics
without warning -- (several unused routines in this code)
constant NUM = 1, DEN = 2
type frac(object r)
return sequence(r) and length(r)=2 and integer(r[NUM]) and integer(r[DEN])
end type
function normalise(object n, atom d=0)
if sequence(n) then
{n,d} = n
end if
if d<0 then
n = -n
d = -d
end if
atom g = gcd(n,d)
return {n/g,d/g}
end function
function frac_new(integer n, d=1)
return normalise(n,d)
end function
function frac_abs(frac r)
return {abs(r[NUM]),r[DEN]}
end function
function frac_inv(frac r)
return reverse(r)
end function
function frac_add(frac a, b)
integer {an,ad} = a,
{bn,bd} = b
return normalise(an*bd+bn*ad, ad*bd)
end function
function frac_sub(frac a, b)
integer {an,ad} = a,
{bn,bd} = b
return normalise(an*bd-bn*ad, ad*bd)
end function
function frac_mul(frac a, b)
integer {an,ad} = a,
{bn,bd} = b
return normalise(an*bn, ad*bd)
end function
function frac_div(frac a, b)
integer {an,ad} = a,
{bn,bd} = b
return normalise(an*bd, ad*bn)
end function
function frac_eq(frac a, b)
return a==b
end function
function frac_ne(frac a, b)
return a!=b
end function
function frac_lt(frac a, b)
return frac_sub(a,b)[NUM]<0
end function
function frac_gt(frac a, b)
return frac_sub(a,b)[NUM]>0
end function
function frac_le(frac a, b)
return frac_sub(a,b)[NUM]<=0
end function
function frac_ge(frac a, b)
return frac_sub(a,b)[NUM]>=0
end function
function is_perfect(integer num)
frac total = frac_new(0)
sequence f = factors(num,1)
for i=1 to length(f) do
total = frac_add(total,frac_new(1,f[i]))
end for
return frac_eq(total,frac_new(2))
end function
procedure get_perfect_numbers()
atom t0 = time()
integer lim = power(2,iff(platform()=JS?13:19))
for i=2 to lim do
if is_perfect(i) then
printf(1,"perfect: %d\n",i)
end if
end for
printf(1,"elapsed: %3.2f seconds\n",time()-t0)
integer pn5 = power(2,12)*(power(2,13)-1) -- 5th perfect number
if is_perfect(pn5) then
printf(1,"perfect: %d\n",pn5)
end if
end procedure
get_perfect_numbers()
|
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geometric mean of two numbers.
The arithmetic-geometric mean of two numbers can be (usefully) denoted as
a
g
m
(
a
,
g
)
{\displaystyle \mathrm {agm} (a,g)}
, and is equal to the limit of the sequence:
a
0
=
a
;
g
0
=
g
{\displaystyle a_{0}=a;\qquad g_{0}=g}
a
n
+
1
=
1
2
(
a
n
+
g
n
)
;
g
n
+
1
=
a
n
g
n
.
{\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.}
Since the limit of
a
n
−
g
n
{\displaystyle a_{n}-g_{n}}
tends (rapidly) to zero with iterations, this is an efficient method.
Demonstrate the function by calculating:
a
g
m
(
1
,
1
/
2
)
{\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})}
Also see
mathworld.wolfram.com/Arithmetic-Geometric Mean
| #Ring | Ring |
decimals(9)
see agm(1, 1/sqrt(2)) + nl
see agm(1,1/pow(2,0.5)) + nl
func agm agm,g
while agm
an = (agm + g)/2
gn = sqrt(agm*g)
if fabs(agm-g) <= fabs(an-gn) exit ok
agm = an
g = gn
end
return gn
|
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geometric mean of two numbers.
The arithmetic-geometric mean of two numbers can be (usefully) denoted as
a
g
m
(
a
,
g
)
{\displaystyle \mathrm {agm} (a,g)}
, and is equal to the limit of the sequence:
a
0
=
a
;
g
0
=
g
{\displaystyle a_{0}=a;\qquad g_{0}=g}
a
n
+
1
=
1
2
(
a
n
+
g
n
)
;
g
n
+
1
=
a
n
g
n
.
{\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.}
Since the limit of
a
n
−
g
n
{\displaystyle a_{n}-g_{n}}
tends (rapidly) to zero with iterations, this is an efficient method.
Demonstrate the function by calculating:
a
g
m
(
1
,
1
/
2
)
{\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})}
Also see
mathworld.wolfram.com/Arithmetic-Geometric Mean
| #Ruby | Ruby | # The flt package (http://flt.rubyforge.org/) is useful for high-precision floating-point math.
# It lets us control 'context' of numbers, individually or collectively -- including precision
# (which adjusts the context's value of epsilon accordingly).
require 'flt'
include Flt
BinNum.Context.precision = 512 # default 53 (bits)
def agm(a,g)
new_a = BinNum a
new_g = BinNum g
while new_a - new_g > new_a.class.Context.epsilon do
old_g = new_g
new_g = (new_a * new_g).sqrt
new_a = (old_g + new_a) * 0.5
end
new_g
end
puts agm(1, 1 / BinNum(2).sqrt) |
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, you may also try something like:
x = 0
y = 0
z = x**y
say 'z=' z
Show the result here.
And of course use any symbols or notation that is supported in your computer programming language for exponentiation.
See also
The Wiki entry: Zero to the power of zero.
The Wiki entry: History of differing points of view.
The MathWorld™ entry: exponent laws.
Also, in the above MathWorld™ entry, see formula (9):
x
0
=
1
{\displaystyle x^{0}=1}
.
The OEIS entry: The special case of zero to the zeroth power
| #Elena | Elena | import extensions;
public program()
{
console.printLine("0^0 is ",0.power:0)
} |
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, you may also try something like:
x = 0
y = 0
z = x**y
say 'z=' z
Show the result here.
And of course use any symbols or notation that is supported in your computer programming language for exponentiation.
See also
The Wiki entry: Zero to the power of zero.
The Wiki entry: History of differing points of view.
The MathWorld™ entry: exponent laws.
Also, in the above MathWorld™ entry, see formula (9):
x
0
=
1
{\displaystyle x^{0}=1}
.
The OEIS entry: The special case of zero to the zeroth power
| #Elixir | Elixir |
:math.pow(0,0)
|
http://rosettacode.org/wiki/Arithmetic_evaluation | Arithmetic evaluation | Create a program which parses and evaluates arithmetic expressions.
Requirements
An abstract-syntax tree (AST) for the expression must be created from parsing the input.
The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.)
The expression will be a string or list of symbols like "(1+3)*7".
The four symbols + - * / must be supported as binary operators with conventional precedence rules.
Precedence-control parentheses must also be supported.
Note
For those who don't remember, mathematical precedence is as follows:
Parentheses
Multiplication/Division (left to right)
Addition/Subtraction (left to right)
C.f
24 game Player.
Parsing/RPN calculator algorithm.
Parsing/RPN to infix conversion.
| #Perl | Perl | sub ev
# Evaluates an arithmetic expression like "(1+3)*7" and returns
# its value.
{my $exp = shift;
# Delete all meaningless characters. (Scientific notation,
# infinity, and not-a-number aren't supported.)
$exp =~ tr {0-9.+-/*()} {}cd;
return ev_ast(astize($exp));}
{my $balanced_paren_regex;
$balanced_paren_regex = qr
{\( ( [^()]+ | (??{$balanced_paren_regex}) )+ \)}x;
# ??{ ... } interpolates lazily (only when necessary),
# permitting recursion to arbitrary depths.
sub astize
# Constructs an abstract syntax tree by recursively
# transforming textual arithmetic expressions into array
# references of the form [operator, left oprand, right oprand].
{my $exp = shift;
# If $exp is just a number, return it as-is.
$exp =~ /[^0-9.]/ or return $exp;
# If parentheses surround the entire expression, get rid of
# them.
$exp = substr($exp, 1, -1)
while $exp =~ /\A($balanced_paren_regex)\z/;
# Replace stuff in parentheses with placeholders.
my @paren_contents;
$exp =~ s {($balanced_paren_regex)}
{push(@paren_contents, $1);
"[p$#paren_contents]"}eg;
# Scan for operators in order of increasing precedence,
# preferring the rightmost.
$exp =~ m{(.+) ([+-]) (.+)}x or
$exp =~ m{(.+) ([*/]) (.+)}x or
# The expression must've been malformed somehow.
# (Note that unary minus isn't supported.)
die "Eh?: [$exp]\n";
my ($op, $lo, $ro) = ($2, $1, $3);
# Restore the parenthetical expressions.
s {\[p(\d+)\]} {($paren_contents[$1])}eg
foreach $lo, $ro;
# And recurse.
return [$op, astize($lo), astize($ro)];}}
{my %ops =
('+' => sub {$_[0] + $_[1]},
'-' => sub {$_[0] - $_[1]},
'*' => sub {$_[0] * $_[1]},
'/' => sub {$_[0] / $_[1]});
sub ev_ast
# Evaluates an abstract syntax tree of the form returned by
# &astize.
{my $ast = shift;
# If $ast is just a number, return it as-is.
ref $ast or return $ast;
# Otherwise, recurse.
my ($op, @operands) = @$ast;
$_ = ev_ast($_) foreach @operands;
return $ops{$op}->(@operands);}} |
http://rosettacode.org/wiki/Zeckendorf_arithmetic | Zeckendorf arithmetic | This task is a total immersion zeckendorf task; using decimal numbers will attract serious disapprobation.
The task is to implement addition, subtraction, multiplication, and division using Zeckendorf number representation. Optionally provide decrement, increment and comparitive operation functions.
Addition
Like binary 1 + 1 = 10, note carry 1 left. There the similarity ends. 10 + 10 = 101, note carry 1 left and 1 right. 100 + 100 = 1001, note carry 1 left and 2 right, this is the general case.
Occurrences of 11 must be changed to 100. Occurrences of 111 may be changed from the right by replacing 11 with 100, or from the left converting 111 to 100 + 100;
Subtraction
10 - 1 = 1. The general rule is borrow 1 right carry 1 left. eg:
abcde
10100 -
1000
_____
100 borrow 1 from a leaves 100
+ 100 add the carry
_____
1001
A larger example:
abcdef
100100 -
1000
______
1*0100 borrow 1 from b
+ 100 add the carry
______
1*1001
Sadly we borrowed 1 from b which didn't have it to lend. So now b borrows from a:
1001
+ 1000 add the carry
____
10100
Multiplication
Here you teach your computer its zeckendorf tables. eg. 101 * 1001:
a = 1 * 101 = 101
b = 10 * 101 = a + a = 10000
c = 100 * 101 = b + a = 10101
d = 1000 * 101 = c + b = 101010
1001 = d + a therefore 101 * 1001 =
101010
+ 101
______
1000100
Division
Lets try 1000101 divided by 101, so we can use the same table used for multiplication.
1000101 -
101010 subtract d (1000 * 101)
_______
1000 -
101 b and c are too large to subtract, so subtract a
____
1 so 1000101 divided by 101 is d + a (1001) remainder 1
Efficient algorithms for Zeckendorf arithmetic is interesting. The sections on addition and subtraction are particularly relevant for this task.
| #C.2B.2B | C++ | // For a class N which implements Zeckendorf numbers:
// I define an increment operation ++()
// I define a comparison operation <=(other N)
// I define an addition operation +=(other N)
// I define a subtraction operation -=(other N)
// Nigel Galloway October 28th., 2012
#include <iostream>
enum class zd {N00,N01,N10,N11};
class N {
private:
int dVal = 0, dLen;
void _a(int i) {
for (;; i++) {
if (dLen < i) dLen = i;
switch ((zd)((dVal >> (i*2)) & 3)) {
case zd::N00: case zd::N01: return;
case zd::N10: if (((dVal >> ((i+1)*2)) & 1) != 1) return;
dVal += (1 << (i*2+1)); return;
case zd::N11: dVal &= ~(3 << (i*2)); _b((i+1)*2);
}}}
void _b(int pos) {
if (pos == 0) {++*this; return;}
if (((dVal >> pos) & 1) == 0) {
dVal += 1 << pos;
_a(pos/2);
if (pos > 1) _a((pos/2)-1);
} else {
dVal &= ~(1 << pos);
_b(pos + 1);
_b(pos - ((pos > 1)? 2:1));
}}
void _c(int pos) {
if (((dVal >> pos) & 1) == 1) {dVal &= ~(1 << pos); return;}
_c(pos + 1);
if (pos > 0) _b(pos - 1); else ++*this;
return;
}
public:
N(char const* x = "0") {
int i = 0, q = 1;
for (; x[i] > 0; i++);
for (dLen = --i/2; i >= 0; i--) {dVal+=(x[i]-48)*q; q*=2;
}}
const N& operator++() {dVal += 1; _a(0); return *this;}
const N& operator+=(const N& other) {
for (int GN = 0; GN < (other.dLen + 1) * 2; GN++) if ((other.dVal >> GN) & 1 == 1) _b(GN);
return *this;
}
const N& operator-=(const N& other) {
for (int GN = 0; GN < (other.dLen + 1) * 2; GN++) if ((other.dVal >> GN) & 1 == 1) _c(GN);
for (;((dVal >> dLen*2) & 3) == 0 or dLen == 0; dLen--);
return *this;
}
const N& operator*=(const N& other) {
N Na = other, Nb = other, Nt, Nr;
for (int i = 0; i <= (dLen + 1) * 2; i++) {
if (((dVal >> i) & 1) > 0) Nr += Nb;
Nt = Nb; Nb += Na; Na = Nt;
}
return *this = Nr;
}
const bool operator<=(const N& other) const {return dVal <= other.dVal;}
friend std::ostream& operator<<(std::ostream&, const N&);
};
N operator "" N(char const* x) {return N(x);}
std::ostream &operator<<(std::ostream &os, const N &G) {
const static std::string dig[] {"00","01","10"}, dig1[] {"","1","10"};
if (G.dVal == 0) return os << "0";
os << dig1[(G.dVal >> (G.dLen*2)) & 3];
for (int i = G.dLen-1; i >= 0; i--) os << dig[(G.dVal >> (i*2)) & 3];
return os;
}
|
http://rosettacode.org/wiki/Zumkeller_numbers | Zumkeller numbers | Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the divisors are partitioned, only that the two partition sums are equal.
E.G.
6 is a Zumkeller number; The divisors {1 2 3 6} can be partitioned into two groups {1 2 3} and {6} that both sum to 6.
10 is not a Zumkeller number; The divisors {1 2 5 10} can not be partitioned into two groups in any way that will both sum to the same value.
12 is a Zumkeller number; The divisors {1 2 3 4 6 12} can be partitioned into two groups {1 3 4 6} and {2 12} that both sum to 14.
Even Zumkeller numbers are common; odd Zumkeller numbers are much less so. For values below 10^6, there is at least one Zumkeller number in every 12 consecutive integers, and the vast majority of them are even. The odd Zumkeller numbers are very similar to the list from the task Abundant odd numbers; they are nearly the same except for the further restriction that the abundance (A(n) = sigma(n) - 2n), must be even: A(n) mod 2 == 0
Task
Write a routine (function, procedure, whatever) to find Zumkeller numbers.
Use the routine to find and display here, on this page, the first 220 Zumkeller numbers.
Use the routine to find and display here, on this page, the first 40 odd Zumkeller numbers.
Optional, stretch goal: Use the routine to find and display here, on this page, the first 40 odd Zumkeller numbers that don't end with 5.
See Also
OEIS:A083207 - Zumkeller numbers to get an impression of different partitions OEIS:A083206 Zumkeller partitions
OEIS:A174865 - Odd Zumkeller numbers
Related Tasks
Abundant odd numbers
Abundant, deficient and perfect number classifications
Proper divisors , Factors of an integer | #D | D | import std.algorithm;
import std.stdio;
int[] getDivisors(int n) {
auto divs = [1, n];
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) {
divs ~= i;
int j = n / i;
if (i != j) {
divs ~= j;
}
}
}
return divs;
}
bool isPartSum(int[] divs, int sum) {
if (sum == 0) {
return true;
}
auto le = divs.length;
if (le == 0) {
return false;
}
auto last = divs[$ - 1];
int[] newDivs;
for (int i = 0; i < le - 1; i++) {
newDivs ~= divs[i];
}
if (last > sum) {
return isPartSum(newDivs, sum);
} else {
return isPartSum(newDivs, sum) || isPartSum(newDivs, sum - last);
}
}
bool isZumkeller(int n) {
auto divs = getDivisors(n);
auto sum = divs.sum();
// if sum is odd can't be split into two partitions with equal sums
if (sum % 2 == 1) {
return false;
}
// if n is odd use 'abundant odd number' optimization
if (n % 2 == 1) {
auto abundance = sum - 2 * n;
return abundance > 0 && abundance % 2 == 0;
}
// if n and sum are both even check if there's a partition which totals sum / 2
return isPartSum(divs, sum / 2);
}
void main() {
writeln("The first 220 Zumkeller numbers are:");
int i = 2;
for (int count = 0; count < 220; i++) {
if (isZumkeller(i)) {
writef("%3d ", i);
count++;
if (count % 20 == 0) {
writeln;
}
}
}
writeln("\nThe first 40 odd Zumkeller numbers are:");
i = 3;
for (int count = 0; count < 40; i += 2) {
if (isZumkeller(i)) {
writef("%5d ", i);
count++;
if (count % 10 == 0) {
writeln;
}
}
}
writeln("\nThe first 40 odd Zumkeller numbers which don't end in 5 are:");
i = 3;
for (int count = 0; count < 40; i += 2) {
if (i % 10 != 5 && isZumkeller(i)) {
writef("%7d ", i);
count++;
if (count % 8 == 0) {
writeln;
}
}
}
} |
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included) | Arbitrary-precision integers (included) | Using the in-built capabilities of your language, calculate the integer value of:
5
4
3
2
{\displaystyle 5^{4^{3^{2}}}}
Confirm that the first and last twenty digits of the answer are:
62060698786608744707...92256259918212890625
Find and show the number of decimal digits in the answer.
Note: Do not submit an implementation of arbitrary precision arithmetic. The intention is to show the capabilities of the language as supplied. If a language has a single, overwhelming, library of varied modules that is endorsed by its home site – such as CPAN for Perl or Boost for C++ – then that may be used instead.
Strictly speaking, this should not be solved by fixed-precision numeric libraries where the precision has to be manually set to a large value; although if this is the only recourse then it may be used with a note explaining that the precision must be set manually to a large enough value.
Related tasks
Long multiplication
Exponentiation order
exponentiation operator
Exponentiation with infix operators in (or operating on) the base
| #bc | bc | /* 5432.bc */
y = 5 ^ 4 ^ 3 ^ 2
c = length(y)
" First 20 digits: "; y / (10 ^ (c - 20))
" Last 20 digits: "; y % (10 ^ 20)
"Number of digits: "; c
quit |
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included) | Arbitrary-precision integers (included) | Using the in-built capabilities of your language, calculate the integer value of:
5
4
3
2
{\displaystyle 5^{4^{3^{2}}}}
Confirm that the first and last twenty digits of the answer are:
62060698786608744707...92256259918212890625
Find and show the number of decimal digits in the answer.
Note: Do not submit an implementation of arbitrary precision arithmetic. The intention is to show the capabilities of the language as supplied. If a language has a single, overwhelming, library of varied modules that is endorsed by its home site – such as CPAN for Perl or Boost for C++ – then that may be used instead.
Strictly speaking, this should not be solved by fixed-precision numeric libraries where the precision has to be manually set to a large value; although if this is the only recourse then it may be used with a note explaining that the precision must be set manually to a large enough value.
Related tasks
Long multiplication
Exponentiation order
exponentiation operator
Exponentiation with infix operators in (or operating on) the base
| #Bracmat | Bracmat | {?} @(5^4^3^2:?first [20 ? [-21 ?last [?length)&str$(!first "..." !last "\nlength " !length)
{!} 62060698786608744707...92256259918212890625
length 183231
S 2,46 sec |
http://rosettacode.org/wiki/Zhang-Suen_thinning_algorithm | Zhang-Suen thinning algorithm | This is an algorithm used to thin a black and white i.e. one bit per pixel images.
For example, with an input image of:
################# #############
################## ################
################### ##################
######## ####### ###################
###### ####### ####### ######
###### ####### #######
################# #######
################ #######
################# #######
###### ####### #######
###### ####### #######
###### ####### ####### ######
######## ####### ###################
######## ####### ###### ################## ######
######## ####### ###### ################ ######
######## ####### ###### ############# ######
It produces the thinned output:
# ########## #######
## # #### #
# # ##
# # #
# # #
# # #
############ #
# # #
# # #
# # #
# # #
# ##
# ############
### ###
Algorithm
Assume black pixels are one and white pixels zero, and that the input image is a rectangular N by M array of ones and zeroes.
The algorithm operates on all black pixels P1 that can have eight neighbours.
The neighbours are, in order, arranged as:
P9 P2 P3
P8 P1 P4
P7 P6 P5
Obviously the boundary pixels of the image cannot have the full eight neighbours.
Define
A
(
P
1
)
{\displaystyle A(P1)}
= the number of transitions from white to black, (0 -> 1) in the sequence P2,P3,P4,P5,P6,P7,P8,P9,P2. (Note the extra P2 at the end - it is circular).
Define
B
(
P
1
)
{\displaystyle B(P1)}
= The number of black pixel neighbours of P1. ( = sum(P2 .. P9) )
Step 1
All pixels are tested and pixels satisfying all the following conditions (simultaneously) are just noted at this stage.
(0) The pixel is black and has eight neighbours
(1)
2
<=
B
(
P
1
)
<=
6
{\displaystyle 2<=B(P1)<=6}
(2) A(P1) = 1
(3) At least one of P2 and P4 and P6 is white
(4) At least one of P4 and P6 and P8 is white
After iterating over the image and collecting all the pixels satisfying all step 1 conditions, all these condition satisfying pixels are set to white.
Step 2
All pixels are again tested and pixels satisfying all the following conditions are just noted at this stage.
(0) The pixel is black and has eight neighbours
(1)
2
<=
B
(
P
1
)
<=
6
{\displaystyle 2<=B(P1)<=6}
(2) A(P1) = 1
(3) At least one of P2 and P4 and P8 is white
(4) At least one of P2 and P6 and P8 is white
After iterating over the image and collecting all the pixels satisfying all step 2 conditions, all these condition satisfying pixels are again set to white.
Iteration
If any pixels were set in this round of either step 1 or step 2 then all steps are repeated until no image pixels are so changed.
Task
Write a routine to perform Zhang-Suen thinning on an image matrix of ones and zeroes.
Use the routine to thin the following image and show the output here on this page as either a matrix of ones and zeroes, an image, or an ASCII-art image of space/non-space characters.
00000000000000000000000000000000
01111111110000000111111110000000
01110001111000001111001111000000
01110000111000001110000111000000
01110001111000001110000000000000
01111111110000001110000000000000
01110111100000001110000111000000
01110011110011101111001111011100
01110001111011100111111110011100
00000000000000000000000000000000
Reference
Zhang-Suen Thinning Algorithm, Java Implementation by Nayef Reza.
"Character Recognition Systems: A Guide for Students and Practitioners" By Mohamed Cheriet, Nawwaf Kharma, Cheng-Lin Liu, Ching Suen
| #Groovy | Groovy | def zhangSuen(text) {
def image = text.split('\n').collect { line -> line.collect { it == '#' ? 1 : 0} }
def p2, p3, p4, p5, p6, p7, p8, p9
def step1 = { (p2 * p4 * p6 == 0) && (p4 * p6 * p8 == 0) }
def step2 = { (p2 * p4 * p8 == 0) && (p2 * p6 * p8 == 0) }
def reduce = { step ->
def toWhite = []
image.eachWithIndex{ line, y ->
line.eachWithIndex{ pixel, x ->
if (!pixel) return
(p2, p3, p4, p5, p6, p7, p8, p9) = [image[y-1][x], image[y-1][x+1], image[y][x+1], image[y+1][x+1], image[y+1][x], image[y+1][x-1], image[y][x-1], image[y-1][x-1]]
def a = [[p2,p3],[p3,p4],[p4,p5],[p5,p6],[p6,p7],[p7,p8],[p8,p9],[p9,p2]].collect { a1, a2 -> (a1 == 0 && a2 ==1) ? 1 : 0 }.sum()
def b = [p2, p3, p4, p5, p6, p7, p8, p9].sum()
if (a != 1 || b < 2 || b > 6) return
if (step.call()) toWhite << [y,x]
}
}
toWhite.each { y, x -> image[y][x] = 0 }
!toWhite.isEmpty()
}
while (reduce(step1) | reduce(step2));
image.collect { line -> line.collect { it ? '#' : '.' }.join('') }.join('\n')
} |
http://rosettacode.org/wiki/Zeckendorf_number_representation | Zeckendorf number representation | Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series.
Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13.
The decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100.
10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that no two consecutive Fibonacci numbers can be used which leads to the former unique solution.
Task
Generate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order.
The intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task.
Also see
OEIS A014417 for the the sequence of required results.
Brown's Criterion - Numberphile
Related task
Fibonacci sequence
| #Common_Lisp | Common Lisp | (defun zeckendorf (n)
"returns zeckendorf integer of n (see OEIS A003714)"
(let ((fib '(2 1)))
;; extend Fibonacci sequence long enough
(loop while (<= (car fib) n) do
(push (+ (car fib) (cadr fib)) fib))
(loop with r = 0 for f in fib do
(setf r (* 2 r))
(when (>= n f) (setf n (- n f))
(incf r))
finally (return r))))
;;; task requirement
(loop for i from 0 to 20 do
(format t "~2D: ~2R~%" i (zeckendorf i))) |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Blade | Blade | var doors = [false] * 100
for i in 0..100 {
iter var j = i; j < 100; j += i + 1 {
doors[j] = !doors[j]
}
var state = doors[i] ? 'open' : 'closed'
echo 'Door ${i + 1} is ${state}'
} |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #D.C3.A9j.C3.A0_Vu | Déjà Vu | #create a new list
local :l []
#add something to it
push-to l "Hi"
#add something else to it
push-to l "Boo"
#the list could also have been built up this way:
local :l2 [ "Hi" "Boo" ]
#this prints 2
!print len l
#this prints Hi
!print get-from l 0
#this prints Boo
!print pop-from l
|
http://rosettacode.org/wiki/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part", where the imaginary part is the number to be multiplied by
i
{\displaystyle i}
.
Task
Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.)
Print the results for each operation tested.
Optional: Show complex conjugation.
By definition, the complex conjugate of
a
+
b
i
{\displaystyle a+bi}
is
a
−
b
i
{\displaystyle a-bi}
Some languages have complex number libraries available. If your language does, show the operations. If your language does not, also show the definition of this type.
| #Octave | Octave | z1 = 1.5 + 3i;
z2 = 1.5 + 1.5i;
disp(z1 + z2); % 3.0 + 4.5i
disp(z1 - z2); % 0.0 + 1.5i
disp(z1 * z2); % -2.25 + 6.75i
disp(z1 / z2); % 1.5 + 0.5i
disp(-z1); % -1.5 - 3i
disp(z1'); % 1.5 - 3i
disp(abs(z1)); % 3.3541 = sqrt(z1*z1')
disp(z1 ^ z2); % -1.10248 - 0.38306i
disp( exp(z1) ); % -4.43684 + 0.63246i
disp( imag(z1) ); % 3
disp( real(z2) ); % 1.5
%... |
http://rosettacode.org/wiki/Arithmetic/Rational | Arithmetic/Rational | Task
Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language.
Example
Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number).
Further define the appropriate rational unary operators abs and '-', with the binary operators for addition '+', subtraction '-', multiplication '×', division '/', integer division '÷', modulo division, the comparison operators (e.g. '<', '≤', '>', & '≥') and equality operators (e.g. '=' & '≠').
Define standard coercion operators for casting int to frac etc.
If space allows, define standard increment and decrement operators (e.g. '+:=' & '-:=' etc.).
Finally test the operators:
Use the new type frac to find all perfect numbers less than 219 by summing the reciprocal of the factors.
Related task
Perfect Numbers
| #PicoLisp | PicoLisp | (load "@lib/frac.l")
(for (N 2 (> (** 2 19) N) (inc N))
(let (Sum (frac 1 N) Lim (sqrt N))
(for (F 2 (>= Lim F) (inc F))
(when (=0 (% N F))
(setq Sum
(f+ Sum
(f+ (frac 1 F) (frac 1 (/ N F))) ) ) ) )
(when (= 1 (cdr Sum))
(prinl
"Perfect " N
", sum is " (car Sum)
(and (= 1 (car Sum)) ": perfect") ) ) ) ) |
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geometric mean of two numbers.
The arithmetic-geometric mean of two numbers can be (usefully) denoted as
a
g
m
(
a
,
g
)
{\displaystyle \mathrm {agm} (a,g)}
, and is equal to the limit of the sequence:
a
0
=
a
;
g
0
=
g
{\displaystyle a_{0}=a;\qquad g_{0}=g}
a
n
+
1
=
1
2
(
a
n
+
g
n
)
;
g
n
+
1
=
a
n
g
n
.
{\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.}
Since the limit of
a
n
−
g
n
{\displaystyle a_{n}-g_{n}}
tends (rapidly) to zero with iterations, this is an efficient method.
Demonstrate the function by calculating:
a
g
m
(
1
,
1
/
2
)
{\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})}
Also see
mathworld.wolfram.com/Arithmetic-Geometric Mean
| #Run_BASIC | Run BASIC | print agm(1, 1/sqr(2))
print agm(1,1/2^.5)
print using("#.############################",agm(1, 1/sqr(2)))
function agm(agm,g)
while agm
an = (agm + g)/2
gn = sqr(agm*g)
if abs(agm-g) <= abs(an-gn) then exit while
agm = an
g = gn
wend
end function |
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geometric mean of two numbers.
The arithmetic-geometric mean of two numbers can be (usefully) denoted as
a
g
m
(
a
,
g
)
{\displaystyle \mathrm {agm} (a,g)}
, and is equal to the limit of the sequence:
a
0
=
a
;
g
0
=
g
{\displaystyle a_{0}=a;\qquad g_{0}=g}
a
n
+
1
=
1
2
(
a
n
+
g
n
)
;
g
n
+
1
=
a
n
g
n
.
{\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.}
Since the limit of
a
n
−
g
n
{\displaystyle a_{n}-g_{n}}
tends (rapidly) to zero with iterations, this is an efficient method.
Demonstrate the function by calculating:
a
g
m
(
1
,
1
/
2
)
{\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})}
Also see
mathworld.wolfram.com/Arithmetic-Geometric Mean
| #Rust | Rust | // Accepts two command line arguments
// cargo run --name agm arg1 arg2
fn main () {
let mut args = std::env::args();
let x = args.nth(1).expect("First argument not specified.").parse::<f32>().unwrap();
let y = args.next().expect("Second argument not specified.").parse::<f32>().unwrap();
let result = agm(x,y);
println!("The arithmetic-geometric mean is {}", result);
}
fn agm (x: f32, y: f32) -> f32 {
let e: f32 = 0.000001;
let mut a = x;
let mut g = y;
let mut a1: f32;
let mut g1: f32;
if a * g < 0f32 { panic!("The arithmetric-geometric mean is undefined for numbers less than zero!"); }
else {
loop {
a1 = (a + g) / 2.;
g1 = (a * g).sqrt();
a = a1;
g = g1;
if (a - g).abs() < e { return a; }
}
}
} |
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, you may also try something like:
x = 0
y = 0
z = x**y
say 'z=' z
Show the result here.
And of course use any symbols or notation that is supported in your computer programming language for exponentiation.
See also
The Wiki entry: Zero to the power of zero.
The Wiki entry: History of differing points of view.
The MathWorld™ entry: exponent laws.
Also, in the above MathWorld™ entry, see formula (9):
x
0
=
1
{\displaystyle x^{0}=1}
.
The OEIS entry: The special case of zero to the zeroth power
| #Emacs_Lisp | Emacs Lisp | (expt 0 0) |
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, you may also try something like:
x = 0
y = 0
z = x**y
say 'z=' z
Show the result here.
And of course use any symbols or notation that is supported in your computer programming language for exponentiation.
See also
The Wiki entry: Zero to the power of zero.
The Wiki entry: History of differing points of view.
The MathWorld™ entry: exponent laws.
Also, in the above MathWorld™ entry, see formula (9):
x
0
=
1
{\displaystyle x^{0}=1}
.
The OEIS entry: The special case of zero to the zeroth power
| #ERRE | ERRE |
.....
PRINT(0^0)
.....
|
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, you may also try something like:
x = 0
y = 0
z = x**y
say 'z=' z
Show the result here.
And of course use any symbols or notation that is supported in your computer programming language for exponentiation.
See also
The Wiki entry: Zero to the power of zero.
The Wiki entry: History of differing points of view.
The MathWorld™ entry: exponent laws.
Also, in the above MathWorld™ entry, see formula (9):
x
0
=
1
{\displaystyle x^{0}=1}
.
The OEIS entry: The special case of zero to the zeroth power
| #F.23 | F# | > let z = 0.**0.;;
val z : float = 1.0 |
http://rosettacode.org/wiki/Zig-zag_matrix | Zig-zag matrix | Task
Produce a zig-zag array.
A zig-zag array is a square arrangement of the first N2 natural numbers, where the
numbers increase sequentially as you zig-zag along the array's anti-diagonals.
For a graphical representation, see JPG zigzag (JPG uses such arrays to encode images).
For example, given 5, produce this array:
0 1 5 6 14
2 4 7 13 15
3 8 12 16 21
9 11 17 20 22
10 18 19 23 24
Related tasks
Spiral matrix
Identity matrix
Ulam spiral (for primes)
See also
Wiktionary entry: anti-diagonals
| #11l | 11l | F zigzag(n)
F compare(xy)
V (x, y) = xy
R (x + y, I (x + y) % 2 {-y} E y)
V xs = 0 .< n
R Dict(enumerate(sorted((multiloop(xs, xs, (x, y) -> (x, y))), key' compare)), (n, index) -> (index, n))
F printzz(myarray)
V n = Int(myarray.len ^ 0.5 + 0.5)
V xs = 0 .< n
print((xs.map(y -> @xs.map(x -> ‘#3’.format(@@myarray[(x, @y)])).join(‘’))).join("\n"))
printzz(zigzag(6)) |
http://rosettacode.org/wiki/Arithmetic_evaluation | Arithmetic evaluation | Create a program which parses and evaluates arithmetic expressions.
Requirements
An abstract-syntax tree (AST) for the expression must be created from parsing the input.
The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.)
The expression will be a string or list of symbols like "(1+3)*7".
The four symbols + - * / must be supported as binary operators with conventional precedence rules.
Precedence-control parentheses must also be supported.
Note
For those who don't remember, mathematical precedence is as follows:
Parentheses
Multiplication/Division (left to right)
Addition/Subtraction (left to right)
C.f
24 game Player.
Parsing/RPN calculator algorithm.
Parsing/RPN to infix conversion.
| #Phix | Phix | -- demo\rosetta\Arithmetic_evaluation.exw
with javascript_semantics
sequence opstack = {} -- atom elements are literals,
-- sequence elements are subexpressions
-- on completion length(opstack) should be 1
object token
constant op_p_p = 1 -- 1: expressions stored as op,p1,p2
-- p_op_p -- 0: expressions stored as p1,op,p2
-- p_p_op -- -1: expressions stored as p1,p2,op
object op = 0 -- 0 if none, else "+", "-", "*", "/", "^", "%", or "u-"
string s -- the expression being parsed
integer ch
integer sidx
procedure err(string msg)
printf(1,"%s\n%s^ %s\n\nPressEnter...",{s,repeat(' ',sidx-1),msg})
{} = wait_key()
abort(0)
end procedure
procedure nxtch(object msg="eof")
sidx += 1
if sidx>length(s) then
if string(msg) then err(msg) end if
ch = -1
else
ch = s[sidx]
end if
end procedure
procedure skipspaces()
while find(ch,{' ','\t','\r','\n'})!=0 do nxtch(0) end while
end procedure
procedure get_token()
atom n, fraction
integer dec
skipspaces()
if ch=-1 then token = "eof" return end if
if ch>='0' and ch<='9' then
n = ch-'0'
while 1 do
nxtch(0)
if ch<'0' or ch>'9' then exit end if
n = n*10+ch-'0'
end while
if ch='.' then
dec = 1
fraction = 0
while 1 do
nxtch(0)
if ch<'0' or ch>'9' then exit end if
fraction = fraction*10 + ch-'0'
dec *= 10
end while
n += fraction/dec
end if
-- if find(ch,"eE") then -- you get the idea
-- end if
token = n
return
end if
if find(ch,"+-/*()^%")=0 then err("syntax error") end if
token = s[sidx..sidx]
nxtch(0)
return
end procedure
procedure Match(string t)
if token!=t then err(t&" expected") end if
get_token()
end procedure
procedure PopFactor()
object p1, p2 = opstack[$]
if op="u-" then
p1 = 0
else
opstack = opstack[1..$-1]
p1 = opstack[$]
end if
if op_p_p=1 then
opstack[$] = {op,p1,p2} -- op_p_p
elsif op_p_p=0 then
opstack[$] = {p1,op,p2} -- p_op_p
else -- -1
opstack[$] = {p1,p2,op} -- p_p_op
end if
op = 0
end procedure
procedure PushFactor(atom t)
if op!=0 then PopFactor() end if
opstack = append(opstack,t)
end procedure
procedure PushOp(string t)
if op!=0 then PopFactor() end if
op = t
end procedure
forward procedure Expr(integer p)
procedure Factor()
if atom(token) then
PushFactor(token)
if ch!=-1 then
get_token()
end if
elsif token="+" then -- (ignore)
nxtch()
Factor()
elsif token="-" then
get_token()
-- Factor()
Expr(3) -- makes "-3^2" yield -9 (ie -(3^2)) not 9 (ie (-3)^2).
if op!=0 then PopFactor() end if
if integer(opstack[$]) then
opstack[$] = -opstack[$]
else
PushOp("u-")
end if
elsif token="(" then
get_token()
Expr(0)
Match(")")
else
err("syntax error")
end if
end procedure
constant {operators,
precedence,
associativity} = columnize({{"^",3,0},
{"%",2,1},
{"*",2,1},
{"/",2,1},
{"+",1,1},
{"-",1,1},
$})
procedure Expr(integer p)
--
-- Parse an expression, using precedence climbing.
--
-- p is the precedence level we should parse to, eg/ie
-- 4: Factor only (may as well just call Factor)
-- 3: "" and ^
-- 2: "" and *,/,%
-- 1: "" and +,-
-- 0: full expression (effectively the same as 1)
-- obviously, parentheses override any setting of p.
--
integer k, thisp
Factor()
while 1 do
k = find(token,operators) -- *,/,+,-
if k=0 then exit end if
thisp = precedence[k]
if thisp<p then exit end if
get_token()
Expr(thisp+associativity[k])
PushOp(operators[k])
end while
end procedure
function evaluate(object s)
object lhs, rhs
string op
if atom(s) then
return s
end if
if op_p_p=1 then -- op_p_p
{op,lhs,rhs} = s
elsif op_p_p=0 then -- p_op_p
{lhs,op,rhs} = s
else -- -1 -- p_p_op
{lhs,rhs,op} = s
end if
if sequence(lhs) then lhs = evaluate(lhs) end if
if sequence(rhs) then rhs = evaluate(rhs) end if
if op="+" then
return lhs+rhs
elsif op="-" then
return lhs-rhs
elsif op="*" then
return lhs*rhs
elsif op="/" then
return lhs/rhs
elsif op="^" then
return power(lhs,rhs)
elsif op="%" then
return remainder(lhs,rhs)
elsif op="u-" then
return -rhs
else
?9/0
end if
end function
s = "3+4+5+6*7/1*5^2^3" -- 16406262
sidx = 0
nxtch()
get_token()
Expr(0)
if op!=0 then PopFactor() end if
if length(opstack)!=1 then err("some error") end if
printf(1,"expression: \"%s\"\n",{s})
puts(1,"AST (flat): ")
?opstack[1]
puts(1,"AST (tree):\n")
ppEx(opstack[1],{pp_Nest,9999})
puts(1,"result: ")
?evaluate(opstack[1])
{} = wait_key()
|
http://rosettacode.org/wiki/Zeckendorf_arithmetic | Zeckendorf arithmetic | This task is a total immersion zeckendorf task; using decimal numbers will attract serious disapprobation.
The task is to implement addition, subtraction, multiplication, and division using Zeckendorf number representation. Optionally provide decrement, increment and comparitive operation functions.
Addition
Like binary 1 + 1 = 10, note carry 1 left. There the similarity ends. 10 + 10 = 101, note carry 1 left and 1 right. 100 + 100 = 1001, note carry 1 left and 2 right, this is the general case.
Occurrences of 11 must be changed to 100. Occurrences of 111 may be changed from the right by replacing 11 with 100, or from the left converting 111 to 100 + 100;
Subtraction
10 - 1 = 1. The general rule is borrow 1 right carry 1 left. eg:
abcde
10100 -
1000
_____
100 borrow 1 from a leaves 100
+ 100 add the carry
_____
1001
A larger example:
abcdef
100100 -
1000
______
1*0100 borrow 1 from b
+ 100 add the carry
______
1*1001
Sadly we borrowed 1 from b which didn't have it to lend. So now b borrows from a:
1001
+ 1000 add the carry
____
10100
Multiplication
Here you teach your computer its zeckendorf tables. eg. 101 * 1001:
a = 1 * 101 = 101
b = 10 * 101 = a + a = 10000
c = 100 * 101 = b + a = 10101
d = 1000 * 101 = c + b = 101010
1001 = d + a therefore 101 * 1001 =
101010
+ 101
______
1000100
Division
Lets try 1000101 divided by 101, so we can use the same table used for multiplication.
1000101 -
101010 subtract d (1000 * 101)
_______
1000 -
101 b and c are too large to subtract, so subtract a
____
1 so 1000101 divided by 101 is d + a (1001) remainder 1
Efficient algorithms for Zeckendorf arithmetic is interesting. The sections on addition and subtraction are particularly relevant for this task.
| #D | D | import std.stdio;
int inv(int a) {
return a ^ -1;
}
class Zeckendorf {
private int dVal;
private int dLen;
private void a(int n) {
auto i = n;
while (true) {
if (dLen < i) dLen = i;
auto j = (dVal >> (i * 2)) & 3;
switch(j) {
case 0:
case 1:
return;
case 2:
if (((dVal >> ((i + 1) * 2)) & 1) != 1) return;
dVal += 1 << (i * 2 + 1);
return;
case 3:
dVal = dVal & (3 << (i * 2)).inv();
b((i + 1) * 2);
break;
default:
assert(false);
}
i++;
}
}
private void b(int pos) {
if (pos == 0) {
this++;
return;
}
if (((dVal >> pos) & 1) == 0) {
dVal += 1 << pos;
a(pos / 2);
if (pos > 1) a(pos / 2 - 1);
} else {
dVal = dVal & (1 << pos).inv();
b(pos + 1);
b(pos - (pos > 1 ? 2 : 1));
}
}
private void c(int pos) {
if (((dVal >> pos) & 1) == 1) {
dVal = dVal & (1 << pos).inv();
return;
}
c(pos + 1);
if (pos > 0) {
b(pos - 1);
} else {
++this;
}
}
this(string x = "0") {
int q = 1;
int i = x.length - 1;
dLen = i / 2;
while (i >= 0) {
dVal += (x[i] - '0') * q;
q *= 2;
i--;
}
}
auto opUnary(string op : "++")() {
dVal += 1;
a(0);
return this;
}
void opOpAssign(string op : "+")(Zeckendorf rhs) {
foreach (gn; 0..(rhs.dLen + 1) * 2) {
if (((rhs.dVal >> gn) & 1) == 1) {
b(gn);
}
}
}
void opOpAssign(string op : "-")(Zeckendorf rhs) {
foreach (gn; 0..(rhs.dLen + 1) * 2) {
if (((rhs.dVal >> gn) & 1) == 1) {
c(gn);
}
}
while ((((dVal >> dLen * 2) & 3) == 0) || (dLen == 0)) {
dLen--;
}
}
void opOpAssign(string op : "*")(Zeckendorf rhs) {
auto na = rhs.dup;
auto nb = rhs.dup;
Zeckendorf nt;
auto nr = "0".Z;
foreach (i; 0..(dLen + 1) * 2) {
if (((dVal >> i) & 1) > 0) nr += nb;
nt = nb.dup;
nb += na;
na = nt.dup;
}
dVal = nr.dVal;
dLen = nr.dLen;
}
void toString(scope void delegate(const(char)[]) sink) const {
if (dVal == 0) {
sink("0");
return;
}
sink(dig1[(dVal >> (dLen * 2)) & 3]);
foreach_reverse (i; 0..dLen) {
sink(dig[(dVal >> (i * 2)) & 3]);
}
}
Zeckendorf dup() {
auto z = "0".Z;
z.dVal = dVal;
z.dLen = dLen;
return z;
}
enum dig = ["00", "01", "10"];
enum dig1 = ["", "1", "10"];
}
auto Z(string val) {
return new Zeckendorf(val);
}
void main() {
writeln("Addition:");
auto g = "10".Z;
g += "10".Z;
writeln(g);
g += "10".Z;
writeln(g);
g += "1001".Z;
writeln(g);
g += "1000".Z;
writeln(g);
g += "10101".Z;
writeln(g);
writeln();
writeln("Subtraction:");
g = "1000".Z;
g -= "101".Z;
writeln(g);
g = "10101010".Z;
g -= "1010101".Z;
writeln(g);
writeln();
writeln("Multiplication:");
g = "1001".Z;
g *= "101".Z;
writeln(g);
g = "101010".Z;
g += "101".Z;
writeln(g);
} |
http://rosettacode.org/wiki/Zumkeller_numbers | Zumkeller numbers | Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the divisors are partitioned, only that the two partition sums are equal.
E.G.
6 is a Zumkeller number; The divisors {1 2 3 6} can be partitioned into two groups {1 2 3} and {6} that both sum to 6.
10 is not a Zumkeller number; The divisors {1 2 5 10} can not be partitioned into two groups in any way that will both sum to the same value.
12 is a Zumkeller number; The divisors {1 2 3 4 6 12} can be partitioned into two groups {1 3 4 6} and {2 12} that both sum to 14.
Even Zumkeller numbers are common; odd Zumkeller numbers are much less so. For values below 10^6, there is at least one Zumkeller number in every 12 consecutive integers, and the vast majority of them are even. The odd Zumkeller numbers are very similar to the list from the task Abundant odd numbers; they are nearly the same except for the further restriction that the abundance (A(n) = sigma(n) - 2n), must be even: A(n) mod 2 == 0
Task
Write a routine (function, procedure, whatever) to find Zumkeller numbers.
Use the routine to find and display here, on this page, the first 220 Zumkeller numbers.
Use the routine to find and display here, on this page, the first 40 odd Zumkeller numbers.
Optional, stretch goal: Use the routine to find and display here, on this page, the first 40 odd Zumkeller numbers that don't end with 5.
See Also
OEIS:A083207 - Zumkeller numbers to get an impression of different partitions OEIS:A083206 Zumkeller partitions
OEIS:A174865 - Odd Zumkeller numbers
Related Tasks
Abundant odd numbers
Abundant, deficient and perfect number classifications
Proper divisors , Factors of an integer | #F.23 | F# |
// Zumkeller numbers: Nigel Galloway. May 16th., 2021
let rec fG n g=match g with h::_ when h>=n->h=n |h::t->fG n t || fG(n-h) t |_->false
let fN g=function n when n&&&1=1->false
|n->let e=n/2-g in match compare e 0 with 0->true
|1->let l=[1..e]|>List.filter(fun n->g%n=0)
match compare(l|>List.sum) e with 1->fG e l |0->true |_->false
|_->false
Seq.initInfinite((+)1)|>Seq.map(fun n->(n,sod n))|>Seq.filter(fun(n,g)->fN n g)|>Seq.take 220|>Seq.iter(fun(n,_)->printf "%d " n); printfn "\n"
Seq.initInfinite((*)2>>(+)1)|>Seq.map(fun n->(n,sod n))|>Seq.filter(fun(n,g)->fN n g)|>Seq.take 40|>Seq.iter(fun(n,_)->printf "%d " n); printfn "\n"
Seq.initInfinite((*)2>>(+)1)|>Seq.filter(fun n->n%10<>5)|>Seq.map(fun n->(n,sod n))|>Seq.filter(fun(n,g)->fN n g)|>Seq.take 40|>Seq.iter(fun(n,_)->printf "%d " n); printfn "\n"
|
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included) | Arbitrary-precision integers (included) | Using the in-built capabilities of your language, calculate the integer value of:
5
4
3
2
{\displaystyle 5^{4^{3^{2}}}}
Confirm that the first and last twenty digits of the answer are:
62060698786608744707...92256259918212890625
Find and show the number of decimal digits in the answer.
Note: Do not submit an implementation of arbitrary precision arithmetic. The intention is to show the capabilities of the language as supplied. If a language has a single, overwhelming, library of varied modules that is endorsed by its home site – such as CPAN for Perl or Boost for C++ – then that may be used instead.
Strictly speaking, this should not be solved by fixed-precision numeric libraries where the precision has to be manually set to a large value; although if this is the only recourse then it may be used with a note explaining that the precision must be set manually to a large enough value.
Related tasks
Long multiplication
Exponentiation order
exponentiation operator
Exponentiation with infix operators in (or operating on) the base
| #C | C | #include <gmp.h>
#include <stdio.h>
#include <string.h>
int main()
{
mpz_t a;
mpz_init_set_ui(a, 5);
mpz_pow_ui(a, a, 1 << 18); /* 2**18 == 4**9 */
int len = mpz_sizeinbase(a, 10);
printf("GMP says size is: %d\n", len);
/* because GMP may report size 1 too big; see doc */
char *s = mpz_get_str(0, 10, a);
printf("size really is %d\n", len = strlen(s));
printf("Digits: %.20s...%s\n", s, s + len - 20);
// free(s); /* we could, but we won't. we are exiting anyway */
return 0;
} |
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included) | Arbitrary-precision integers (included) | Using the in-built capabilities of your language, calculate the integer value of:
5
4
3
2
{\displaystyle 5^{4^{3^{2}}}}
Confirm that the first and last twenty digits of the answer are:
62060698786608744707...92256259918212890625
Find and show the number of decimal digits in the answer.
Note: Do not submit an implementation of arbitrary precision arithmetic. The intention is to show the capabilities of the language as supplied. If a language has a single, overwhelming, library of varied modules that is endorsed by its home site – such as CPAN for Perl or Boost for C++ – then that may be used instead.
Strictly speaking, this should not be solved by fixed-precision numeric libraries where the precision has to be manually set to a large value; although if this is the only recourse then it may be used with a note explaining that the precision must be set manually to a large enough value.
Related tasks
Long multiplication
Exponentiation order
exponentiation operator
Exponentiation with infix operators in (or operating on) the base
| #C.23 | C# | using System;
using System.Diagnostics;
using System.Linq;
using System.Numerics;
static class Program {
static void Main() {
BigInteger n = BigInteger.Pow(5, (int)BigInteger.Pow(4, (int)BigInteger.Pow(3, 2)));
string result = n.ToString();
Debug.Assert(result.Length == 183231);
Debug.Assert(result.StartsWith("62060698786608744707"));
Debug.Assert(result.EndsWith("92256259918212890625"));
Console.WriteLine("n = 5^4^3^2");
Console.WriteLine("n = {0}...{1}",
result.Substring(0, 20),
result.Substring(result.Length - 20, 20)
);
Console.WriteLine("n digits = {0}", result.Length);
}
} |
http://rosettacode.org/wiki/Zhang-Suen_thinning_algorithm | Zhang-Suen thinning algorithm | This is an algorithm used to thin a black and white i.e. one bit per pixel images.
For example, with an input image of:
################# #############
################## ################
################### ##################
######## ####### ###################
###### ####### ####### ######
###### ####### #######
################# #######
################ #######
################# #######
###### ####### #######
###### ####### #######
###### ####### ####### ######
######## ####### ###################
######## ####### ###### ################## ######
######## ####### ###### ################ ######
######## ####### ###### ############# ######
It produces the thinned output:
# ########## #######
## # #### #
# # ##
# # #
# # #
# # #
############ #
# # #
# # #
# # #
# # #
# ##
# ############
### ###
Algorithm
Assume black pixels are one and white pixels zero, and that the input image is a rectangular N by M array of ones and zeroes.
The algorithm operates on all black pixels P1 that can have eight neighbours.
The neighbours are, in order, arranged as:
P9 P2 P3
P8 P1 P4
P7 P6 P5
Obviously the boundary pixels of the image cannot have the full eight neighbours.
Define
A
(
P
1
)
{\displaystyle A(P1)}
= the number of transitions from white to black, (0 -> 1) in the sequence P2,P3,P4,P5,P6,P7,P8,P9,P2. (Note the extra P2 at the end - it is circular).
Define
B
(
P
1
)
{\displaystyle B(P1)}
= The number of black pixel neighbours of P1. ( = sum(P2 .. P9) )
Step 1
All pixels are tested and pixels satisfying all the following conditions (simultaneously) are just noted at this stage.
(0) The pixel is black and has eight neighbours
(1)
2
<=
B
(
P
1
)
<=
6
{\displaystyle 2<=B(P1)<=6}
(2) A(P1) = 1
(3) At least one of P2 and P4 and P6 is white
(4) At least one of P4 and P6 and P8 is white
After iterating over the image and collecting all the pixels satisfying all step 1 conditions, all these condition satisfying pixels are set to white.
Step 2
All pixels are again tested and pixels satisfying all the following conditions are just noted at this stage.
(0) The pixel is black and has eight neighbours
(1)
2
<=
B
(
P
1
)
<=
6
{\displaystyle 2<=B(P1)<=6}
(2) A(P1) = 1
(3) At least one of P2 and P4 and P8 is white
(4) At least one of P2 and P6 and P8 is white
After iterating over the image and collecting all the pixels satisfying all step 2 conditions, all these condition satisfying pixels are again set to white.
Iteration
If any pixels were set in this round of either step 1 or step 2 then all steps are repeated until no image pixels are so changed.
Task
Write a routine to perform Zhang-Suen thinning on an image matrix of ones and zeroes.
Use the routine to thin the following image and show the output here on this page as either a matrix of ones and zeroes, an image, or an ASCII-art image of space/non-space characters.
00000000000000000000000000000000
01111111110000000111111110000000
01110001111000001111001111000000
01110000111000001110000111000000
01110001111000001110000000000000
01111111110000001110000000000000
01110111100000001110000111000000
01110011110011101111001111011100
01110001111011100111111110011100
00000000000000000000000000000000
Reference
Zhang-Suen Thinning Algorithm, Java Implementation by Nayef Reza.
"Character Recognition Systems: A Guide for Students and Practitioners" By Mohamed Cheriet, Nawwaf Kharma, Cheng-Lin Liu, Ching Suen
| #Haskell | Haskell | import Data.Array
import qualified Data.List as List
data BW = Black | White
deriving (Eq, Show)
type Index = (Int, Int)
type BWArray = Array Index BW
toBW :: Char -> BW
toBW '0' = White
toBW '1' = Black
toBW ' ' = White
toBW '#' = Black
toBW _ = error "toBW: illegal char"
toBWArray :: [String] -> BWArray
toBWArray strings = arr
where
height = length strings
width = minimum $ map length strings
arr = listArray ((0, 0), (width - 1, height - 1))
. map toBW . concat . List.transpose $ map (take width) strings
toChar :: BW -> Char
toChar White = ' '
toChar Black = '#'
chunksOf :: Int -> [a] -> [[a]]
chunksOf _ [] = []
chunksOf n xs = take n xs : (chunksOf n $ drop n xs)
showBWArray :: BWArray -> String
showBWArray arr =
List.intercalate "\n" . List.transpose
. chunksOf (height + 1) . map toChar $ elems arr
where
(_, (_, height)) = bounds arr
add :: Num a => (a, a) -> (a, a) -> (a, a)
add (a, b) (x, y) = (a + x, b + y)
within :: Ord a => ((a, a), (a, a)) -> (a, a) -> Bool
within ((a, b), (c, d)) (x, y) =
a <= x && x <= c &&
b <= y && y <= d
p2, p3, p4, p5, p6, p7, p8, p9 :: Index
p2 = ( 0, -1)
p3 = ( 1, -1)
p4 = ( 1, 0)
p5 = ( 1, 1)
p6 = ( 0, 1)
p7 = (-1, 1)
p8 = (-1, 0)
p9 = (-1, -1)
ixamap :: Ix i => ((i, a) -> b) -> Array i a -> Array i b
ixamap f a = listArray (bounds a) $ map f $ assocs a
thin :: BWArray -> BWArray
thin arr =
if pass2 == arr then pass2 else thin pass2
where
(low, high) = bounds arr
lowB = low `add` (1, 1)
highB = high `add` (-1, -1)
isInner = within (lowB, highB)
offs p = map (add p) [p2, p3, p4, p5, p6, p7, p8, p9]
trans c (a, b) = if a == White && b == Black then c + 1 else c
zipshift xs = zip xs (drop 1 xs ++ xs)
transitions a = (== (1 :: Int)) . foldl trans 0 . zipshift . map (a !) . offs
within2to6 n = 2 <= n && n <= 6
blacks a p = within2to6 . length . filter ((== Black) . (a !)) $ offs p
oneWhite xs a p = any ((== White) . (a !) . add p) xs
oneRight = oneWhite [p2, p4, p6]
oneDown = oneWhite [p4, p6, p8]
oneUp = oneWhite [p2, p4, p8]
oneLeft = oneWhite [p2, p6, p8]
precond a p = (a ! p == Black) && isInner p && blacks a p && transitions a p
stage1 a p = precond a p && oneRight a p && oneDown a p
stage2 a p = precond a p && oneUp a p && oneLeft a p
stager f (p, d) = if f p then White else d
pass1 = ixamap (stager $ stage1 arr) arr
pass2 = ixamap (stager $ stage2 pass1) pass1
sampleExA :: [String]
sampleExA =
["00000000000000000000000000000000"
,"01111111110000000111111110000000"
,"01110001111000001111001111000000"
,"01110000111000001110000111000000"
,"01110001111000001110000000000000"
,"01111111110000001110000000000000"
,"01110111100000001110000111000000"
,"01110011110011101111001111011100"
,"01110001111011100111111110011100"
,"00000000000000000000000000000000"]
sampleExB :: [String]
sampleExB =
[" "
," ################# ############# "
," ################## ################ "
," ################### ################## "
," ######## ####### ################### "
," ###### ####### ####### ###### "
," ###### ####### ####### "
," ################# ####### "
," ################ ####### "
," ################# ####### "
," ###### ####### ####### "
," ###### ####### ####### "
," ###### ####### ####### ###### "
," ######## ####### ################### "
," ######## ####### ###### ################## ###### "
," ######## ####### ###### ################ ###### "
," ######## ####### ###### ############# ###### "
," "]
main :: IO ()
main = mapM_ (putStrLn . showBWArray . thin . toBWArray) [sampleExA, sampleExB] |
http://rosettacode.org/wiki/Zeckendorf_number_representation | Zeckendorf number representation | Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series.
Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13.
The decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100.
10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that no two consecutive Fibonacci numbers can be used which leads to the former unique solution.
Task
Generate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order.
The intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task.
Also see
OEIS A014417 for the the sequence of required results.
Brown's Criterion - Numberphile
Related task
Fibonacci sequence
| #Cowgol | Cowgol | include "cowgol.coh";
sub zeckendorf(n: uint32, buf: [uint8]): (r: [uint8]) is
var fibs: uint32[] := {
0,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,
2584,4181,6765,10946,17711,28657,46368,75025,121393,
196418,317811,514229,832040,1346269,2178309,3524578,
5702887,9227465,14930352,24157817,39088169,63245986,
102334155,165580141,267914296,433494437,701408733,
1134903170,1836311903,2971215073
};
r := buf;
if n == 0 then
[r] := '0';
[@next r] := 0;
return;
end if;
var fib: [uint32] := &fibs[1];
while n >= [fib] loop
fib := @next fib;
end loop;
fib := @prev fib;
while [fib] != 0 loop
if [fib] <= n then
n := n - [fib];
[buf] := '1';
else
[buf] := '0';
end if;
fib := @prev fib;
buf := @next buf;
end loop;
[buf] := 0;
end sub;
var i: uint32 := 0;
while i <= 20 loop
print_i32(i);
print(": ");
print(zeckendorf(i, LOMEM));
print_nl();
i := i + 1;
end loop; |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #BlitzMax | BlitzMax | Graphics 640,480
i=1
While ((i*i)<=100)
a$=i*i
DrawText a$,10,20*i
Print i*i
i=i+1
Wend
Flip
WaitKey |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #E | E | ? def empty := []
# value: []
? def numbers := [1,2,3,4,5]
# value: [1, 2, 3, 4, 5]
? numbers.with(6)
# value: [1, 2, 3, 4, 5, 6]
? numbers + [4,3,2,1]
# value: [1, 2, 3, 4, 5, 4, 3, 2, 1] |
http://rosettacode.org/wiki/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part", where the imaginary part is the number to be multiplied by
i
{\displaystyle i}
.
Task
Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.)
Print the results for each operation tested.
Optional: Show complex conjugation.
By definition, the complex conjugate of
a
+
b
i
{\displaystyle a+bi}
is
a
−
b
i
{\displaystyle a-bi}
Some languages have complex number libraries available. If your language does, show the operations. If your language does not, also show the definition of this type.
| #Oforth | Oforth | Object Class new: Complex(re, im)
Complex method: re @re ;
Complex method: im @im ;
Complex method: initialize := im := re ;
Complex method: << '(' <<c @re << ',' <<c @im << ')' <<c ;
0 1 Complex new const: I
Complex method: ==(c -- b )
c re @re == c im @im == and ;
Complex method: norm -- f
@re sq @im sq + sqrt ;
Complex method: conj -- c
@re @im neg Complex new ;
Complex method: +(c -- d )
c re @re + c im @im + Complex new ;
Complex method: -(c -- d )
c re @re - c im @im - Complex new ;
Complex method: *(c -- d)
c re @re * c im @im * - c re @im * @re c im * + Complex new ;
Complex method: inv
| n |
@re sq @im sq + >float ->n
@re n / @im neg n / Complex new
;
Complex method: /( c -- d )
c self inv * ;
Integer method: >complex self 0 Complex new ;
Float method: >complex self 0 Complex new ; |
http://rosettacode.org/wiki/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part", where the imaginary part is the number to be multiplied by
i
{\displaystyle i}
.
Task
Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.)
Print the results for each operation tested.
Optional: Show complex conjugation.
By definition, the complex conjugate of
a
+
b
i
{\displaystyle a+bi}
is
a
−
b
i
{\displaystyle a-bi}
Some languages have complex number libraries available. If your language does, show the operations. If your language does not, also show the definition of this type.
| #Ol | Ol |
(define A 0+1i) ; manually entered numbers
(define B 1+0i)
(print (+ A B))
; <== 1+i
(print (- A B))
; <== -1+i
(print (* A B))
; <== 0+i
(print (/ A B))
; <== 0+i
(define C (complex 2/7 -3)) ; functional way
(print "real part of " C " is " (car C))
; <== real part of 2/7-3i is 2/7
(print "imaginary part of " C " is " (cdr C))
; <== imaginary part of 2/7-3i is -3
|
http://rosettacode.org/wiki/Arithmetic/Rational | Arithmetic/Rational | Task
Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language.
Example
Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number).
Further define the appropriate rational unary operators abs and '-', with the binary operators for addition '+', subtraction '-', multiplication '×', division '/', integer division '÷', modulo division, the comparison operators (e.g. '<', '≤', '>', & '≥') and equality operators (e.g. '=' & '≠').
Define standard coercion operators for casting int to frac etc.
If space allows, define standard increment and decrement operators (e.g. '+:=' & '-:=' etc.).
Finally test the operators:
Use the new type frac to find all perfect numbers less than 219 by summing the reciprocal of the factors.
Related task
Perfect Numbers
| #PL.2FI | PL/I | *process source attributes xref or(!);
arat: Proc Options(main);
/*--------------------------------------------------------------------
* Rational Arithmetic
* (Mis)use the Complex data type to represent fractions
* real(x) is used as numerator
* imag(x) is used as denominator
* Output:
* a=-3/7 b=9/2
* a*b=-27/14
* a+b=57/14
* a-b=-69/14
* a/b=-2/21
* -3/7<9/2
* 9/2>-3/7
* -3/7=-3/7
* 26.01.2015 handle 0/0
*-------------------------------------------------------------------*/
Dcl (abs,imag,mod,real,sign,trim) Builtin;
Dcl sysprint Print;
Dcl (candidate,max2,factor) Dec Fixed(15);
Dcl sum complex Dec Fixed(15);
Dcl one complex Dec Fixed(15);
one=mk_fr(1,1);
Put Edit('First solve the task at hand')(Skip,a);
Do candidate = 2 to 10000;
sum = mk_fr(1, candidate);
max2 = sqrt(candidate);
Do factor = 2 to max2;
If mod(candidate,factor)=0 Then Do;
sum=fr_add(sum,mk_fr(1,factor));
sum=fr_add(sum,mk_fr(1,candidate/factor));
End;
End;
If fr_cmp(sum,one)='=' Then Do;
Put Edit(candidate,' is a perfect number')(Skip,f(7),a);
Do factor = 2 to candidate-1;
If mod(candidate,factor)=0 Then
Put Edit(factor)(f(5));
End;
End;
End;
Put Edit('','Then try a few things')(Skip,a);
Dcl a Complex Dec Fixed(15);
Dcl b Complex Dec Fixed(15);
Dcl p Complex Dec Fixed(15);
Dcl s Complex Dec Fixed(15);
Dcl d Complex Dec Fixed(15);
Dcl q Complex Dec Fixed(15);
Dcl zero Complex Dec Fixed(15);
zero=mk_fr(0,1); Put Edit('zero=',fr_rep(zero))(Skip,2(a));
a=mk_fr(0,0); Put Edit('a=',fr_rep(a))(Skip,2(a));
/*--------------------------------------------------------------------
a=mk_fr(-3333,0); Put Edit('a=',fr_rep(a))(Skip,2(a));
=> Request mk_fr(-3333,0)
Denominator must not be 0
IBM0280I ONCODE=0009 The ERROR condition was raised
by a SIGNAL statement.
At offset +00000276 in procedure with entry FT
*-------------------------------------------------------------------*/
a=mk_fr(0,3333); Put Edit('a=',fr_rep(a))(Skip,2(a));
Put Edit('-3,7')(Skip,a);
a=mk_fr(-3,7);
b=mk_fr(9,2);
p=fr_mult(a,b);
s=fr_add(a,b);
d=fr_sub(a,b);
q=fr_div(a,b);
r=fr_div(b,a);
Put Edit('a=',fr_rep(a))(Skip,2(a));
Put Edit('b=',fr_rep(b))(Skip,2(a));
Put Edit('a*b=',fr_rep(p))(Skip,2(a));
Put Edit('a+b=',fr_rep(s))(Skip,2(a));
Put Edit('a-b=',fr_rep(d))(Skip,2(a));
Put Edit('a/b=',fr_rep(q))(Skip,2(a));
Put Edit('b/a=',fr_rep(r))(Skip,2(a));
Put Edit(fr_rep(a),fr_cmp(a,b),fr_rep(b))(Skip,3(a));
Put Edit(fr_rep(b),fr_cmp(b,a),fr_rep(a))(Skip,3(a));
Put Edit(fr_rep(a),fr_cmp(a,a),fr_rep(a))(Skip,3(a));
mk_fr: Proc(n,d) Recursive Returns(Dec Fixed(15) Complex);
/*--------------------------------------------------------------------
* make a Complex number
* normalize and cancel
*-------------------------------------------------------------------*/
Dcl (n,d) Dec Fixed(15);
Dcl (na,da) Dec Fixed(15);
Dcl res Dec Fixed(15) Complex;
Dcl x Dec Fixed(15);
na=abs(n);
da=abs(d);
Select;
When(n=0) Do;
real(res)=0;
imag(res)=1;
End;
When(d=0) Do;
Put Edit('Request mk_fr('!!n_rep(n)!!','!!n_rep(d)!!')')
(Skip,a);
Put Edit('Denominator must not be 0')(Skip,a);
Signal error;
End;
Otherwise Do;
x=gcd(na,da);
real(res)=sign(n)*sign(d)*na/x;
imag(res)=da/x;
End;
End;
Return(res);
End;
fr_add: Proc(a,b) Returns(Dec Fixed(15) Complex);
/*--------------------------------------------------------------------
* add 'fractions' a and b
*-------------------------------------------------------------------*/
Dcl (a,b,res) Dec Fixed(15) Complex;
Dcl (an,ad,bn,bd) Dec Fixed(15);
Dcl (rd,rn) Dec Fixed(15);
Dcl x Dec Fixed(15);
an=real(a);
ad=imag(a);
bn=real(b);
bd=imag(b);
rd=ad*bd;
rn=an*bd+bn*ad;
x=gcd(rd,rn);
real(res)=rn/x;
imag(res)=rd/x;
Return(res);
End;
fr_sub: Proc(a,b) Returns(Dec Fixed(15) Complex);
/*--------------------------------------------------------------------
* subtract 'fraction' b from a
*-------------------------------------------------------------------*/
Dcl (a,b) Dec Fixed(15) Complex;
Dcl b2 Dec Fixed(15) Complex;
real(b2)=-real(b);
imag(b2)=imag(b);
Return(fr_add(a,b2));
End;
fr_mult: Proc(a,b) Returns(Dec Fixed(15) Complex);
/*--------------------------------------------------------------------
* multiply 'fractions' a and b
*-------------------------------------------------------------------*/
Dcl (a,b,res) Dec Fixed(15) Complex;
real(res)=real(a)*real(b);
imag(res)=imag(a)*imag(b);
Return(res);
End;
fr_div: Proc(a,b) Returns(Dec Fixed(15) Complex);
/*--------------------------------------------------------------------
* divide 'fraction' a by b
*-------------------------------------------------------------------*/
Dcl (a,b) Dec Fixed(15) Complex;
Dcl b2 Dec Fixed(15) Complex;
real(b2)=imag(b);
imag(b2)=real(b);
If real(a)=0 & real(b)=0 Then
Return(mk_fr(1,1));
Return(fr_mult(a,b2));
End;
fr_cmp: Proc(a,b) Returns(char(1));
/*--------------------------------------------------------------------
* compare 'fractions' a and b
*-------------------------------------------------------------------*/
Dcl (a,b) Dec Fixed(15) Complex;
Dcl (an,ad,bn,bd) Dec Fixed(15);
Dcl (a2,b2) Dec Fixed(15);
Dcl (rd) Dec Fixed(15);
Dcl res Char(1);
an=real(a);
ad=imag(a);
If ad=0 Then Do;
Put Edit('ad=',ad,'candidate=',candidate)(Skip,a,f(10));
Signal Error;
End;
bn=real(b);
bd=imag(b);
rd=ad*bd;
a2=abs(an*bd)*sign(an)*sign(ad);
b2=abs(bn*ad)*sign(bn)*sign(bd);
Select;
When(a2<b2) res='<';
When(a2>b2) res='>';
Otherwise Do;
res='=';
End;
End;
Return(res);
End;
fr_rep: Proc(f) Returns(char(15) Var);
/*--------------------------------------------------------------------
* Return the representation of 'fraction' f
*-------------------------------------------------------------------*/
Dcl f Dec Fixed(15) Complex;
Dcl res Char(15) Var;
Dcl (n,d) Pic'(14)Z9';
Dcl x Dec Fixed(15);
Dcl s Dec Fixed(15);
n=abs(real(f));
d=abs(imag(f));
x=gcd(n,d);
s=sign(real(f))*sign(imag(f));
res=trim(n/x)!!'/'!!trim(d/x);
If s<0 Then
res='-'!!res;
Return(res);
End;
n_rep: Proc(x) Returns(char(15) Var);
/*--------------------------------------------------------------------
* Return the representation of x
*-------------------------------------------------------------------*/
Dcl x Dec Fixed(15);
Dcl res Char(15) Var;
Put String(res) List(x);
res=trim(res);
Return(res);
End;
gcd: Proc(a,b) Returns(Dec Fixed(15)) Recursive;
/*--------------------------------------------------------------------
* Compute the greatest common divisor
*-------------------------------------------------------------------*/
Dcl (a,b) Dec Fixed(15) Nonassignable;
If b=0 then Return (abs(a));
Return(gcd(abs(b),mod(abs(a),abs(b))));
End gcd;
lcm: Proc(a,b) Returns(Dec Fixed(15));
/*--------------------------------------------------------------------
* Compute the least common multiple
*-------------------------------------------------------------------*/
Dcl (a,b) Dec Fixed(15) Nonassignable;
if a=0 ! b=0 then Return (0);
Return(abs(a*b)/gcd(a,b));
End lcm;
End; |
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geometric mean of two numbers.
The arithmetic-geometric mean of two numbers can be (usefully) denoted as
a
g
m
(
a
,
g
)
{\displaystyle \mathrm {agm} (a,g)}
, and is equal to the limit of the sequence:
a
0
=
a
;
g
0
=
g
{\displaystyle a_{0}=a;\qquad g_{0}=g}
a
n
+
1
=
1
2
(
a
n
+
g
n
)
;
g
n
+
1
=
a
n
g
n
.
{\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.}
Since the limit of
a
n
−
g
n
{\displaystyle a_{n}-g_{n}}
tends (rapidly) to zero with iterations, this is an efficient method.
Demonstrate the function by calculating:
a
g
m
(
1
,
1
/
2
)
{\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})}
Also see
mathworld.wolfram.com/Arithmetic-Geometric Mean
| #Scala | Scala |
def agm(a: Double, g: Double, eps: Double): Double = {
if (math.abs(a - g) < eps) (a + g) / 2
else agm((a + g) / 2, math.sqrt(a * g), eps)
}
agm(1, math.sqrt(2)/2, 1e-15)
|
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geometric mean of two numbers.
The arithmetic-geometric mean of two numbers can be (usefully) denoted as
a
g
m
(
a
,
g
)
{\displaystyle \mathrm {agm} (a,g)}
, and is equal to the limit of the sequence:
a
0
=
a
;
g
0
=
g
{\displaystyle a_{0}=a;\qquad g_{0}=g}
a
n
+
1
=
1
2
(
a
n
+
g
n
)
;
g
n
+
1
=
a
n
g
n
.
{\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.}
Since the limit of
a
n
−
g
n
{\displaystyle a_{n}-g_{n}}
tends (rapidly) to zero with iterations, this is an efficient method.
Demonstrate the function by calculating:
a
g
m
(
1
,
1
/
2
)
{\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})}
Also see
mathworld.wolfram.com/Arithmetic-Geometric Mean
| #Scheme | Scheme |
(define agm
(case-lambda
((a0 g0) ; call again with default value for tolerance
(agm a0 g0 1e-8))
((a0 g0 tolerance) ; called with three arguments
(do ((a a0 (* (+ a g) 1/2))
(g g0 (sqrt (* a g))))
((< (abs (- a g)) tolerance) a)))))
(display (agm 1 (/ 1 (sqrt 2)))) (newline)
|
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, you may also try something like:
x = 0
y = 0
z = x**y
say 'z=' z
Show the result here.
And of course use any symbols or notation that is supported in your computer programming language for exponentiation.
See also
The Wiki entry: Zero to the power of zero.
The Wiki entry: History of differing points of view.
The MathWorld™ entry: exponent laws.
Also, in the above MathWorld™ entry, see formula (9):
x
0
=
1
{\displaystyle x^{0}=1}
.
The OEIS entry: The special case of zero to the zeroth power
| #Factor | Factor | USING: math.functions.private ; ! ^complex
0 0 ^
C{ 0 0 } C{ 0 0 } ^complex |
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, you may also try something like:
x = 0
y = 0
z = x**y
say 'z=' z
Show the result here.
And of course use any symbols or notation that is supported in your computer programming language for exponentiation.
See also
The Wiki entry: Zero to the power of zero.
The Wiki entry: History of differing points of view.
The MathWorld™ entry: exponent laws.
Also, in the above MathWorld™ entry, see formula (9):
x
0
=
1
{\displaystyle x^{0}=1}
.
The OEIS entry: The special case of zero to the zeroth power
| #Falcon | Falcon |
/* created by Aykayayciti Earl Lamont Montgomery
April 9th, 2018 */
x = 0
y = 0
z = x**y
> "z=", z
|
http://rosettacode.org/wiki/Zig-zag_matrix | Zig-zag matrix | Task
Produce a zig-zag array.
A zig-zag array is a square arrangement of the first N2 natural numbers, where the
numbers increase sequentially as you zig-zag along the array's anti-diagonals.
For a graphical representation, see JPG zigzag (JPG uses such arrays to encode images).
For example, given 5, produce this array:
0 1 5 6 14
2 4 7 13 15
3 8 12 16 21
9 11 17 20 22
10 18 19 23 24
Related tasks
Spiral matrix
Identity matrix
Ulam spiral (for primes)
See also
Wiktionary entry: anti-diagonals
| #360_Assembly | 360 Assembly | * Zig-zag matrix 15/08/2015
ZIGZAGMA CSECT
USING ZIGZAGMA,R12 set base register
LR R12,R15 establish addressability
LA R9,N n : matrix size
LA R6,1 i=1
LA R7,1 j=1
LR R11,R9 n
MR R10,R9 *n
BCTR R11,0 R11=n**2-1
SR R8,R8 k=0
LOOPK CR R8,R11 do k=0 to n**2-1
BH ELOOPK k>limit
LR R1,R6 i
BCTR R1,0 -1
MR R0,R9 *n
LR R2,R7 j
BCTR R2,0 -1
AR R1,R2 (i-1)*n+(j-1)
SLA R1,1 index=((i-1)*n+j-1)*2
STH R8,T(R1) t(i,j)=k
LR R2,R6 i
AR R2,R7 i+j
LA R1,2 2
SRDA R2,32 shift right r1 to r2
DR R2,R1 (i+j)/2
LTR R2,R2 if mod(i+j,2)=0
BNZ ELSEMOD
CR R7,R9 if j<n
BNL ELSE1
LA R7,1(R7) j=j+1
B EIF1
ELSE1 LA R6,2(R6) i=i+2
EIF1 CH R6,=H'1' if i>1
BNH NOT1
BCTR R6,0 i=i-1
NOT1 B NOT2
ELSEMOD CR R6,R9 if i<n
BNL ELSE2
LA R6,1(R6) i=i+1
B EIF2
ELSE2 LA R7,2(R7) j=j+2
EIF2 CH R7,=H'1' if j>1
BNH NOT2
BCTR R7,0 j=j-1
NOT2 LA R8,1(R8) k=k+1
B LOOPK
ELOOPK LA R6,1 end k; i=1
LOOPI CR R6,R9 do i=1 to n
BH ELOOPI i>n
LA R10,0 ibuf=0 buffer index
MVC BUFFER,=CL80' '
LA R7,1 j=1
LOOPJ CR R7,R9 do j=1 to n
BH ELOOPJ j>n
LR R1,R6 i
BCTR R1,0 -1
MR R0,R9 *n
LR R2,R7 j
BCTR R2,0 -1
AR R1,R2 (i-1)*n+(j-1)
SLA R1,1 index=((i-1)*n+j-1)*2
LH R2,T(R1) t(i,j)
LA R3,BUFFER
AR R3,R10
XDECO R2,XDEC edit t(i,j) length=12
MVC 0(4,R3),XDEC+8 move in buffer length=4
LA R10,4(R10) ibuf=ibuf+1
LA R7,1(R7) j=j+1
B LOOPJ
ELOOPJ XPRNT BUFFER,80 end j
LA R6,1(R6) i=i+1
B LOOPI
ELOOPI XR R15,R15 end i; return_code=0
BR R14 return to caller
N EQU 5 matrix size
BUFFER DS CL80
XDEC DS CL12
T DS (N*N)H t(n,n) matrix
YREGS
END ZIGZAGMA |
http://rosettacode.org/wiki/Yellowstone_sequence | Yellowstone sequence | The Yellowstone sequence, also called the Yellowstone permutation, is defined as:
For n <= 3,
a(n) = n
For n >= 4,
a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and
is not relatively prime to a(n-2).
The sequence is a permutation of the natural numbers, and gets its name from what its authors felt was a spiking, geyser like appearance of a plot of the sequence.
Example
a(4) is 4 because 4 is the smallest number following 1, 2, 3 in the sequence that is relatively prime to the entry before it (3), and is not relatively prime to the number two entries before it (2).
Task
Find and show as output the first 30 Yellowstone numbers.
Extra
Demonstrate how to plot, with x = n and y coordinate a(n), the first 100 Yellowstone numbers.
Related tasks
Greatest common divisor.
Plot coordinate pairs.
See also
The OEIS entry: A098550 The Yellowstone permutation.
Applegate et al, 2015: The Yellowstone Permutation [1].
| #11l | 11l | T YellowstoneGenerator
min_ = 1
n_ = 0
n1_ = 0
n2_ = 0
Set[Int] sequence_
F next()
.n2_ = .n1_
.n1_ = .n_
I .n_ < 3
.n_++
E
.n_ = .min_
L !(.n_ !C .sequence_ & gcd(.n1_, .n_) == 1 & gcd(.n2_, .n_) > 1)
.n_++
.sequence_.add(.n_)
L
I .min_ !C .sequence_
L.break
.sequence_.remove(.min_)
.min_++
R .n_
print(‘First 30 Yellowstone numbers:’)
V ygen = YellowstoneGenerator()
print(ygen.next(), end' ‘’)
L(i) 1 .< 30
print(‘ ’ygen.next(), end' ‘’)
print() |
http://rosettacode.org/wiki/Arithmetic_evaluation | Arithmetic evaluation | Create a program which parses and evaluates arithmetic expressions.
Requirements
An abstract-syntax tree (AST) for the expression must be created from parsing the input.
The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.)
The expression will be a string or list of symbols like "(1+3)*7".
The four symbols + - * / must be supported as binary operators with conventional precedence rules.
Precedence-control parentheses must also be supported.
Note
For those who don't remember, mathematical precedence is as follows:
Parentheses
Multiplication/Division (left to right)
Addition/Subtraction (left to right)
C.f
24 game Player.
Parsing/RPN calculator algorithm.
Parsing/RPN to infix conversion.
| #Picat | Picat | main =>
print("Enter an expression: "),
Str = read_line(),
Exp = parse_term(Str),
Res is Exp,
printf("Result = %w\n", Res).
|
http://rosettacode.org/wiki/Arithmetic_evaluation | Arithmetic evaluation | Create a program which parses and evaluates arithmetic expressions.
Requirements
An abstract-syntax tree (AST) for the expression must be created from parsing the input.
The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.)
The expression will be a string or list of symbols like "(1+3)*7".
The four symbols + - * / must be supported as binary operators with conventional precedence rules.
Precedence-control parentheses must also be supported.
Note
For those who don't remember, mathematical precedence is as follows:
Parentheses
Multiplication/Division (left to right)
Addition/Subtraction (left to right)
C.f
24 game Player.
Parsing/RPN calculator algorithm.
Parsing/RPN to infix conversion.
| #PicoLisp | PicoLisp | (de ast (Str)
(let *L (str Str "")
(aggregate) ) )
(de aggregate ()
(let X (product)
(while (member (car *L) '("+" "-"))
(setq X (list (intern (pop '*L)) X (product))) )
X ) )
(de product ()
(let X (term)
(while (member (car *L) '("*" "/"))
(setq X (list (intern (pop '*L)) X (term))) )
X ) )
(de term ()
(let X (pop '*L)
(cond
((num? X) X)
((= "+" X) (term))
((= "-" X) (list '- (term)))
((= "(" X) (prog1 (aggregate) (pop '*L)))) ) ) |
http://rosettacode.org/wiki/Zeckendorf_arithmetic | Zeckendorf arithmetic | This task is a total immersion zeckendorf task; using decimal numbers will attract serious disapprobation.
The task is to implement addition, subtraction, multiplication, and division using Zeckendorf number representation. Optionally provide decrement, increment and comparitive operation functions.
Addition
Like binary 1 + 1 = 10, note carry 1 left. There the similarity ends. 10 + 10 = 101, note carry 1 left and 1 right. 100 + 100 = 1001, note carry 1 left and 2 right, this is the general case.
Occurrences of 11 must be changed to 100. Occurrences of 111 may be changed from the right by replacing 11 with 100, or from the left converting 111 to 100 + 100;
Subtraction
10 - 1 = 1. The general rule is borrow 1 right carry 1 left. eg:
abcde
10100 -
1000
_____
100 borrow 1 from a leaves 100
+ 100 add the carry
_____
1001
A larger example:
abcdef
100100 -
1000
______
1*0100 borrow 1 from b
+ 100 add the carry
______
1*1001
Sadly we borrowed 1 from b which didn't have it to lend. So now b borrows from a:
1001
+ 1000 add the carry
____
10100
Multiplication
Here you teach your computer its zeckendorf tables. eg. 101 * 1001:
a = 1 * 101 = 101
b = 10 * 101 = a + a = 10000
c = 100 * 101 = b + a = 10101
d = 1000 * 101 = c + b = 101010
1001 = d + a therefore 101 * 1001 =
101010
+ 101
______
1000100
Division
Lets try 1000101 divided by 101, so we can use the same table used for multiplication.
1000101 -
101010 subtract d (1000 * 101)
_______
1000 -
101 b and c are too large to subtract, so subtract a
____
1 so 1000101 divided by 101 is d + a (1001) remainder 1
Efficient algorithms for Zeckendorf arithmetic is interesting. The sections on addition and subtraction are particularly relevant for this task.
| #Elena | Elena | import extensions;
const dig = new string[]{"00","01","10"};
const dig1 = new string[]{"","1","10"};
sealed struct ZeckendorfNumber
{
int dVal;
int dLen;
clone()
= ZeckendorfNumber.newInternal(dVal,dLen);
cast n(string s)
{
int i := s.Length - 1;
int q := 1;
dLen := i / 2;
dVal := 0;
while (i >= 0)
{
dVal += ((intConvertor.convert(s[i]) - 48) * q);
q *= 2;
i -= 1
}
}
internal readContent(ref int val, ref int len)
{
val := dVal;
len := dLen;
}
private a(int n)
{
int i := n;
while (true)
{
if (dLen < i)
{
dLen := i
};
int v := (dVal $shr (i * 2)) && 3;
v =>
0 { ^ self }
1 { ^ self }
2 {
ifnot ((dVal $shr ((i + 1) * 2)).allMask:1)
{
^ self
};
dVal += (1 $shl (i*2 + 1));
^ self
}
3 {
int tmp := 3 $shl (i * 2);
tmp := tmp.xor(-1);
dVal := dVal && tmp;
self.b((i+1)*2)
};
i += 1
}
}
inc()
{
dVal += 1;
self.a(0)
}
private b(int pos)
{
if (pos == 0) { ^ self.inc() };
ifnot((dVal $shr pos).allMask:1)
{
dVal += (1 $shl pos);
self.a(pos / 2);
if (pos > 1) { self.a((pos / 2) - 1) }
}
else
{
dVal := dVal && (1 $shl pos).Inverted;
self.b(pos + 1);
int arg := pos - ((pos > 1) ? 2 : 1);
self.b(/*pos - ((pos > 1) ? 2 : 1)*/arg)
}
}
private c(int pos)
{
if ((dVal $shr pos).allMask:1)
{
int tmp := 1 $shl pos;
tmp := tmp.xor(-1);
dVal := dVal && tmp;
^ self
};
self.c(pos + 1);
if (pos > 0)
{
self.b(pos - 1)
}
else
{
self.inc()
}
}
internal constructor sum(ZeckendorfNumber n, ZeckendorfNumber m)
{
int mVal := 0;
int mLen := 0;
n.readContent(ref dVal, ref dLen);
m.readContent(ref mVal, ref mLen);
for(int GN := 0, GN < (mLen + 1) * 2, GN += 1)
{
if ((mVal $shr GN).allMask:1)
{
self.b(GN)
}
}
}
internal constructor difference(ZeckendorfNumber n, ZeckendorfNumber m)
{
int mVal := 0;
int mLen := 0;
n.readContent(ref dVal, ref dLen);
m.readContent(ref mVal, ref mLen);
for(int GN := 0, GN < (mLen + 1) * 2, GN += 1)
{
if ((mVal $shr GN).allMask:1)
{
self.c(GN)
}
};
while (((dVal $shr (dLen*2)) && 3) == 0 || dLen == 0)
{
dLen -= 1
}
}
internal constructor product(ZeckendorfNumber n, ZeckendorfNumber m)
{
n.readContent(ref dVal, ref dLen);
ZeckendorfNumber Na := m;
ZeckendorfNumber Nb := m;
ZeckendorfNumber Nr := 0n;
ZeckendorfNumber Nt := 0n;
for(int i := 0, i < (dLen + 1) * 2, i += 1)
{
if (((dVal $shr i) && 1) > 0)
{
Nr += Nb
};
Nt := Nb;
Nb += Na;
Na := Nt
};
Nr.readContent(ref dVal, ref dLen);
}
internal constructor newInternal(int v, int l)
{
dVal := v;
dLen := l
}
string toPrintable()
{
if (dVal == 0)
{ ^ "0" };
string s := dig1[(dVal $shr (dLen * 2)) && 3];
int i := dLen - 1;
while (i >= 0)
{
s := s + dig[(dVal $shr (i * 2)) && 3];
i-=1
};
^ s
}
add(ZeckendorfNumber n)
= ZeckendorfNumber.sum(self, n);
subtract(ZeckendorfNumber n)
= ZeckendorfNumber.difference(self, n);
multiply(ZeckendorfNumber n)
= ZeckendorfNumber.product(self, n);
}
public program()
{
console.printLine("Addition:");
var n := 10n;
n += 10n;
console.printLine(n);
n += 10n;
console.printLine(n);
n += 1001n;
console.printLine(n);
n += 1000n;
console.printLine(n);
n += 10101n;
console.printLine(n);
console.printLine("Subtraction:");
n := 1000n;
n -= 101n;
console.printLine(n);
n := 10101010n;
n -= 1010101n;
console.printLine(n);
console.printLine("Multiplication:");
n := 1001n;
n *= 101n;
console.printLine(n);
n := 101010n;
n += 101n;
console.printLine(n)
} |
http://rosettacode.org/wiki/Zeckendorf_arithmetic | Zeckendorf arithmetic | This task is a total immersion zeckendorf task; using decimal numbers will attract serious disapprobation.
The task is to implement addition, subtraction, multiplication, and division using Zeckendorf number representation. Optionally provide decrement, increment and comparitive operation functions.
Addition
Like binary 1 + 1 = 10, note carry 1 left. There the similarity ends. 10 + 10 = 101, note carry 1 left and 1 right. 100 + 100 = 1001, note carry 1 left and 2 right, this is the general case.
Occurrences of 11 must be changed to 100. Occurrences of 111 may be changed from the right by replacing 11 with 100, or from the left converting 111 to 100 + 100;
Subtraction
10 - 1 = 1. The general rule is borrow 1 right carry 1 left. eg:
abcde
10100 -
1000
_____
100 borrow 1 from a leaves 100
+ 100 add the carry
_____
1001
A larger example:
abcdef
100100 -
1000
______
1*0100 borrow 1 from b
+ 100 add the carry
______
1*1001
Sadly we borrowed 1 from b which didn't have it to lend. So now b borrows from a:
1001
+ 1000 add the carry
____
10100
Multiplication
Here you teach your computer its zeckendorf tables. eg. 101 * 1001:
a = 1 * 101 = 101
b = 10 * 101 = a + a = 10000
c = 100 * 101 = b + a = 10101
d = 1000 * 101 = c + b = 101010
1001 = d + a therefore 101 * 1001 =
101010
+ 101
______
1000100
Division
Lets try 1000101 divided by 101, so we can use the same table used for multiplication.
1000101 -
101010 subtract d (1000 * 101)
_______
1000 -
101 b and c are too large to subtract, so subtract a
____
1 so 1000101 divided by 101 is d + a (1001) remainder 1
Efficient algorithms for Zeckendorf arithmetic is interesting. The sections on addition and subtraction are particularly relevant for this task.
| #Go | Go | package main
import (
"fmt"
"strings"
)
var (
dig = [3]string{"00", "01", "10"}
dig1 = [3]string{"", "1", "10"}
)
type Zeckendorf struct{ dVal, dLen int }
func NewZeck(x string) *Zeckendorf {
z := new(Zeckendorf)
if x == "" {
x = "0"
}
q := 1
i := len(x) - 1
z.dLen = i / 2
for ; i >= 0; i-- {
z.dVal += int(x[i]-'0') * q
q *= 2
}
return z
}
func (z *Zeckendorf) a(i int) {
for ; ; i++ {
if z.dLen < i {
z.dLen = i
}
j := (z.dVal >> uint(i*2)) & 3
switch j {
case 0, 1:
return
case 2:
if ((z.dVal >> (uint(i+1) * 2)) & 1) != 1 {
return
}
z.dVal += 1 << uint(i*2+1)
return
case 3:
z.dVal &= ^(3 << uint(i*2))
z.b((i + 1) * 2)
}
}
}
func (z *Zeckendorf) b(pos int) {
if pos == 0 {
z.Inc()
return
}
if ((z.dVal >> uint(pos)) & 1) == 0 {
z.dVal += 1 << uint(pos)
z.a(pos / 2)
if pos > 1 {
z.a(pos/2 - 1)
}
} else {
z.dVal &= ^(1 << uint(pos))
z.b(pos + 1)
temp := 1
if pos > 1 {
temp = 2
}
z.b(pos - temp)
}
}
func (z *Zeckendorf) c(pos int) {
if ((z.dVal >> uint(pos)) & 1) == 1 {
z.dVal &= ^(1 << uint(pos))
return
}
z.c(pos + 1)
if pos > 0 {
z.b(pos - 1)
} else {
z.Inc()
}
}
func (z *Zeckendorf) Inc() {
z.dVal++
z.a(0)
}
func (z1 *Zeckendorf) PlusAssign(z2 *Zeckendorf) {
for gn := 0; gn < (z2.dLen+1)*2; gn++ {
if ((z2.dVal >> uint(gn)) & 1) == 1 {
z1.b(gn)
}
}
}
func (z1 *Zeckendorf) MinusAssign(z2 *Zeckendorf) {
for gn := 0; gn < (z2.dLen+1)*2; gn++ {
if ((z2.dVal >> uint(gn)) & 1) == 1 {
z1.c(gn)
}
}
for z1.dLen > 0 && ((z1.dVal>>uint(z1.dLen*2))&3) == 0 {
z1.dLen--
}
}
func (z1 *Zeckendorf) TimesAssign(z2 *Zeckendorf) {
na := z2.Copy()
nb := z2.Copy()
nr := new(Zeckendorf)
for i := 0; i <= (z1.dLen+1)*2; i++ {
if ((z1.dVal >> uint(i)) & 1) > 0 {
nr.PlusAssign(nb)
}
nt := nb.Copy()
nb.PlusAssign(na)
na = nt.Copy()
}
z1.dVal = nr.dVal
z1.dLen = nr.dLen
}
func (z *Zeckendorf) Copy() *Zeckendorf {
return &Zeckendorf{z.dVal, z.dLen}
}
func (z1 *Zeckendorf) Compare(z2 *Zeckendorf) int {
switch {
case z1.dVal < z2.dVal:
return -1
case z1.dVal > z2.dVal:
return 1
default:
return 0
}
}
func (z *Zeckendorf) String() string {
if z.dVal == 0 {
return "0"
}
var sb strings.Builder
sb.WriteString(dig1[(z.dVal>>uint(z.dLen*2))&3])
for i := z.dLen - 1; i >= 0; i-- {
sb.WriteString(dig[(z.dVal>>uint(i*2))&3])
}
return sb.String()
}
func main() {
fmt.Println("Addition:")
g := NewZeck("10")
g.PlusAssign(NewZeck("10"))
fmt.Println(g)
g.PlusAssign(NewZeck("10"))
fmt.Println(g)
g.PlusAssign(NewZeck("1001"))
fmt.Println(g)
g.PlusAssign(NewZeck("1000"))
fmt.Println(g)
g.PlusAssign(NewZeck("10101"))
fmt.Println(g)
fmt.Println("\nSubtraction:")
g = NewZeck("1000")
g.MinusAssign(NewZeck("101"))
fmt.Println(g)
g = NewZeck("10101010")
g.MinusAssign(NewZeck("1010101"))
fmt.Println(g)
fmt.Println("\nMultiplication:")
g = NewZeck("1001")
g.TimesAssign(NewZeck("101"))
fmt.Println(g)
g = NewZeck("101010")
g.PlusAssign(NewZeck("101"))
fmt.Println(g)
} |
http://rosettacode.org/wiki/Zumkeller_numbers | Zumkeller numbers | Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the divisors are partitioned, only that the two partition sums are equal.
E.G.
6 is a Zumkeller number; The divisors {1 2 3 6} can be partitioned into two groups {1 2 3} and {6} that both sum to 6.
10 is not a Zumkeller number; The divisors {1 2 5 10} can not be partitioned into two groups in any way that will both sum to the same value.
12 is a Zumkeller number; The divisors {1 2 3 4 6 12} can be partitioned into two groups {1 3 4 6} and {2 12} that both sum to 14.
Even Zumkeller numbers are common; odd Zumkeller numbers are much less so. For values below 10^6, there is at least one Zumkeller number in every 12 consecutive integers, and the vast majority of them are even. The odd Zumkeller numbers are very similar to the list from the task Abundant odd numbers; they are nearly the same except for the further restriction that the abundance (A(n) = sigma(n) - 2n), must be even: A(n) mod 2 == 0
Task
Write a routine (function, procedure, whatever) to find Zumkeller numbers.
Use the routine to find and display here, on this page, the first 220 Zumkeller numbers.
Use the routine to find and display here, on this page, the first 40 odd Zumkeller numbers.
Optional, stretch goal: Use the routine to find and display here, on this page, the first 40 odd Zumkeller numbers that don't end with 5.
See Also
OEIS:A083207 - Zumkeller numbers to get an impression of different partitions OEIS:A083206 Zumkeller partitions
OEIS:A174865 - Odd Zumkeller numbers
Related Tasks
Abundant odd numbers
Abundant, deficient and perfect number classifications
Proper divisors , Factors of an integer | #Factor | Factor | USING: combinators grouping io kernel lists lists.lazy math
math.primes.factors memoize prettyprint sequences ;
MEMO: psum? ( seq n -- ? )
{
{ [ dup zero? ] [ 2drop t ] }
{ [ over length zero? ] [ 2drop f ] }
{ [ over last over > ] [ [ but-last ] dip psum? ] }
[
[ [ but-last ] dip psum? ]
[ over last - [ but-last ] dip psum? ] 2bi or
]
} cond ;
: zumkeller? ( n -- ? )
dup divisors dup sum
{
{ [ dup odd? ] [ 3drop f ] }
{ [ pick odd? ] [ nip swap 2 * - [ 0 > ] [ even? ] bi and ] }
[ nipd 2/ psum? ]
} cond ;
: zumkellers ( -- list )
1 lfrom [ zumkeller? ] lfilter ;
: odd-zumkellers ( -- list )
1 [ 2 + ] lfrom-by [ zumkeller? ] lfilter ;
: odd-zumkellers-no-5 ( -- list )
odd-zumkellers [ 5 mod zero? not ] lfilter ;
: show ( count list row-len -- )
[ ltake list>array ] dip group simple-table. nl ;
"First 220 Zumkeller numbers:" print
220 zumkellers 20 show
"First 40 odd Zumkeller numbers:" print
40 odd-zumkellers 10 show
"First 40 odd Zumkeller numbers not ending with 5:" print
40 odd-zumkellers-no-5 8 show |
http://rosettacode.org/wiki/Zumkeller_numbers | Zumkeller numbers | Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the divisors are partitioned, only that the two partition sums are equal.
E.G.
6 is a Zumkeller number; The divisors {1 2 3 6} can be partitioned into two groups {1 2 3} and {6} that both sum to 6.
10 is not a Zumkeller number; The divisors {1 2 5 10} can not be partitioned into two groups in any way that will both sum to the same value.
12 is a Zumkeller number; The divisors {1 2 3 4 6 12} can be partitioned into two groups {1 3 4 6} and {2 12} that both sum to 14.
Even Zumkeller numbers are common; odd Zumkeller numbers are much less so. For values below 10^6, there is at least one Zumkeller number in every 12 consecutive integers, and the vast majority of them are even. The odd Zumkeller numbers are very similar to the list from the task Abundant odd numbers; they are nearly the same except for the further restriction that the abundance (A(n) = sigma(n) - 2n), must be even: A(n) mod 2 == 0
Task
Write a routine (function, procedure, whatever) to find Zumkeller numbers.
Use the routine to find and display here, on this page, the first 220 Zumkeller numbers.
Use the routine to find and display here, on this page, the first 40 odd Zumkeller numbers.
Optional, stretch goal: Use the routine to find and display here, on this page, the first 40 odd Zumkeller numbers that don't end with 5.
See Also
OEIS:A083207 - Zumkeller numbers to get an impression of different partitions OEIS:A083206 Zumkeller partitions
OEIS:A174865 - Odd Zumkeller numbers
Related Tasks
Abundant odd numbers
Abundant, deficient and perfect number classifications
Proper divisors , Factors of an integer | #Go | Go | package main
import "fmt"
func getDivisors(n int) []int {
divs := []int{1, n}
for i := 2; i*i <= n; i++ {
if n%i == 0 {
j := n / i
divs = append(divs, i)
if i != j {
divs = append(divs, j)
}
}
}
return divs
}
func sum(divs []int) int {
sum := 0
for _, div := range divs {
sum += div
}
return sum
}
func isPartSum(divs []int, sum int) bool {
if sum == 0 {
return true
}
le := len(divs)
if le == 0 {
return false
}
last := divs[le-1]
divs = divs[0 : le-1]
if last > sum {
return isPartSum(divs, sum)
}
return isPartSum(divs, sum) || isPartSum(divs, sum-last)
}
func isZumkeller(n int) bool {
divs := getDivisors(n)
sum := sum(divs)
// if sum is odd can't be split into two partitions with equal sums
if sum%2 == 1 {
return false
}
// if n is odd use 'abundant odd number' optimization
if n%2 == 1 {
abundance := sum - 2*n
return abundance > 0 && abundance%2 == 0
}
// if n and sum are both even check if there's a partition which totals sum / 2
return isPartSum(divs, sum/2)
}
func main() {
fmt.Println("The first 220 Zumkeller numbers are:")
for i, count := 2, 0; count < 220; i++ {
if isZumkeller(i) {
fmt.Printf("%3d ", i)
count++
if count%20 == 0 {
fmt.Println()
}
}
}
fmt.Println("\nThe first 40 odd Zumkeller numbers are:")
for i, count := 3, 0; count < 40; i += 2 {
if isZumkeller(i) {
fmt.Printf("%5d ", i)
count++
if count%10 == 0 {
fmt.Println()
}
}
}
fmt.Println("\nThe first 40 odd Zumkeller numbers which don't end in 5 are:")
for i, count := 3, 0; count < 40; i += 2 {
if (i % 10 != 5) && isZumkeller(i) {
fmt.Printf("%7d ", i)
count++
if count%8 == 0 {
fmt.Println()
}
}
}
fmt.Println()
} |
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included) | Arbitrary-precision integers (included) | Using the in-built capabilities of your language, calculate the integer value of:
5
4
3
2
{\displaystyle 5^{4^{3^{2}}}}
Confirm that the first and last twenty digits of the answer are:
62060698786608744707...92256259918212890625
Find and show the number of decimal digits in the answer.
Note: Do not submit an implementation of arbitrary precision arithmetic. The intention is to show the capabilities of the language as supplied. If a language has a single, overwhelming, library of varied modules that is endorsed by its home site – such as CPAN for Perl or Boost for C++ – then that may be used instead.
Strictly speaking, this should not be solved by fixed-precision numeric libraries where the precision has to be manually set to a large value; although if this is the only recourse then it may be used with a note explaining that the precision must be set manually to a large enough value.
Related tasks
Long multiplication
Exponentiation order
exponentiation operator
Exponentiation with infix operators in (or operating on) the base
| #C.2B.2B | C++ | #include <iostream>
#include <boost/multiprecision/gmp.hpp>
#include <string>
namespace mp = boost::multiprecision;
int main(int argc, char const *argv[])
{
// We could just use (1 << 18) instead of tmpres, but let's point out one
// pecularity with gmp and hence boost::multiprecision: they won't accept
// a second mpz_int with pow(). Therefore, if we stick to multiprecision
// pow we need to convert_to<uint64_t>().
uint64_t tmpres = mp::pow(mp::mpz_int(4)
, mp::pow(mp::mpz_int(3)
, 2).convert_to<uint64_t>()
).convert_to<uint64_t>();
mp::mpz_int res = mp::pow(mp::mpz_int(5), tmpres);
std::string s = res.str();
std::cout << s.substr(0, 20)
<< "..."
<< s.substr(s.length() - 20, 20) << std::endl;
return 0;
}
|
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included) | Arbitrary-precision integers (included) | Using the in-built capabilities of your language, calculate the integer value of:
5
4
3
2
{\displaystyle 5^{4^{3^{2}}}}
Confirm that the first and last twenty digits of the answer are:
62060698786608744707...92256259918212890625
Find and show the number of decimal digits in the answer.
Note: Do not submit an implementation of arbitrary precision arithmetic. The intention is to show the capabilities of the language as supplied. If a language has a single, overwhelming, library of varied modules that is endorsed by its home site – such as CPAN for Perl or Boost for C++ – then that may be used instead.
Strictly speaking, this should not be solved by fixed-precision numeric libraries where the precision has to be manually set to a large value; although if this is the only recourse then it may be used with a note explaining that the precision must be set manually to a large enough value.
Related tasks
Long multiplication
Exponentiation order
exponentiation operator
Exponentiation with infix operators in (or operating on) the base
| #Ceylon | Ceylon | import ceylon.whole {
wholeNumber,
two
}
shared void run() {
value five = wholeNumber(5);
value four = wholeNumber(4);
value three = wholeNumber(3);
value bigNumber = five ^ four ^ three ^ two;
value firstTwenty = "62060698786608744707";
value lastTwenty = "92256259918212890625";
value bigString = bigNumber.string;
"The number must start with ``firstTwenty`` and end with ``lastTwenty``"
assert(bigString.startsWith(firstTwenty), bigString.endsWith(lastTwenty));
value bigSize = bigString.size;
print("The first twenty digits are ``bigString[...19]``");
print("The last twenty digits are ``bigString[(bigSize - 20)...]``");
print("The number of digits in 5^4^3^2 is ``bigSize``");
} |
http://rosettacode.org/wiki/Zhang-Suen_thinning_algorithm | Zhang-Suen thinning algorithm | This is an algorithm used to thin a black and white i.e. one bit per pixel images.
For example, with an input image of:
################# #############
################## ################
################### ##################
######## ####### ###################
###### ####### ####### ######
###### ####### #######
################# #######
################ #######
################# #######
###### ####### #######
###### ####### #######
###### ####### ####### ######
######## ####### ###################
######## ####### ###### ################## ######
######## ####### ###### ################ ######
######## ####### ###### ############# ######
It produces the thinned output:
# ########## #######
## # #### #
# # ##
# # #
# # #
# # #
############ #
# # #
# # #
# # #
# # #
# ##
# ############
### ###
Algorithm
Assume black pixels are one and white pixels zero, and that the input image is a rectangular N by M array of ones and zeroes.
The algorithm operates on all black pixels P1 that can have eight neighbours.
The neighbours are, in order, arranged as:
P9 P2 P3
P8 P1 P4
P7 P6 P5
Obviously the boundary pixels of the image cannot have the full eight neighbours.
Define
A
(
P
1
)
{\displaystyle A(P1)}
= the number of transitions from white to black, (0 -> 1) in the sequence P2,P3,P4,P5,P6,P7,P8,P9,P2. (Note the extra P2 at the end - it is circular).
Define
B
(
P
1
)
{\displaystyle B(P1)}
= The number of black pixel neighbours of P1. ( = sum(P2 .. P9) )
Step 1
All pixels are tested and pixels satisfying all the following conditions (simultaneously) are just noted at this stage.
(0) The pixel is black and has eight neighbours
(1)
2
<=
B
(
P
1
)
<=
6
{\displaystyle 2<=B(P1)<=6}
(2) A(P1) = 1
(3) At least one of P2 and P4 and P6 is white
(4) At least one of P4 and P6 and P8 is white
After iterating over the image and collecting all the pixels satisfying all step 1 conditions, all these condition satisfying pixels are set to white.
Step 2
All pixels are again tested and pixels satisfying all the following conditions are just noted at this stage.
(0) The pixel is black and has eight neighbours
(1)
2
<=
B
(
P
1
)
<=
6
{\displaystyle 2<=B(P1)<=6}
(2) A(P1) = 1
(3) At least one of P2 and P4 and P8 is white
(4) At least one of P2 and P6 and P8 is white
After iterating over the image and collecting all the pixels satisfying all step 2 conditions, all these condition satisfying pixels are again set to white.
Iteration
If any pixels were set in this round of either step 1 or step 2 then all steps are repeated until no image pixels are so changed.
Task
Write a routine to perform Zhang-Suen thinning on an image matrix of ones and zeroes.
Use the routine to thin the following image and show the output here on this page as either a matrix of ones and zeroes, an image, or an ASCII-art image of space/non-space characters.
00000000000000000000000000000000
01111111110000000111111110000000
01110001111000001111001111000000
01110000111000001110000111000000
01110001111000001110000000000000
01111111110000001110000000000000
01110111100000001110000111000000
01110011110011101111001111011100
01110001111011100111111110011100
00000000000000000000000000000000
Reference
Zhang-Suen Thinning Algorithm, Java Implementation by Nayef Reza.
"Character Recognition Systems: A Guide for Students and Practitioners" By Mohamed Cheriet, Nawwaf Kharma, Cheng-Lin Liu, Ching Suen
| #J | J | isBlackPx=: '1'&=;._2 NB. boolean array of black pixels
toImage=: [: , LF ,.~ '01' {~ ] NB. convert to original representation
frameImg=: 0 ,. 0 , >:@$ {. ] NB. adds border of 0's to image
neighbrs=: 1 :'(1 1 ,: 3 3)&(u;._3)' NB. applies verb u to neighbourhoods
Bdry=: 1 2 5 8 7 6 3 0 1 NB. map pixel index to neighbour order
getPx=: { , NB. get desired pixels from neighbourhood
Ap1=: [: +/ 2 </\ Bdry&getPx NB. count 0->1 transitions
Bp1=: [: +/ [: }. Bdry&getPx NB. count black neighbours
c11=: (2&<: *. <:&6)@Bp1 NB. step 1, condition 1
c12=: 1 = Ap1 NB. ...
c13=: 0 e. 1 5 7&getPx
c14=: 0 e. 5 7 3&getPx
c23=: 0 e. 1 5 3&getPx NB. step2, condition 3
c24=: 0 e. 1 7 3&getPx
cond1=: c11 *. c12 *. c13 *. c14 NB. step1 conditions
cond2=: c11 *. c12 *. c23 *. c24 NB. step2 conditions
whiten=: [ * -.@:*. NB. make black pixels white
step1=: whiten frameImg@(cond1 neighbrs)
step2=: whiten frameImg@(cond2 neighbrs)
zhangSuen=: [: toImage [: step2@step1^:_ isBlackPx |
http://rosettacode.org/wiki/Zeckendorf_number_representation | Zeckendorf number representation | Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series.
Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13.
The decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100.
10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that no two consecutive Fibonacci numbers can be used which leads to the former unique solution.
Task
Generate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order.
The intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task.
Also see
OEIS A014417 for the the sequence of required results.
Brown's Criterion - Numberphile
Related task
Fibonacci sequence
| #Crystal | Crystal | def zeckendorf(n)
return 0 if n.zero?
fib = [1, 2]
while fib[-1] < n; fib << fib[-2] + fib[-1] end
digit = ""
fib.reverse_each do |f|
if f <= n
digit, n = digit + "1", n - f
else
digit += "0"
end
end
digit.to_i
end
(0..20).each { |i| puts "%3d: %8d" % [i, zeckendorf(i)] } |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #BlooP | BlooP |
DEFINE PROCEDURE ''DIVIDE'' [A,B]:
BLOCK 0: BEGIN
IF A < B, THEN:
QUIT BLOCK 0;
CELL(0) <= 1;
OUTPUT <= 1;
LOOP AT MOST A TIMES:
BLOCK 2: BEGIN
IF OUTPUT * B = A, THEN:
QUIT BLOCK 0;
OUTPUT <= OUTPUT + 1;
IF OUTPUT * B > A, THEN:
BLOCK 3: BEGIN
OUTPUT <= CELL(0);
QUIT BLOCK 0;
BLOCK 3: END;
CELL(0) <= OUTPUT;
BLOCK 2: END;
BLOCK 0: END.
DEFINE PROCEDURE ''MINUS'' [A,B]:
BLOCK 0: BEGIN
IF A < B, THEN:
QUIT BLOCK 0;
LOOP AT MOST A TIMES:
BLOCK 1: BEGIN
IF OUTPUT + B = A, THEN:
QUIT BLOCK 0;
OUTPUT <= OUTPUT + 1;
BLOCK 1: END;
BLOCK 0: END.
DEFINE PROCEDURE ''MODULUS'' [A,B]:
BLOCK 0: BEGIN
CELL(0) <= DIVIDE[A,B];
OUTPUT <= MINUS[A,CELL(0) * B];
BLOCK 0: END.
DEFINE PROCEDURE ''TOGGLE'' [DOOR]:
BLOCK 0: BEGIN
IF DOOR = 1, THEN:
QUIT BLOCK 0;
OUTPUT <= 1;
BLOCK 0: END.
DEFINE PROCEDURE ''NUMBERS'' [DOOR, COUNT]:
BLOCK 0: BEGIN
CELL(0) <= 1; /*each number*/
OUTPUT <= 0; /*current door state*/
LOOP COUNT TIMES:
BLOCK 1: BEGIN
IF MODULUS[DOOR, CELL(0)] = 0, THEN:
OUTPUT <= TOGGLE[OUTPUT];
CELL(0) <= CELL(0) + 1;
BLOCK 1: END;
BLOCK 0: END.
DEFINE PROCEDURE ''DOORS'' [COUNT]:
BLOCK 0: BEGIN
CELL(0) <= 1; /*each door*/
LOOP COUNT TIMES:
BLOCK 1: BEGIN
CELL(1) <= NUMBERS[CELL(0), COUNT]; /*iterate over the states of this door to get its final state*/
IF CELL(1) = 1, THEN: /*door state = open*/
PRINT[CELL(0), ' '];
CELL(0) <= CELL(0) + 1;
BLOCK 1: END;
BLOCK 0: END.
DOORS[100];
|
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #EasyLang | EasyLang | len f[] 3
for i range len f[]
f[i] = i
.
f[] &= 3
for i range len f[]
print f[i]
. |
http://rosettacode.org/wiki/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part", where the imaginary part is the number to be multiplied by
i
{\displaystyle i}
.
Task
Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.)
Print the results for each operation tested.
Optional: Show complex conjugation.
By definition, the complex conjugate of
a
+
b
i
{\displaystyle a+bi}
is
a
−
b
i
{\displaystyle a-bi}
Some languages have complex number libraries available. If your language does, show the operations. If your language does not, also show the definition of this type.
| #ooRexx | ooRexx | c1 = .complex~new(1, 2)
c2 = .complex~new(3, 4)
r = 7
say "c1 =" c1
say "c2 =" c2
say "r =" r
say "-c1 =" (-c1)
say "c1 + r =" c1 + r
say "c1 + c2 =" c1 + c2
say "c1 - r =" c1 - r
say "c1 - c2 =" c1 - c2
say "c1 * r =" c1 * r
say "c1 * c2 =" c1 * c2
say "inv(c1) =" c1~inv
say "conj(c1) =" c1~conjugate
say "c1 / r =" c1 / r
say "c1 / c2 =" c1 / c2
say "c1 == c1 =" (c1 == c1)
say "c1 == c2 =" (c1 == c2)
::class complex
::method init
expose r i
use strict arg r, i = 0
-- complex instances are immutable, so these are
-- read only attributes
::attribute r GET
::attribute i GET
::method negative
expose r i
return self~class~new(-r, -i)
::method add
expose r i
use strict arg other
if other~isa(.complex) then
return self~class~new(r + other~r, i + other~i)
else return self~class~new(r + other, i)
::method subtract
expose r i
use strict arg other
if other~isa(.complex) then
return self~class~new(r - other~r, i - other~i)
else return self~class~new(r - other, i)
::method times
expose r i
use strict arg other
if other~isa(.complex) then
return self~class~new(r * other~r - i * other~i, r * other~i + i * other~r)
else return self~class~new(r * other, i * other)
::method inv
expose r i
denom = r * r + i * i
return self~class~new(r/denom,-i/denom)
::method conjugate
expose r i
return self~class~new(r, -i)
::method divide
use strict arg other
-- this is easier if everything is a complex number
if \other~isA(.complex) then other = .complex~new(other)
-- division is multiplication with the inversion
return self * other~inv
::method "=="
expose r i
use strict arg other
if \other~isa(.complex) then return .false
-- Note: these are numeric comparisons, so we're using the "="
-- method so those are handled correctly
return r = other~r & i = other~i
::method "\=="
use strict arg other
return \self~"\=="(other)
::method "="
-- this is equivalent of "=="
forward message("==")
::method "\="
-- this is equivalent of "\=="
forward message("\==")
::method "<>"
-- this is equivalent of "\=="
forward message("\==")
::method "><"
-- this is equivalent of "\=="
forward message("\==")
-- some operator overrides -- these only work if the left-hand-side of the
-- subexpression is a quaternion
::method "*"
forward message("TIMES")
::method "/"
forward message("DIVIDE")
::method "-"
-- need to check if this is a prefix minus or a subtract
if arg() == 0 then
forward message("NEGATIVE")
else
forward message("SUBTRACT")
::method "+"
-- need to check if this is a prefix plus or an addition
if arg() == 0 then
return self -- we can return this copy since it is immutable
else
forward message("ADD")
::method string
expose r i
return r self~formatnumber(i)"i"
::method formatnumber private
use arg value
if value > 0 then return "+" value
else return "-" value~abs
-- override hashcode for collection class hash uses
::method hashCode
expose r i
return r~hashcode~bitxor(i~hashcode) |
http://rosettacode.org/wiki/Arithmetic/Rational | Arithmetic/Rational | Task
Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language.
Example
Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number).
Further define the appropriate rational unary operators abs and '-', with the binary operators for addition '+', subtraction '-', multiplication '×', division '/', integer division '÷', modulo division, the comparison operators (e.g. '<', '≤', '>', & '≥') and equality operators (e.g. '=' & '≠').
Define standard coercion operators for casting int to frac etc.
If space allows, define standard increment and decrement operators (e.g. '+:=' & '-:=' etc.).
Finally test the operators:
Use the new type frac to find all perfect numbers less than 219 by summing the reciprocal of the factors.
Related task
Perfect Numbers
| #Prolog | Prolog |
divisor(N, Div) :-
Max is floor(sqrt(N)),
between(1, Max, D),
divmod(N, D, _, 0),
(Div = D; Div is N div D, Div =\= D).
divisors(N, Divs) :-
setof(M, divisor(N, M), Divs).
recip(A, B) :- B is 1 rdiv A.
sumrecip(N, A) :-
divisors(N, [1 | Ds]),
maplist(recip, Ds, As),
sum_list(As, A).
perfect(X) :- sumrecip(X, 1).
main :-
Limit is 1 << 19,
forall(
(between(1, Limit, N), perfect(N)),
(format("~w~n", [N]))),
halt.
?- main.
|
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geometric mean of two numbers.
The arithmetic-geometric mean of two numbers can be (usefully) denoted as
a
g
m
(
a
,
g
)
{\displaystyle \mathrm {agm} (a,g)}
, and is equal to the limit of the sequence:
a
0
=
a
;
g
0
=
g
{\displaystyle a_{0}=a;\qquad g_{0}=g}
a
n
+
1
=
1
2
(
a
n
+
g
n
)
;
g
n
+
1
=
a
n
g
n
.
{\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.}
Since the limit of
a
n
−
g
n
{\displaystyle a_{n}-g_{n}}
tends (rapidly) to zero with iterations, this is an efficient method.
Demonstrate the function by calculating:
a
g
m
(
1
,
1
/
2
)
{\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})}
Also see
mathworld.wolfram.com/Arithmetic-Geometric Mean
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "float.s7i";
include "math.s7i";
const func float: agm (in var float: a, in var float: g) is func
result
var float: agm is 0.0;
local
const float: iota is 1.0E-7;
var float: a1 is 0.0;
var float: g1 is 0.0;
begin
if a * g < 0.0 then
raise RANGE_ERROR;
else
while abs(a - g) > iota do
a1 := (a + g) / 2.0;
g1 := sqrt(a * g);
a := a1;
g := g1;
end while;
agm := a;
end if;
end func;
const proc: main is func
begin
writeln(agm(1.0, 2.0) digits 6);
writeln(agm(1.0, 1.0 / sqrt(2.0)) digits 6);
end func; |
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geometric mean of two numbers.
The arithmetic-geometric mean of two numbers can be (usefully) denoted as
a
g
m
(
a
,
g
)
{\displaystyle \mathrm {agm} (a,g)}
, and is equal to the limit of the sequence:
a
0
=
a
;
g
0
=
g
{\displaystyle a_{0}=a;\qquad g_{0}=g}
a
n
+
1
=
1
2
(
a
n
+
g
n
)
;
g
n
+
1
=
a
n
g
n
.
{\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.}
Since the limit of
a
n
−
g
n
{\displaystyle a_{n}-g_{n}}
tends (rapidly) to zero with iterations, this is an efficient method.
Demonstrate the function by calculating:
a
g
m
(
1
,
1
/
2
)
{\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})}
Also see
mathworld.wolfram.com/Arithmetic-Geometric Mean
| #SequenceL | SequenceL | import <Utilities/Math.sl>;
agm(a, g) :=
let
iota := 1.0e-15;
arithmeticMean := 0.5 * (a + g);
geometricMean := sqrt(a * g);
in
a when abs(a-g) < iota
else
agm(arithmeticMean, geometricMean);
main := agm(1.0, 1.0 / sqrt(2)); |
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, you may also try something like:
x = 0
y = 0
z = x**y
say 'z=' z
Show the result here.
And of course use any symbols or notation that is supported in your computer programming language for exponentiation.
See also
The Wiki entry: Zero to the power of zero.
The Wiki entry: History of differing points of view.
The MathWorld™ entry: exponent laws.
Also, in the above MathWorld™ entry, see formula (9):
x
0
=
1
{\displaystyle x^{0}=1}
.
The OEIS entry: The special case of zero to the zeroth power
| #Fermat | Fermat | 0^0 |
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, you may also try something like:
x = 0
y = 0
z = x**y
say 'z=' z
Show the result here.
And of course use any symbols or notation that is supported in your computer programming language for exponentiation.
See also
The Wiki entry: Zero to the power of zero.
The Wiki entry: History of differing points of view.
The MathWorld™ entry: exponent laws.
Also, in the above MathWorld™ entry, see formula (9):
x
0
=
1
{\displaystyle x^{0}=1}
.
The OEIS entry: The special case of zero to the zeroth power
| #Forth | Forth | 0e 0e f** f. |
http://rosettacode.org/wiki/Zig-zag_matrix | Zig-zag matrix | Task
Produce a zig-zag array.
A zig-zag array is a square arrangement of the first N2 natural numbers, where the
numbers increase sequentially as you zig-zag along the array's anti-diagonals.
For a graphical representation, see JPG zigzag (JPG uses such arrays to encode images).
For example, given 5, produce this array:
0 1 5 6 14
2 4 7 13 15
3 8 12 16 21
9 11 17 20 22
10 18 19 23 24
Related tasks
Spiral matrix
Identity matrix
Ulam spiral (for primes)
See also
Wiktionary entry: anti-diagonals
| #Action.21 | Action! | DEFINE MAX_SIZE="10"
DEFINE MAX_MATRIX_SIZE="100"
INT FUNC Index(BYTE size,x,y)
RETURN (x+y*size)
PROC PrintMatrix(BYTE ARRAY a BYTE size)
BYTE i,j,v
FOR j=0 TO size-1
DO
FOR i=0 TO size-1
DO
v=a(Index(size,i,j))
IF v<10 THEN
Print(" ")
ELSE
Print(" ")
FI
PrintB(v)
OD
PutE()
OD
RETURN
PROC FillMatrix(BYTE ARRAY a BYTE size)
BYTE start,end
INT dir,i,j
start=0 end=size*size-1
i=0 j=0 dir=1
DO
a(Index(size,i,j))=start
a(Index(size,size-1-i,size-1-j))=end
start==+1 end==-1
i==+dir j==-dir
IF i<0 THEN
i==+1 dir=-dir
ELSEIF j<0 THEN
j==+1 dir=-dir
FI
UNTIL start>=end
OD
IF start=end THEN
a(Index(size,i,j))=start
FI
RETURN
PROC Test(BYTE size)
BYTE ARRAY mat(MAX_MATRIX_SIZE)
PrintF("Matrix size: %B%E",size)
FillMatrix(mat,size)
PrintMatrix(mat,size)
PutE()
RETURN
PROC Main()
Test(5)
Test(6)
RETURN |
http://rosettacode.org/wiki/Yellowstone_sequence | Yellowstone sequence | The Yellowstone sequence, also called the Yellowstone permutation, is defined as:
For n <= 3,
a(n) = n
For n >= 4,
a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and
is not relatively prime to a(n-2).
The sequence is a permutation of the natural numbers, and gets its name from what its authors felt was a spiking, geyser like appearance of a plot of the sequence.
Example
a(4) is 4 because 4 is the smallest number following 1, 2, 3 in the sequence that is relatively prime to the entry before it (3), and is not relatively prime to the number two entries before it (2).
Task
Find and show as output the first 30 Yellowstone numbers.
Extra
Demonstrate how to plot, with x = n and y coordinate a(n), the first 100 Yellowstone numbers.
Related tasks
Greatest common divisor.
Plot coordinate pairs.
See also
The OEIS entry: A098550 The Yellowstone permutation.
Applegate et al, 2015: The Yellowstone Permutation [1].
| #Action.21 | Action! | BYTE FUNC Gcd(BYTE a,b)
BYTE tmp
IF a<b THEN
tmp=a a=b b=tmp
FI
WHILE b#0
DO
tmp=a MOD b
a=b b=tmp
OD
RETURN (a)
BYTE FUNC Contains(BYTE ARRAY a BYTE len,value)
BYTE i
FOR i=0 TO len-1
DO
IF a(i)=value THEN
RETURN (1)
FI
OD
RETURN (0)
PROC Generate(BYTE ARRAY seq BYTE count)
BYTE i,x
seq(0)=1 seq(1)=2 seq(2)=3
FOR i=3 TO COUNT-1
DO
x=1
DO
IF Contains(seq,i,x)=0 AND
Gcd(x,seq(i-1))=1 AND Gcd(x,seq(i-2))>1 THEN
EXIT
FI
x==+1
OD
seq(i)=x
OD
RETURN
PROC Main()
DEFINE COUNT="30"
BYTE ARRAY seq(COUNT)
BYTE i
Generate(seq,COUNT)
PrintF("First %B Yellowstone numbers:%E",COUNT)
FOR i=0 TO COUNT-1
DO
PrintB(seq(i)) Put(32)
OD
RETURN |
http://rosettacode.org/wiki/Yellowstone_sequence | Yellowstone sequence | The Yellowstone sequence, also called the Yellowstone permutation, is defined as:
For n <= 3,
a(n) = n
For n >= 4,
a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and
is not relatively prime to a(n-2).
The sequence is a permutation of the natural numbers, and gets its name from what its authors felt was a spiking, geyser like appearance of a plot of the sequence.
Example
a(4) is 4 because 4 is the smallest number following 1, 2, 3 in the sequence that is relatively prime to the entry before it (3), and is not relatively prime to the number two entries before it (2).
Task
Find and show as output the first 30 Yellowstone numbers.
Extra
Demonstrate how to plot, with x = n and y coordinate a(n), the first 100 Yellowstone numbers.
Related tasks
Greatest common divisor.
Plot coordinate pairs.
See also
The OEIS entry: A098550 The Yellowstone permutation.
Applegate et al, 2015: The Yellowstone Permutation [1].
| #Ada | Ada | with Ada.Text_IO;
with Ada.Containers.Ordered_Sets;
procedure Yellowstone_Sequence is
generic -- Allow more than one generator, but must be instantiated
package Yellowstones is
function Next return Integer;
function GCD (Left, Right : Integer) return Integer;
end Yellowstones;
package body Yellowstones
is
package Sequences is
new Ada.Containers.Ordered_Sets (Integer);
-- Internal package state
N_0 : Integer := 0;
N_1 : Integer := 0;
N_2 : Integer := 0;
Seq : Sequences.Set;
Min : Integer := 1;
function GCD (Left, Right : Integer) return Integer
is (if Right = 0
then Left
else GCD (Right, Left mod Right));
function Next return Integer is
begin
N_2 := N_1;
N_1 := N_0;
if N_0 < 3 then
N_0 := N_0 + 1;
else
N_0 := Min;
while
not (not Seq.Contains (N_0)
and then GCD (N_1, N_0) = 1
and then GCD (N_2, N_0) > 1)
loop
N_0 := N_0 + 1;
end loop;
end if;
Seq.Insert (N_0);
while Seq.Contains (Min) loop
Seq.Delete (Min);
Min := Min + 1;
end loop;
return N_0;
end Next;
end Yellowstones;
procedure First_30 is
package Yellowstone is new Yellowstones; -- New generator instance
use Ada.Text_IO;
begin
Put_Line ("First 30 Yellowstone numbers:");
for A in 1 .. 30 loop
Put (Yellowstone.Next'Image); Put (" ");
end loop;
New_Line;
end First_30;
begin
First_30;
end Yellowstone_Sequence; |
http://rosettacode.org/wiki/Arithmetic_evaluation | Arithmetic evaluation | Create a program which parses and evaluates arithmetic expressions.
Requirements
An abstract-syntax tree (AST) for the expression must be created from parsing the input.
The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.)
The expression will be a string or list of symbols like "(1+3)*7".
The four symbols + - * / must be supported as binary operators with conventional precedence rules.
Precedence-control parentheses must also be supported.
Note
For those who don't remember, mathematical precedence is as follows:
Parentheses
Multiplication/Division (left to right)
Addition/Subtraction (left to right)
C.f
24 game Player.
Parsing/RPN calculator algorithm.
Parsing/RPN to infix conversion.
| #Pop11 | Pop11 | /* Scanner routines */
/* Uncomment the following to parse data from standard input
vars itemrep;
incharitem(charin) -> itemrep;
*/
;;; Current symbol
vars sym;
define get_sym();
itemrep() -> sym;
enddefine;
define expect(x);
lvars x;
if x /= sym then
printf(x, 'Error, expected %p\n');
mishap(sym, 1, 'Example parser error');
endif;
get_sym();
enddefine;
lconstant res_list = [( ) + * ];
lconstant reserved = newproperty(
maplist(res_list, procedure(x); [^x ^(true)]; endprocedure),
20, false, "perm");
/*
Parser for arithmetic expressions
*/
/*
expr: term
| expr "+" term
| expr "-" term
;
*/
define do_expr() -> result;
lvars result = do_term(), op;
while sym = "+" or sym = "-" do
sym -> op;
get_sym();
[^op ^result ^(do_term())] -> result;
endwhile;
enddefine;
/*
term: factor
| term "*" factor
| term "/" factor
;
*/
define do_term() -> result;
lvars result = do_factor(), op;
while sym = "*" or sym = "/" do
sym -> op;
get_sym();
[^op ^result ^(do_factor())] -> result;
endwhile;
enddefine;
/*
factor: word
| constant
| "(" expr ")"
;
*/
define do_factor() -> result;
if sym = "(" then
get_sym();
do_expr() -> result;
expect(")");
elseif isinteger(sym) or isbiginteger(sym) then
sym -> result;
get_sym();
else
if reserved(sym) then
printf(sym, 'unexpected symbol %p\n');
mishap(sym, 1, 'Example parser syntax error');
endif;
sym -> result;
get_sym();
endif;
enddefine;
/* Expression evaluator, returns false on error (currently only
division by 0 */
define arith_eval(expr);
lvars op, arg1, arg2;
if not(expr) then
return(expr);
endif;
if isinteger(expr) or isbiginteger(expr) then
return(expr);
endif;
expr(1) -> op;
arith_eval(expr(2)) -> arg1;
arith_eval(expr(3)) -> arg2;
if not(arg1) or not(arg2) then
return(false);
endif;
if op = "+" then
return(arg1 + arg2);
elseif op = "-" then
return(arg1 - arg2);
elseif op = "*" then
return(arg1 * arg2);
elseif op = "/" then
if arg2 = 0 then
return(false);
else
return(arg1 div arg2);
endif;
else
printf('Internal error\n');
return(false);
endif;
enddefine;
/* Given list, create item repeater. Input list is stored in a
closure are traversed when new item is requested. */
define listitemrep(lst);
procedure();
lvars item;
if lst = [] then
termin;
else
front(lst) -> item;
back(lst) -> lst;
item;
endif;
endprocedure;
enddefine;
/* Initialise scanner */
listitemrep([(3 + 50) * 7 - 100 / 10]) -> itemrep;
get_sym();
;;; Test it
arith_eval(do_expr()) => |
http://rosettacode.org/wiki/Arithmetic_evaluation | Arithmetic evaluation | Create a program which parses and evaluates arithmetic expressions.
Requirements
An abstract-syntax tree (AST) for the expression must be created from parsing the input.
The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.)
The expression will be a string or list of symbols like "(1+3)*7".
The four symbols + - * / must be supported as binary operators with conventional precedence rules.
Precedence-control parentheses must also be supported.
Note
For those who don't remember, mathematical precedence is as follows:
Parentheses
Multiplication/Division (left to right)
Addition/Subtraction (left to right)
C.f
24 game Player.
Parsing/RPN calculator algorithm.
Parsing/RPN to infix conversion.
| #Prolog | Prolog | % Lexer
numeric(X) :- 48 =< X, X =< 57.
not_numeric(X) :- 48 > X ; X > 57.
lex1([], []).
lex1([40|Xs], ['('|Ys]) :- lex1(Xs, Ys).
lex1([41|Xs], [')'|Ys]) :- lex1(Xs, Ys).
lex1([43|Xs], ['+'|Ys]) :- lex1(Xs, Ys).
lex1([45|Xs], ['-'|Ys]) :- lex1(Xs, Ys).
lex1([42|Xs], ['*'|Ys]) :- lex1(Xs, Ys).
lex1([47|Xs], ['/'|Ys]) :- lex1(Xs, Ys).
lex1([X|Xs], [N|Ys]) :- numeric(X), N is X - 48, lex1(Xs, Ys).
lex2([], []).
lex2([X], [X]).
lex2([Xa,Xb|Xs], [Xa|Ys]) :- atom(Xa), lex2([Xb|Xs], Ys).
lex2([Xa,Xb|Xs], [Xa|Ys]) :- number(Xa), atom(Xb), lex2([Xb|Xs], Ys).
lex2([Xa,Xb|Xs], [Y|Ys]) :- number(Xa), number(Xb), N is Xa * 10 + Xb, lex2([N|Xs], [Y|Ys]).
% Parser
oper(1, *, X, Y, X * Y). oper(1, /, X, Y, X / Y).
oper(2, +, X, Y, X + Y). oper(2, -, X, Y, X - Y).
num(D) --> [D], {number(D)}.
expr(0, Z) --> num(Z).
expr(0, Z) --> {Z = (X)}, ['('], expr(2, X), [')'].
expr(N, Z) --> {succ(N0, N)}, {oper(N, Op, X, Y, Z)}, expr(N0, X), [Op], expr(N, Y).
expr(N, Z) --> {succ(N0, N)}, expr(N0, Z).
parse(Tokens, Expr) :- expr(2, Expr, Tokens, []).
% Evaluator
evaluate(E, E) :- number(E).
evaluate(A + B, E) :- evaluate(A, Ae), evaluate(B, Be), E is Ae + Be.
evaluate(A - B, E) :- evaluate(A, Ae), evaluate(B, Be), E is Ae - Be.
evaluate(A * B, E) :- evaluate(A, Ae), evaluate(B, Be), E is Ae * Be.
evaluate(A / B, E) :- evaluate(A, Ae), evaluate(B, Be), E is Ae / Be.
% Solution
calculator(String, Value) :-
string_codes(String, Codes),
lex1(Codes, Tokens1),
lex2(Tokens1, Tokens2),
parse(Tokens2, Expression),
evaluate(Expression, Value).
% Example use
% calculator("(3+50)*7-9", X). |
http://rosettacode.org/wiki/Zeckendorf_arithmetic | Zeckendorf arithmetic | This task is a total immersion zeckendorf task; using decimal numbers will attract serious disapprobation.
The task is to implement addition, subtraction, multiplication, and division using Zeckendorf number representation. Optionally provide decrement, increment and comparitive operation functions.
Addition
Like binary 1 + 1 = 10, note carry 1 left. There the similarity ends. 10 + 10 = 101, note carry 1 left and 1 right. 100 + 100 = 1001, note carry 1 left and 2 right, this is the general case.
Occurrences of 11 must be changed to 100. Occurrences of 111 may be changed from the right by replacing 11 with 100, or from the left converting 111 to 100 + 100;
Subtraction
10 - 1 = 1. The general rule is borrow 1 right carry 1 left. eg:
abcde
10100 -
1000
_____
100 borrow 1 from a leaves 100
+ 100 add the carry
_____
1001
A larger example:
abcdef
100100 -
1000
______
1*0100 borrow 1 from b
+ 100 add the carry
______
1*1001
Sadly we borrowed 1 from b which didn't have it to lend. So now b borrows from a:
1001
+ 1000 add the carry
____
10100
Multiplication
Here you teach your computer its zeckendorf tables. eg. 101 * 1001:
a = 1 * 101 = 101
b = 10 * 101 = a + a = 10000
c = 100 * 101 = b + a = 10101
d = 1000 * 101 = c + b = 101010
1001 = d + a therefore 101 * 1001 =
101010
+ 101
______
1000100
Division
Lets try 1000101 divided by 101, so we can use the same table used for multiplication.
1000101 -
101010 subtract d (1000 * 101)
_______
1000 -
101 b and c are too large to subtract, so subtract a
____
1 so 1000101 divided by 101 is d + a (1001) remainder 1
Efficient algorithms for Zeckendorf arithmetic is interesting. The sections on addition and subtraction are particularly relevant for this task.
| #Haskell | Haskell | {-# LANGUAGE LambdaCase #-}
import Data.List (find, mapAccumL)
import Control.Arrow (first, second)
-- Generalized Fibonacci series defined for any Num instance, and for Zeckendorf numbers as well.
-- Used to build Zeckendorf tables.
fibs :: Num a => a -> a -> [a]
fibs a b = res
where
res = a : b : zipWith (+) res (tail res)
data Fib = Fib { sign :: Int, digits :: [Int]}
-- smart constructor
mkFib s ds =
case dropWhile (==0) ds of
[] -> 0
ds -> Fib s (reverse ds)
-- Textual representation
instance Show Fib where
show (Fib s ds) = sig s ++ foldMap show (reverse ds)
where sig = \case { -1 -> "-"; s -> "" }
-- Equivalence relation
instance Eq Fib where
Fib sa a == Fib sb b = sa == sb && a == b
-- Order relation
instance Ord Fib where
a `compare` b =
sign a `compare` sign b <>
case find (/= 0) $ alignWith (-) (digits a) (digits b) of
Nothing -> EQ
Just 1 -> if sign a > 0 then GT else LT
Just (-1) -> if sign a > 0 then LT else GT
-- Arithmetic
instance Num Fib where
negate (Fib s ds) = Fib (negate s) ds
abs (Fib s ds) = Fib 1 ds
signum (Fib s _) = fromIntegral s
fromInteger n =
case compare n 0 of
LT -> negate $ fromInteger (- n)
EQ -> Fib 0 [0]
GT -> Fib 1 . reverse . fst $ divModFib n 1
0 + a = a
a + 0 = a
a + b =
case (sign a, sign b) of
( 1, 1) -> res
(-1, 1) -> b - (-a)
( 1,-1) -> a - (-b)
(-1,-1) -> - ((- a) + (- b))
where
res = mkFib 1 . process $ 0:0:c
c = alignWith (+) (digits a) (digits b)
-- use cellular automata
process =
runRight 3 r2 . runLeftR 3 r2 . runRightR 4 r1
0 - a = -a
a - 0 = a
a - b =
case (sign a, sign b) of
( 1, 1) -> res
(-1, 1) -> - ((-a) + b)
( 1,-1) -> a + (-b)
(-1,-1) -> - ((-a) - (-b))
where
res = case find (/= 0) c of
Just 1 -> mkFib 1 . process $ c
Just (-1) -> - (b - a)
Nothing -> 0
c = alignWith (-) (digits a) (digits b)
-- use cellular automata
process =
runRight 3 r2 . runLeftR 3 r2 . runRightR 4 r1 . runRight 3 r3
0 * a = 0
a * 0 = 0
1 * a = a
a * 1 = a
a * b =
case (sign a, sign b) of
(1, 1) -> res
(-1, 1) -> - ((-a) * b)
( 1,-1) -> - (a * (-b))
(-1,-1) -> ((-a) * (-b))
where
-- use Zeckendorf table
table = fibs a (a + a)
res = sum $ onlyOnes $ zip (digits b) table
onlyOnes = map snd . filter ((==1) . fst)
-- Enumeration
instance Enum Fib where
toEnum = fromInteger . fromIntegral
fromEnum = fromIntegral . toInteger
instance Real Fib where
toRational = fromInteger . toInteger
-- Integral division
instance Integral Fib where
toInteger (Fib s ds) = signum (fromIntegral s) * res
where
res = sum (zipWith (*) (fibs 1 2) (fromIntegral <$> ds))
quotRem 0 _ = (0, 0)
quotRem a 0 = error "divide by zero"
quotRem a b = case (sign a, sign b) of
(1, 1) -> first (mkFib 1) $ divModFib a b
(-1, 1) -> second negate . first negate $ quotRem (-a) b
( 1,-1) -> first negate $ quotRem a (-b)
(-1,-1) -> second negate $ quotRem (-a) (-b)
------------------------------------------------------------
-- helper funtions
-- general division using Zeckendorf table
divModFib :: (Ord a, Num c, Num a) => a -> a -> ([c], a)
divModFib a b = (q, r)
where
(r, q) = mapAccumL f a $ reverse $ takeWhile (<= a) table
table = fibs b (b+b)
f n x = if n < x then (n, 0) else (n - x, 1)
-- application of rewriting rules
-- runs window from left to right
runRight n f = go
where
go [] = []
go lst = let (w, r) = splitAt n lst
(h: t) = f w
in h : go (t ++ r)
-- runs window from left to right and reverses the result
runRightR n f = go []
where
go res [] = res
go res lst = let (w, r) = splitAt n lst
(h: t) = f w
in go (h : res) (t ++ r)
-- runs reversed window and reverses the result
runLeftR n f = runRightR n (reverse . f . reverse)
-- rewriting rules from [C. Ahlbach et. all]
r1 = \case [0,3,0] -> [1,1,1]
[0,2,0] -> [1,0,1]
[0,1,2] -> [1,0,1]
[0,2,1] -> [1,1,0]
[x,0,2] -> [x,1,0]
[x,0,3] -> [x,1,1]
[0,1,2,0] -> [1,0,1,0]
[0,2,0,x] -> [1,0,0,x+1]
[0,3,0,x] -> [1,1,0,x+1]
[0,2,1,x] -> [1,1,0,x ]
[0,1,2,x] -> [1,0,1,x ]
l -> l
r2 = \case [0,1,1] -> [1,0,0]
l -> l
r3 = \case [1,-1] -> [0,1]
[2,-1] -> [1,1]
[1, 0, 0] -> [0,1,1]
[1,-1, 0] -> [0,0,1]
[1,-1, 1] -> [0,0,2]
[1, 0,-1] -> [0,1,0]
[2, 0, 0] -> [1,1,1]
[2,-1, 0] -> [1,0,1]
[2,-1, 1] -> [1,0,2]
[2, 0,-1] -> [1,1,0]
l -> l
alignWith :: (Int -> Int -> a) -> [Int] -> [Int] -> [a]
alignWith f a b = go [] a b
where
go res as [] = ((`f` 0) <$> reverse as) ++ res
go res [] bs = ((0 `f`) <$> reverse bs) ++ res
go res (a:as) (b:bs) = go (f a b : res) as bs |
http://rosettacode.org/wiki/Zumkeller_numbers | Zumkeller numbers | Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the divisors are partitioned, only that the two partition sums are equal.
E.G.
6 is a Zumkeller number; The divisors {1 2 3 6} can be partitioned into two groups {1 2 3} and {6} that both sum to 6.
10 is not a Zumkeller number; The divisors {1 2 5 10} can not be partitioned into two groups in any way that will both sum to the same value.
12 is a Zumkeller number; The divisors {1 2 3 4 6 12} can be partitioned into two groups {1 3 4 6} and {2 12} that both sum to 14.
Even Zumkeller numbers are common; odd Zumkeller numbers are much less so. For values below 10^6, there is at least one Zumkeller number in every 12 consecutive integers, and the vast majority of them are even. The odd Zumkeller numbers are very similar to the list from the task Abundant odd numbers; they are nearly the same except for the further restriction that the abundance (A(n) = sigma(n) - 2n), must be even: A(n) mod 2 == 0
Task
Write a routine (function, procedure, whatever) to find Zumkeller numbers.
Use the routine to find and display here, on this page, the first 220 Zumkeller numbers.
Use the routine to find and display here, on this page, the first 40 odd Zumkeller numbers.
Optional, stretch goal: Use the routine to find and display here, on this page, the first 40 odd Zumkeller numbers that don't end with 5.
See Also
OEIS:A083207 - Zumkeller numbers to get an impression of different partitions OEIS:A083206 Zumkeller partitions
OEIS:A174865 - Odd Zumkeller numbers
Related Tasks
Abundant odd numbers
Abundant, deficient and perfect number classifications
Proper divisors , Factors of an integer | #Haskell | Haskell | import Data.List (group, sort)
import Data.List.Split (chunksOf)
import Data.Numbers.Primes (primeFactors)
-------------------- ZUMKELLER NUMBERS -------------------
isZumkeller :: Int -> Bool
isZumkeller n =
let ds = divisors n
m = sum ds
in ( even m
&& let half = div m 2
in elem half ds
|| ( all (half >=) ds
&& summable half ds
)
)
summable :: Int -> [Int] -> Bool
summable _ [] = False
summable x xs@(h : t) =
elem x xs
|| summable (x - h) t
|| summable x t
divisors :: Int -> [Int]
divisors x =
sort
( foldr
( flip ((<*>) . fmap (*))
. scanl (*) 1
)
[1]
(group (primeFactors x))
)
--------------------------- TEST -------------------------
main :: IO ()
main =
mapM_
( \(s, n, xs) ->
putStrLn $
s
<> ( '\n' :
tabulated
10
(take n (filter isZumkeller xs))
)
)
[ ("First 220 Zumkeller numbers:", 220, [1 ..]),
("First 40 odd Zumkeller numbers:", 40, [1, 3 ..])
]
------------------------- DISPLAY ------------------------
tabulated ::
Show a =>
Int ->
[a] ->
String
tabulated nCols = go
where
go xs =
let ts = show <$> xs
w = succ (maximum (length <$> ts))
in unlines
( concat
<$> chunksOf
nCols
(justifyRight w ' ' <$> ts)
)
justifyRight :: Int -> Char -> String -> String
justifyRight n c = (drop . length) <*> (replicate n c <>) |
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included) | Arbitrary-precision integers (included) | Using the in-built capabilities of your language, calculate the integer value of:
5
4
3
2
{\displaystyle 5^{4^{3^{2}}}}
Confirm that the first and last twenty digits of the answer are:
62060698786608744707...92256259918212890625
Find and show the number of decimal digits in the answer.
Note: Do not submit an implementation of arbitrary precision arithmetic. The intention is to show the capabilities of the language as supplied. If a language has a single, overwhelming, library of varied modules that is endorsed by its home site – such as CPAN for Perl or Boost for C++ – then that may be used instead.
Strictly speaking, this should not be solved by fixed-precision numeric libraries where the precision has to be manually set to a large value; although if this is the only recourse then it may be used with a note explaining that the precision must be set manually to a large enough value.
Related tasks
Long multiplication
Exponentiation order
exponentiation operator
Exponentiation with infix operators in (or operating on) the base
| #Clojure | Clojure | (defn exp [n k] (reduce * (repeat k n)))
(def big (->> 2 (exp 3) (exp 4) (exp 5)))
(def sbig (str big))
(assert (= "62060698786608744707" (.substring sbig 0 20)))
(assert (= "92256259918212890625" (.substring sbig (- (count sbig) 20))))
(println (count sbig) "digits")
(println (str (.substring sbig 0 20) ".."
(.substring sbig (- (count sbig) 20)))
(str "(" (count sbig) " digits)")) |
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included) | Arbitrary-precision integers (included) | Using the in-built capabilities of your language, calculate the integer value of:
5
4
3
2
{\displaystyle 5^{4^{3^{2}}}}
Confirm that the first and last twenty digits of the answer are:
62060698786608744707...92256259918212890625
Find and show the number of decimal digits in the answer.
Note: Do not submit an implementation of arbitrary precision arithmetic. The intention is to show the capabilities of the language as supplied. If a language has a single, overwhelming, library of varied modules that is endorsed by its home site – such as CPAN for Perl or Boost for C++ – then that may be used instead.
Strictly speaking, this should not be solved by fixed-precision numeric libraries where the precision has to be manually set to a large value; although if this is the only recourse then it may be used with a note explaining that the precision must be set manually to a large enough value.
Related tasks
Long multiplication
Exponentiation order
exponentiation operator
Exponentiation with infix operators in (or operating on) the base
| #CLU | CLU | start_up = proc ()
% Get bigint versions of 5, 4, 3 and 2
five: bigint := bigint$i2bi(5)
four: bigint := bigint$i2bi(4)
three: bigint := bigint$i2bi(3)
two: bigint := bigint$i2bi(2)
% Calculate 5**4**3**2
huge_no: bigint := five ** four ** three ** two
% Turn answer into string
huge_str: string := bigint$unparse(huge_no)
% Scan for first digit (the string will have some leading whitespace)
i: int := 1
while huge_str[i] = ' ' do i := i + 1 end
po: stream := stream$primary_output()
stream$putl(po, "First 20 digits: "
|| string$substr(huge_str, i, 20))
stream$putl(po, "Last 20 digits: "
|| string$substr(huge_str, string$size(huge_str)-19, 20))
stream$putl(po, "Amount of digits: "
|| int$unparse(string$size(huge_str) - i + 1))
end start_up |
http://rosettacode.org/wiki/Zhang-Suen_thinning_algorithm | Zhang-Suen thinning algorithm | This is an algorithm used to thin a black and white i.e. one bit per pixel images.
For example, with an input image of:
################# #############
################## ################
################### ##################
######## ####### ###################
###### ####### ####### ######
###### ####### #######
################# #######
################ #######
################# #######
###### ####### #######
###### ####### #######
###### ####### ####### ######
######## ####### ###################
######## ####### ###### ################## ######
######## ####### ###### ################ ######
######## ####### ###### ############# ######
It produces the thinned output:
# ########## #######
## # #### #
# # ##
# # #
# # #
# # #
############ #
# # #
# # #
# # #
# # #
# ##
# ############
### ###
Algorithm
Assume black pixels are one and white pixels zero, and that the input image is a rectangular N by M array of ones and zeroes.
The algorithm operates on all black pixels P1 that can have eight neighbours.
The neighbours are, in order, arranged as:
P9 P2 P3
P8 P1 P4
P7 P6 P5
Obviously the boundary pixels of the image cannot have the full eight neighbours.
Define
A
(
P
1
)
{\displaystyle A(P1)}
= the number of transitions from white to black, (0 -> 1) in the sequence P2,P3,P4,P5,P6,P7,P8,P9,P2. (Note the extra P2 at the end - it is circular).
Define
B
(
P
1
)
{\displaystyle B(P1)}
= The number of black pixel neighbours of P1. ( = sum(P2 .. P9) )
Step 1
All pixels are tested and pixels satisfying all the following conditions (simultaneously) are just noted at this stage.
(0) The pixel is black and has eight neighbours
(1)
2
<=
B
(
P
1
)
<=
6
{\displaystyle 2<=B(P1)<=6}
(2) A(P1) = 1
(3) At least one of P2 and P4 and P6 is white
(4) At least one of P4 and P6 and P8 is white
After iterating over the image and collecting all the pixels satisfying all step 1 conditions, all these condition satisfying pixels are set to white.
Step 2
All pixels are again tested and pixels satisfying all the following conditions are just noted at this stage.
(0) The pixel is black and has eight neighbours
(1)
2
<=
B
(
P
1
)
<=
6
{\displaystyle 2<=B(P1)<=6}
(2) A(P1) = 1
(3) At least one of P2 and P4 and P8 is white
(4) At least one of P2 and P6 and P8 is white
After iterating over the image and collecting all the pixels satisfying all step 2 conditions, all these condition satisfying pixels are again set to white.
Iteration
If any pixels were set in this round of either step 1 or step 2 then all steps are repeated until no image pixels are so changed.
Task
Write a routine to perform Zhang-Suen thinning on an image matrix of ones and zeroes.
Use the routine to thin the following image and show the output here on this page as either a matrix of ones and zeroes, an image, or an ASCII-art image of space/non-space characters.
00000000000000000000000000000000
01111111110000000111111110000000
01110001111000001111001111000000
01110000111000001110000111000000
01110001111000001110000000000000
01111111110000001110000000000000
01110111100000001110000111000000
01110011110011101111001111011100
01110001111011100111111110011100
00000000000000000000000000000000
Reference
Zhang-Suen Thinning Algorithm, Java Implementation by Nayef Reza.
"Character Recognition Systems: A Guide for Students and Practitioners" By Mohamed Cheriet, Nawwaf Kharma, Cheng-Lin Liu, Ching Suen
| #Java | Java | import java.awt.Point;
import java.util.*;
public class ZhangSuen {
final static String[] image = {
" ",
" ################# ############# ",
" ################## ################ ",
" ################### ################## ",
" ######## ####### ################### ",
" ###### ####### ####### ###### ",
" ###### ####### ####### ",
" ################# ####### ",
" ################ ####### ",
" ################# ####### ",
" ###### ####### ####### ",
" ###### ####### ####### ",
" ###### ####### ####### ###### ",
" ######## ####### ################### ",
" ######## ####### ###### ################## ###### ",
" ######## ####### ###### ################ ###### ",
" ######## ####### ###### ############# ###### ",
" "};
final static int[][] nbrs = {{0, -1}, {1, -1}, {1, 0}, {1, 1}, {0, 1},
{-1, 1}, {-1, 0}, {-1, -1}, {0, -1}};
final static int[][][] nbrGroups = {{{0, 2, 4}, {2, 4, 6}}, {{0, 2, 6},
{0, 4, 6}}};
static List<Point> toWhite = new ArrayList<>();
static char[][] grid;
public static void main(String[] args) {
grid = new char[image.length][];
for (int r = 0; r < image.length; r++)
grid[r] = image[r].toCharArray();
thinImage();
}
static void thinImage() {
boolean firstStep = false;
boolean hasChanged;
do {
hasChanged = false;
firstStep = !firstStep;
for (int r = 1; r < grid.length - 1; r++) {
for (int c = 1; c < grid[0].length - 1; c++) {
if (grid[r][c] != '#')
continue;
int nn = numNeighbors(r, c);
if (nn < 2 || nn > 6)
continue;
if (numTransitions(r, c) != 1)
continue;
if (!atLeastOneIsWhite(r, c, firstStep ? 0 : 1))
continue;
toWhite.add(new Point(c, r));
hasChanged = true;
}
}
for (Point p : toWhite)
grid[p.y][p.x] = ' ';
toWhite.clear();
} while (firstStep || hasChanged);
printResult();
}
static int numNeighbors(int r, int c) {
int count = 0;
for (int i = 0; i < nbrs.length - 1; i++)
if (grid[r + nbrs[i][1]][c + nbrs[i][0]] == '#')
count++;
return count;
}
static int numTransitions(int r, int c) {
int count = 0;
for (int i = 0; i < nbrs.length - 1; i++)
if (grid[r + nbrs[i][1]][c + nbrs[i][0]] == ' ') {
if (grid[r + nbrs[i + 1][1]][c + nbrs[i + 1][0]] == '#')
count++;
}
return count;
}
static boolean atLeastOneIsWhite(int r, int c, int step) {
int count = 0;
int[][] group = nbrGroups[step];
for (int i = 0; i < 2; i++)
for (int j = 0; j < group[i].length; j++) {
int[] nbr = nbrs[group[i][j]];
if (grid[r + nbr[1]][c + nbr[0]] == ' ') {
count++;
break;
}
}
return count > 1;
}
static void printResult() {
for (char[] row : grid)
System.out.println(row);
}
} |
http://rosettacode.org/wiki/Zeckendorf_number_representation | Zeckendorf number representation | Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series.
Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13.
The decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100.
10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that no two consecutive Fibonacci numbers can be used which leads to the former unique solution.
Task
Generate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order.
The intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task.
Also see
OEIS A014417 for the the sequence of required results.
Brown's Criterion - Numberphile
Related task
Fibonacci sequence
| #D | D | import std.stdio, std.range, std.algorithm, std.functional;
void main() {
size_t
.max
.iota
.filter!q{ !(a & (a >> 1)) }
.take(21)
.binaryReverseArgs!writefln("%(%b\n%)");
} |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Bracmat | Bracmat | ( 100doors-tbl
= door step
. tbl$(doors.101) { Create an array. Indexing is 0-based. Add one extra for addressing element nr. 100 }
& 0:?step
& whl
' ( 1+!step:~>100:?step { ~> means 'not greater than', i.e. 'less than or equal' }
& 0:?door
& whl
' ( !step+!door:~>100:?door
& 1+-1*!(!door$doors):?doors { <number>$<variable> sets the current index, which stays the same until explicitly changed. }
)
)
& 0:?door
& whl
' ( 1+!door:~>100:?door
& out
$ ( door
!door
is
( !(!door$doors):1&open
| closed
)
)
)
& tbl$(doors.0) { clean up the array }
) |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #EGL | EGL |
array int[10]; //optionally, add a braced list of values. E.g. array int[10]{1, 2, 3};
array[1] = 42;
SysLib.writeStdout(array[1]);
|
http://rosettacode.org/wiki/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part", where the imaginary part is the number to be multiplied by
i
{\displaystyle i}
.
Task
Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.)
Print the results for each operation tested.
Optional: Show complex conjugation.
By definition, the complex conjugate of
a
+
b
i
{\displaystyle a+bi}
is
a
−
b
i
{\displaystyle a-bi}
Some languages have complex number libraries available. If your language does, show the operations. If your language does not, also show the definition of this type.
| #OxygenBasic | OxygenBasic |
'COMPLEX OPERATIONS
'=================
type tcomplex double x,y
class Complex
'============
has tcomplex
static sys i,pp
static tcomplex accum[32]
def operands
tcomplex*a,*b
@a=@accum+i
if pp then
@b=@a+sizeof accum
pp=0
else
@b=@this
end if
end def
method "load"()
operands
a.x=b.x
a.y=b.y
end method
method "push"()
i+=sizeof accum
end method
method "pop"()
pp=1
i-=sizeof accum
end method
method "="()
operands
b.x=a.x
b.y=a.y
end method
method "+"()
operands
a.x+=b.x
a.y+=b.y
end method
method "-"()
operands
a.x-=b.x
a.y-=b.y
end method
method "*"()
operands
double d
d=a.x
a.x = a.x * b.x - a.y * b.y
a.y = a.y * b.x + d * b.y
end method
method "/"()
operands
double d,v
v=1/(b.x * b.x + b.y * b.y)
d=a.x
a.x = (a.x * b.x + a.y * b.y) * v
a.y = (a.y * b.x - d * b.y) * v
end method
method power(double n)
operands
'Using DeMoivre theorem
double r,an,mg
r = hypot(b.x,b.y)
mg = r^n
if b.x=0 then
ay=.5*pi
if b.y<0 then ay=-ay
else
an = atan(b.y,b.x)
end if
an *= n
a.x = mg * cos(an)
a.y = mg * sin(an)
end method
method show() as string
return str(x,14) ", " str(y,14)
end method
end class
'#recordof complexop
'====
'TEST
'====
complex z1,z2,z3,z4,z5
'ENTER VALUES
z1 <= 0, 0
z2 <= 2, 1
z3 <= -2, 1
z4 <= 2, 4
z5 <= 1, 1
'EVALUATE COMPLEX EXPRESSIONS
z1 = z2 * z3
print "Z1 = "+z1.show 'RESULT -5.0, 0
z1 = z3+(z2.power(2))
print "Z1 = "+z1.show 'RESULT 1.0, 5.0
z1 = z5/z4
print "Z1 = "+z1.show 'RESULT 0.3, 0.1
z1 = z5/z1
print "Z1 = "+z1.show 'RESULT 2.0, 4.0
z1 = z2/z4
print "Z1 = "+z1.show 'RESULT -0.4, -0.3
z1 = z1*z4
print "Z1 = "+z1.show 'RESULT 2.0, 1.0
|
http://rosettacode.org/wiki/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part", where the imaginary part is the number to be multiplied by
i
{\displaystyle i}
.
Task
Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.)
Print the results for each operation tested.
Optional: Show complex conjugation.
By definition, the complex conjugate of
a
+
b
i
{\displaystyle a+bi}
is
a
−
b
i
{\displaystyle a-bi}
Some languages have complex number libraries available. If your language does, show the operations. If your language does not, also show the definition of this type.
| #PARI.2FGP | PARI/GP | add(a,b)=a+b;
mult(a,b)=a*b;
neg(a)=-a;
inv(a)=1/a; |
http://rosettacode.org/wiki/Arithmetic/Rational | Arithmetic/Rational | Task
Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language.
Example
Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number).
Further define the appropriate rational unary operators abs and '-', with the binary operators for addition '+', subtraction '-', multiplication '×', division '/', integer division '÷', modulo division, the comparison operators (e.g. '<', '≤', '>', & '≥') and equality operators (e.g. '=' & '≠').
Define standard coercion operators for casting int to frac etc.
If space allows, define standard increment and decrement operators (e.g. '+:=' & '-:=' etc.).
Finally test the operators:
Use the new type frac to find all perfect numbers less than 219 by summing the reciprocal of the factors.
Related task
Perfect Numbers
| #Python | Python | from fractions import Fraction
for candidate in range(2, 2**19):
sum = Fraction(1, candidate)
for factor in range(2, int(candidate**0.5)+1):
if candidate % factor == 0:
sum += Fraction(1, factor) + Fraction(1, candidate // factor)
if sum.denominator == 1:
print("Sum of recipr. factors of %d = %d exactly %s" %
(candidate, int(sum), "perfect!" if sum == 1 else "")) |
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geometric mean of two numbers.
The arithmetic-geometric mean of two numbers can be (usefully) denoted as
a
g
m
(
a
,
g
)
{\displaystyle \mathrm {agm} (a,g)}
, and is equal to the limit of the sequence:
a
0
=
a
;
g
0
=
g
{\displaystyle a_{0}=a;\qquad g_{0}=g}
a
n
+
1
=
1
2
(
a
n
+
g
n
)
;
g
n
+
1
=
a
n
g
n
.
{\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.}
Since the limit of
a
n
−
g
n
{\displaystyle a_{n}-g_{n}}
tends (rapidly) to zero with iterations, this is an efficient method.
Demonstrate the function by calculating:
a
g
m
(
1
,
1
/
2
)
{\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})}
Also see
mathworld.wolfram.com/Arithmetic-Geometric Mean
| #Sidef | Sidef | func agm(a, g) {
loop {
var (a1, g1) = ((a+g)/2, sqrt(a*g))
[a1,g1] == [a,g] && return a
(a, g) = (a1, g1)
}
}
say agm(1, 1/sqrt(2)) |
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geometric mean of two numbers.
The arithmetic-geometric mean of two numbers can be (usefully) denoted as
a
g
m
(
a
,
g
)
{\displaystyle \mathrm {agm} (a,g)}
, and is equal to the limit of the sequence:
a
0
=
a
;
g
0
=
g
{\displaystyle a_{0}=a;\qquad g_{0}=g}
a
n
+
1
=
1
2
(
a
n
+
g
n
)
;
g
n
+
1
=
a
n
g
n
.
{\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.}
Since the limit of
a
n
−
g
n
{\displaystyle a_{n}-g_{n}}
tends (rapidly) to zero with iterations, this is an efficient method.
Demonstrate the function by calculating:
a
g
m
(
1
,
1
/
2
)
{\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})}
Also see
mathworld.wolfram.com/Arithmetic-Geometric Mean
| #Sinclair_ZX81_BASIC | Sinclair ZX81 BASIC | 10 LET A=1
20 LET G=1/SQR 2
30 GOSUB 100
40 PRINT AGM
50 STOP
100 LET A0=A
110 LET A=(A+G)/2
120 LET G=SQR (A0*G)
130 IF ABS(A-G)>.00000001 THEN GOTO 100
140 LET AGM=A
150 RETURN |
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, you may also try something like:
x = 0
y = 0
z = x**y
say 'z=' z
Show the result here.
And of course use any symbols or notation that is supported in your computer programming language for exponentiation.
See also
The Wiki entry: Zero to the power of zero.
The Wiki entry: History of differing points of view.
The MathWorld™ entry: exponent laws.
Also, in the above MathWorld™ entry, see formula (9):
x
0
=
1
{\displaystyle x^{0}=1}
.
The OEIS entry: The special case of zero to the zeroth power
| #Fortran | Fortran |
program zero
double precision :: i, j
double complex :: z1, z2
i = 0.0D0
j = 0.0D0
z1 = (0.0D0,0.0D0)
z2 = (0.0D0,0.0D0)
write(*,*) 'When integers are used, we have 0^0 = ', 0**0
write(*,*) 'When double precision numbers are used, we have 0.0^0.0 = ', i**j
write(*,*) 'When complex numbers are used, we have (0.0+0.0i)^(0.0+0.0i) = ', z1**z2
end program
|
http://rosettacode.org/wiki/Zero_to_the_zero_power | Zero to the zero power | Some computer programming languages are not exactly consistent (with other computer programming languages)
when raising zero to the zeroth power: 00
Task
Show the results of raising zero to the zeroth power.
If your computer language objects to 0**0 or 0^0 at compile time, you may also try something like:
x = 0
y = 0
z = x**y
say 'z=' z
Show the result here.
And of course use any symbols or notation that is supported in your computer programming language for exponentiation.
See also
The Wiki entry: Zero to the power of zero.
The Wiki entry: History of differing points of view.
The MathWorld™ entry: exponent laws.
Also, in the above MathWorld™ entry, see formula (9):
x
0
=
1
{\displaystyle x^{0}=1}
.
The OEIS entry: The special case of zero to the zeroth power
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Print "0 ^ 0 ="; 0 ^ 0
Sleep |
http://rosettacode.org/wiki/Zig-zag_matrix | Zig-zag matrix | Task
Produce a zig-zag array.
A zig-zag array is a square arrangement of the first N2 natural numbers, where the
numbers increase sequentially as you zig-zag along the array's anti-diagonals.
For a graphical representation, see JPG zigzag (JPG uses such arrays to encode images).
For example, given 5, produce this array:
0 1 5 6 14
2 4 7 13 15
3 8 12 16 21
9 11 17 20 22
10 18 19 23 24
Related tasks
Spiral matrix
Identity matrix
Ulam spiral (for primes)
See also
Wiktionary entry: anti-diagonals
| #ActionScript | ActionScript |
package
{
public class ZigZagMatrix extends Array
{
private var height:uint;
private var width:uint;
public var mtx:Array = [];
public function ZigZagMatrix(size:uint)
{
this.height = size;
this.width = size;
this.mtx = [];
for (var i:uint = 0; i < size; i++) {
this.mtx[i] = [];
}
i = 1;
var j:uint = 1;
for (var e:uint = 0; e < size*size; e++) {
this.mtx[i-1][j-1] = e;
if ((i + j) % 2 == 0) {
// Even stripes
if (j < size) j ++;
else i += 2;
if (i > 1) i --;
} else {
// Odd stripes
if (i < size) i ++;
else j += 2;
if (j > 1) j --;
}
}
}
}
}
|
http://rosettacode.org/wiki/Yellowstone_sequence | Yellowstone sequence | The Yellowstone sequence, also called the Yellowstone permutation, is defined as:
For n <= 3,
a(n) = n
For n >= 4,
a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and
is not relatively prime to a(n-2).
The sequence is a permutation of the natural numbers, and gets its name from what its authors felt was a spiking, geyser like appearance of a plot of the sequence.
Example
a(4) is 4 because 4 is the smallest number following 1, 2, 3 in the sequence that is relatively prime to the entry before it (3), and is not relatively prime to the number two entries before it (2).
Task
Find and show as output the first 30 Yellowstone numbers.
Extra
Demonstrate how to plot, with x = n and y coordinate a(n), the first 100 Yellowstone numbers.
Related tasks
Greatest common divisor.
Plot coordinate pairs.
See also
The OEIS entry: A098550 The Yellowstone permutation.
Applegate et al, 2015: The Yellowstone Permutation [1].
| #ALGOL_68 | ALGOL 68 | BEGIN # find members of the yellowstone sequence: starting from 1, 2, 3 the #
# subsequent members are the lowest number coprime to the previous one #
# and not coprime to the one before that, that haven't appeared in the #
# sequence yet #
# iterative Greatest Common Divisor routine, returns the gcd of m and n #
PROC gcd = ( INT m, n )INT:
BEGIN
INT a := ABS m, b := ABS n;
WHILE b /= 0 DO
INT new a = b;
b := a MOD b;
a := new a
OD;
a
END # gcd # ;
# returns an array of the Yellowstone seuence up to n #
OP YELLOWSTONE = ( INT n )[]INT:
BEGIN
[ 1 : n ]INT result;
IF n > 0 THEN
result[ 1 ] := 1;
IF n > 1 THEN
result[ 2 ] := 2;
IF n > 2 THEN
result[ 3 ] := 3;
# guess the maximum element will be n, if it is larger, used will be enlarged #
REF[]BOOL used := HEAP[ 1 : n ]BOOL;
used[ 1 ] := used[ 2 ] := used[ 3 ] := TRUE;
FOR i FROM 4 TO UPB used DO used[ i ] := FALSE OD;
FOR i FROM 4 TO UPB result DO
INT p1 = result[ i - 1 ];
INT p2 = result[ i - 2 ];
BOOL found := FALSE;
FOR j WHILE NOT found DO
IF j > UPB used THEN
# not enough elements in used - enlarge it #
REF[]BOOL new used := HEAP[ 1 : 2 * UPB used ]BOOL;
new used[ 1 : UPB used ] := used;
FOR k FROM UPB used + 1 TO UPB new used DO new used[ k ] := FALSE OD;
used := new used
FI;
IF NOT used[ j ] THEN
IF found := gcd( j, p1 ) = 1 AND gcd( j, p2 ) /= 1
THEN
result[ i ] := j;
used[ j ] := TRUE
FI
FI
OD
OD
FI
FI
FI;
result
END # YELLOWSTONE # ;
[]INT ys = YELLOWSTONE 30;
FOR i TO UPB ys DO
print( ( " ", whole( ys[ i ], 0 ) ) )
OD
END |
http://rosettacode.org/wiki/Arithmetic_evaluation | Arithmetic evaluation | Create a program which parses and evaluates arithmetic expressions.
Requirements
An abstract-syntax tree (AST) for the expression must be created from parsing the input.
The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.)
The expression will be a string or list of symbols like "(1+3)*7".
The four symbols + - * / must be supported as binary operators with conventional precedence rules.
Precedence-control parentheses must also be supported.
Note
For those who don't remember, mathematical precedence is as follows:
Parentheses
Multiplication/Division (left to right)
Addition/Subtraction (left to right)
C.f
24 game Player.
Parsing/RPN calculator algorithm.
Parsing/RPN to infix conversion.
| #Python | Python | import operator
class AstNode(object):
def __init__( self, opr, left, right ):
self.opr = opr
self.l = left
self.r = right
def eval(self):
return self.opr(self.l.eval(), self.r.eval())
class LeafNode(object):
def __init__( self, valStrg ):
self.v = int(valStrg)
def eval(self):
return self.v
class Yaccer(object):
def __init__(self):
self.operstak = []
self.nodestak =[]
self.__dict__.update(self.state1)
def v1( self, valStrg ):
# Value String
self.nodestak.append( LeafNode(valStrg))
self.__dict__.update(self.state2)
#print 'push', valStrg
def o2( self, operchar ):
# Operator character or open paren in state1
def openParen(a,b):
return 0 # function should not be called
opDict= { '+': ( operator.add, 2, 2 ),
'-': (operator.sub, 2, 2 ),
'*': (operator.mul, 3, 3 ),
'/': (operator.div, 3, 3 ),
'^': ( pow, 4, 5 ), # right associative exponentiation for grins
'(': ( openParen, 0, 8 )
}
operPrecidence = opDict[operchar][2]
self.redeuce(operPrecidence)
self.operstak.append(opDict[operchar])
self.__dict__.update(self.state1)
# print 'pushop', operchar
def syntaxErr(self, char ):
# Open Parenthesis
print 'parse error - near operator "%s"' %char
def pc2( self,operchar ):
# Close Parenthesis
# reduce node until matching open paren found
self.redeuce( 1 )
if len(self.operstak)>0:
self.operstak.pop() # pop off open parenthesis
else:
print 'Error - no open parenthesis matches close parens.'
self.__dict__.update(self.state2)
def end(self):
self.redeuce(0)
return self.nodestak.pop()
def redeuce(self, precidence):
while len(self.operstak)>0:
tailOper = self.operstak[-1]
if tailOper[1] < precidence: break
tailOper = self.operstak.pop()
vrgt = self.nodestak.pop()
vlft= self.nodestak.pop()
self.nodestak.append( AstNode(tailOper[0], vlft, vrgt))
# print 'reduce'
state1 = { 'v': v1, 'o':syntaxErr, 'po':o2, 'pc':syntaxErr }
state2 = { 'v': syntaxErr, 'o':o2, 'po':syntaxErr, 'pc':pc2 }
def Lex( exprssn, p ):
bgn = None
cp = -1
for c in exprssn:
cp += 1
if c in '+-/*^()': # throw in exponentiation (^)for grins
if bgn is not None:
p.v(p, exprssn[bgn:cp])
bgn = None
if c=='(': p.po(p, c)
elif c==')':p.pc(p, c)
else: p.o(p, c)
elif c in ' \t':
if bgn is not None:
p.v(p, exprssn[bgn:cp])
bgn = None
elif c in '0123456789':
if bgn is None:
bgn = cp
else:
print 'Invalid character in expression'
if bgn is not None:
p.v(p, exprssn[bgn:cp])
bgn = None
if bgn is not None:
p.v(p, exprssn[bgn:cp+1])
bgn = None
return p.end()
expr = raw_input("Expression:")
astTree = Lex( expr, Yaccer())
print expr, '=',astTree.eval() |
http://rosettacode.org/wiki/Zeckendorf_arithmetic | Zeckendorf arithmetic | This task is a total immersion zeckendorf task; using decimal numbers will attract serious disapprobation.
The task is to implement addition, subtraction, multiplication, and division using Zeckendorf number representation. Optionally provide decrement, increment and comparitive operation functions.
Addition
Like binary 1 + 1 = 10, note carry 1 left. There the similarity ends. 10 + 10 = 101, note carry 1 left and 1 right. 100 + 100 = 1001, note carry 1 left and 2 right, this is the general case.
Occurrences of 11 must be changed to 100. Occurrences of 111 may be changed from the right by replacing 11 with 100, or from the left converting 111 to 100 + 100;
Subtraction
10 - 1 = 1. The general rule is borrow 1 right carry 1 left. eg:
abcde
10100 -
1000
_____
100 borrow 1 from a leaves 100
+ 100 add the carry
_____
1001
A larger example:
abcdef
100100 -
1000
______
1*0100 borrow 1 from b
+ 100 add the carry
______
1*1001
Sadly we borrowed 1 from b which didn't have it to lend. So now b borrows from a:
1001
+ 1000 add the carry
____
10100
Multiplication
Here you teach your computer its zeckendorf tables. eg. 101 * 1001:
a = 1 * 101 = 101
b = 10 * 101 = a + a = 10000
c = 100 * 101 = b + a = 10101
d = 1000 * 101 = c + b = 101010
1001 = d + a therefore 101 * 1001 =
101010
+ 101
______
1000100
Division
Lets try 1000101 divided by 101, so we can use the same table used for multiplication.
1000101 -
101010 subtract d (1000 * 101)
_______
1000 -
101 b and c are too large to subtract, so subtract a
____
1 so 1000101 divided by 101 is d + a (1001) remainder 1
Efficient algorithms for Zeckendorf arithmetic is interesting. The sections on addition and subtraction are particularly relevant for this task.
| #Java | Java | import java.util.List;
public class Zeckendorf implements Comparable<Zeckendorf> {
private static List<String> dig = List.of("00", "01", "10");
private static List<String> dig1 = List.of("", "1", "10");
private String x;
private int dVal = 0;
private int dLen = 0;
public Zeckendorf() {
this("0");
}
public Zeckendorf(String x) {
this.x = x;
int q = 1;
int i = x.length() - 1;
dLen = i / 2;
while (i >= 0) {
dVal += (x.charAt(i) - '0') * q;
q *= 2;
i--;
}
}
private void a(int n) {
int i = n;
while (true) {
if (dLen < i) dLen = i;
int j = (dVal >> (i * 2)) & 3;
switch (j) {
case 0:
case 1:
return;
case 2:
if (((dVal >> ((i + 1) * 2)) & 1) != 1) return;
dVal += 1 << (i * 2 + 1);
return;
case 3:
int temp = 3 << (i * 2);
temp ^= -1;
dVal = dVal & temp;
b((i + 1) * 2);
break;
}
i++;
}
}
private void b(int pos) {
if (pos == 0) {
Zeckendorf thiz = this;
thiz.inc();
return;
}
if (((dVal >> pos) & 1) == 0) {
dVal += 1 << pos;
a(pos / 2);
if (pos > 1) a(pos / 2 - 1);
} else {
int temp = 1 << pos;
temp ^= -1;
dVal = dVal & temp;
b(pos + 1);
b(pos - (pos > 1 ? 2 : 1));
}
}
private void c(int pos) {
if (((dVal >> pos) & 1) == 1) {
int temp = 1 << pos;
temp ^= -1;
dVal = dVal & temp;
return;
}
c(pos + 1);
if (pos > 0) {
b(pos - 1);
} else {
Zeckendorf thiz = this;
thiz.inc();
}
}
public Zeckendorf inc() {
dVal++;
a(0);
return this;
}
public void plusAssign(Zeckendorf other) {
for (int gn = 0; gn < (other.dLen + 1) * 2; gn++) {
if (((other.dVal >> gn) & 1) == 1) {
b(gn);
}
}
}
public void minusAssign(Zeckendorf other) {
for (int gn = 0; gn < (other.dLen + 1) * 2; gn++) {
if (((other.dVal >> gn) & 1) == 1) {
c(gn);
}
}
while ((((dVal >> dLen * 2) & 3) == 0) || (dLen == 0)) {
dLen--;
}
}
public void timesAssign(Zeckendorf other) {
Zeckendorf na = other.copy();
Zeckendorf nb = other.copy();
Zeckendorf nt;
Zeckendorf nr = new Zeckendorf();
for (int i = 0; i < (dLen + 1) * 2; i++) {
if (((dVal >> i) & 1) > 0) {
nr.plusAssign(nb);
}
nt = nb.copy();
nb.plusAssign(na);
na = nt.copy();
}
dVal = nr.dVal;
dLen = nr.dLen;
}
private Zeckendorf copy() {
Zeckendorf z = new Zeckendorf();
z.dVal = dVal;
z.dLen = dLen;
return z;
}
@Override
public int compareTo(Zeckendorf other) {
return ((Integer) dVal).compareTo(other.dVal);
}
@Override
public String toString() {
if (dVal == 0) {
return "0";
}
int idx = (dVal >> (dLen * 2)) & 3;
StringBuilder stringBuilder = new StringBuilder(dig1.get(idx));
for (int i = dLen - 1; i >= 0; i--) {
idx = (dVal >> (i * 2)) & 3;
stringBuilder.append(dig.get(idx));
}
return stringBuilder.toString();
}
public static void main(String[] args) {
System.out.println("Addition:");
Zeckendorf g = new Zeckendorf("10");
g.plusAssign(new Zeckendorf("10"));
System.out.println(g);
g.plusAssign(new Zeckendorf("10"));
System.out.println(g);
g.plusAssign(new Zeckendorf("1001"));
System.out.println(g);
g.plusAssign(new Zeckendorf("1000"));
System.out.println(g);
g.plusAssign(new Zeckendorf("10101"));
System.out.println(g);
System.out.println("\nSubtraction:");
g = new Zeckendorf("1000");
g.minusAssign(new Zeckendorf("101"));
System.out.println(g);
g = new Zeckendorf("10101010");
g.minusAssign(new Zeckendorf("1010101"));
System.out.println(g);
System.out.println("\nMultiplication:");
g = new Zeckendorf("1001");
g.timesAssign(new Zeckendorf("101"));
System.out.println(g);
g = new Zeckendorf("101010");
g.plusAssign(new Zeckendorf("101"));
System.out.println(g);
}
} |
http://rosettacode.org/wiki/Zumkeller_numbers | Zumkeller numbers | Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the divisors are partitioned, only that the two partition sums are equal.
E.G.
6 is a Zumkeller number; The divisors {1 2 3 6} can be partitioned into two groups {1 2 3} and {6} that both sum to 6.
10 is not a Zumkeller number; The divisors {1 2 5 10} can not be partitioned into two groups in any way that will both sum to the same value.
12 is a Zumkeller number; The divisors {1 2 3 4 6 12} can be partitioned into two groups {1 3 4 6} and {2 12} that both sum to 14.
Even Zumkeller numbers are common; odd Zumkeller numbers are much less so. For values below 10^6, there is at least one Zumkeller number in every 12 consecutive integers, and the vast majority of them are even. The odd Zumkeller numbers are very similar to the list from the task Abundant odd numbers; they are nearly the same except for the further restriction that the abundance (A(n) = sigma(n) - 2n), must be even: A(n) mod 2 == 0
Task
Write a routine (function, procedure, whatever) to find Zumkeller numbers.
Use the routine to find and display here, on this page, the first 220 Zumkeller numbers.
Use the routine to find and display here, on this page, the first 40 odd Zumkeller numbers.
Optional, stretch goal: Use the routine to find and display here, on this page, the first 40 odd Zumkeller numbers that don't end with 5.
See Also
OEIS:A083207 - Zumkeller numbers to get an impression of different partitions OEIS:A083206 Zumkeller partitions
OEIS:A174865 - Odd Zumkeller numbers
Related Tasks
Abundant odd numbers
Abundant, deficient and perfect number classifications
Proper divisors , Factors of an integer | #Java | Java |
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ZumkellerNumbers {
public static void main(String[] args) {
int n = 1;
System.out.printf("First 220 Zumkeller numbers:%n");
for ( int count = 1 ; count <= 220 ; n += 1 ) {
if ( isZumkeller(n) ) {
System.out.printf("%3d ", n);
if ( count % 20 == 0 ) {
System.out.printf("%n");
}
count++;
}
}
n = 1;
System.out.printf("%nFirst 40 odd Zumkeller numbers:%n");
for ( int count = 1 ; count <= 40 ; n += 2 ) {
if ( isZumkeller(n) ) {
System.out.printf("%6d", n);
if ( count % 10 == 0 ) {
System.out.printf("%n");
}
count++;
}
}
n = 1;
System.out.printf("%nFirst 40 odd Zumkeller numbers that do not end in a 5:%n");
for ( int count = 1 ; count <= 40 ; n += 2 ) {
if ( n % 5 != 0 && isZumkeller(n) ) {
System.out.printf("%8d", n);
if ( count % 10 == 0 ) {
System.out.printf("%n");
}
count++;
}
}
}
private static boolean isZumkeller(int n) {
// numbers congruent to 6 or 12 modulo 18 are Zumkeller numbers
if ( n % 18 == 6 || n % 18 == 12 ) {
return true;
}
List<Integer> divisors = getDivisors(n);
int divisorSum = divisors.stream().mapToInt(i -> i.intValue()).sum();
// divisor sum cannot be odd
if ( divisorSum % 2 == 1 ) {
return false;
}
// numbers where n is odd and the abundance is even are Zumkeller numbers
int abundance = divisorSum - 2 * n;
if ( n % 2 == 1 && abundance > 0 && abundance % 2 == 0 ) {
return true;
}
Collections.sort(divisors);
int j = divisors.size() - 1;
int sum = divisorSum/2;
// Largest divisor larger than sum - then cannot partition and not Zumkeller number
if ( divisors.get(j) > sum ) {
return false;
}
return canPartition(j, divisors, sum, new int[2]);
}
private static boolean canPartition(int j, List<Integer> divisors, int sum, int[] buckets) {
if ( j < 0 ) {
return true;
}
for ( int i = 0 ; i < 2 ; i++ ) {
if ( buckets[i] + divisors.get(j) <= sum ) {
buckets[i] += divisors.get(j);
if ( canPartition(j-1, divisors, sum, buckets) ) {
return true;
}
buckets[i] -= divisors.get(j);
}
if( buckets[i] == 0 ) {
break;
}
}
return false;
}
private static final List<Integer> getDivisors(int number) {
List<Integer> divisors = new ArrayList<Integer>();
long sqrt = (long) Math.sqrt(number);
for ( int i = 1 ; i <= sqrt ; i++ ) {
if ( number % i == 0 ) {
divisors.add(i);
int div = number / i;
if ( div != i ) {
divisors.add(div);
}
}
}
return divisors;
}
}
|
Subsets and Splits