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/Eban_numbers | Eban numbers |
Definition
An eban number is a number that has no letter e in it when the number is spelled in English.
Or more literally, spelled numbers that contain the letter e are banned.
The American version of spelling numbers will be used here (as opposed to the British).
2,000,000,000 is two billion, not two milliard.
Only numbers less than one sextillion (1021) will be considered in/for this task.
This will allow optimizations to be used.
Task
show all eban numbers ≤ 1,000 (in a horizontal format), and a count
show all eban numbers between 1,000 and 4,000 (inclusive), and a count
show a count of all eban numbers up and including 10,000
show a count of all eban numbers up and including 100,000
show a count of all eban numbers up and including 1,000,000
show a count of all eban numbers up and including 10,000,000
show all output here.
See also
The MathWorld entry: eban numbers.
The OEIS entry: A6933, eban numbers.
| #AWK | AWK |
# syntax: GAWK -f EBAN_NUMBERS.AWK
# converted from FreeBASIC
BEGIN {
main(2,1000,1)
main(1000,4000,1)
main(2,10000,0)
main(2,100000,0)
main(2,1000000,0)
main(2,10000000,0)
main(2,100000000,0)
exit(0)
}
function main(start,stop,printable, b,count,i,m,r,t) {
printf("%d-%d:",start,stop)
for (i=start; i<=stop; i+=2) {
b = int(i / 1000000000)
r = i % 1000000000
m = int(r / 1000000)
r = i % 1000000
t = int(r / 1000)
r = r % 1000
if (m >= 30 && m <= 66) { m %= 10 }
if (t >= 30 && t <= 66) { t %= 10 }
if (r >= 30 && r <= 66) { r %= 10 }
if (x(b) && x(m) && x(t) && x(r)) {
count++
if (printable) {
printf(" %d",i)
}
}
}
printf(" (count=%d)\n",count)
}
function x(n) {
return(n == 0 || n == 2 || n == 4 || n == 6)
}
|
http://rosettacode.org/wiki/Duffinian_numbers | Duffinian numbers | A Duffinian number is a composite number k that is relatively prime to its sigma sum σ.
The sigma sum of k is the sum of the divisors of k.
E.G.
161 is a Duffinian number.
It is composite. (7 × 23)
The sigma sum 192 (1 + 7 + 23 + 161) is relatively prime to 161.
Duffinian numbers are very common.
It is not uncommon for two consecutive integers to be Duffinian (a Duffinian twin) (8, 9), (35, 36), (49, 50), etc.
Less common are Duffinian triplets; three consecutive Duffinian numbers. (63, 64, 65), (323, 324, 325), etc.
Much, much less common are Duffinian quadruplets and quintuplets. The first Duffinian quintuplet is (202605639573839041, 202605639573839042, 202605639573839043, 202605639573839044, 202605639573839045).
It is not possible to have six consecutive Duffinian numbers
Task
Find and show the first 50 Duffinian numbers.
Find and show at least the first 15 Duffinian triplets.
See also
Numbers Aplenty - Duffinian numbers
OEIS:A003624 - Duffinian numbers: composite numbers k relatively prime to sigma(k)
| #Factor | Factor | USING: combinators.short-circuit.smart grouping io kernel lists
lists.lazy math math.primes math.primes.factors math.statistics
prettyprint sequences sequences.deep ;
: duffinian? ( n -- ? )
{ [ prime? not ] [ dup divisors sum simple-gcd 1 = ] } && ;
: duffinians ( -- list ) 3 lfrom [ duffinian? ] lfilter ;
: triples ( -- list )
duffinians dup cdr dup cdr lzip lzip [ flatten ] lmap-lazy
[ differences { 1 1 } = ] lfilter ;
"First 50 Duffinian numbers:" print
50 duffinians ltake list>array 10 group simple-table. nl
"First 15 Duffinian triplets:" print
15 triples ltake list>array simple-table. |
http://rosettacode.org/wiki/Duffinian_numbers | Duffinian numbers | A Duffinian number is a composite number k that is relatively prime to its sigma sum σ.
The sigma sum of k is the sum of the divisors of k.
E.G.
161 is a Duffinian number.
It is composite. (7 × 23)
The sigma sum 192 (1 + 7 + 23 + 161) is relatively prime to 161.
Duffinian numbers are very common.
It is not uncommon for two consecutive integers to be Duffinian (a Duffinian twin) (8, 9), (35, 36), (49, 50), etc.
Less common are Duffinian triplets; three consecutive Duffinian numbers. (63, 64, 65), (323, 324, 325), etc.
Much, much less common are Duffinian quadruplets and quintuplets. The first Duffinian quintuplet is (202605639573839041, 202605639573839042, 202605639573839043, 202605639573839044, 202605639573839045).
It is not possible to have six consecutive Duffinian numbers
Task
Find and show the first 50 Duffinian numbers.
Find and show at least the first 15 Duffinian triplets.
See also
Numbers Aplenty - Duffinian numbers
OEIS:A003624 - Duffinian numbers: composite numbers k relatively prime to sigma(k)
| #Go | Go | package main
import (
"fmt"
"math"
"rcu"
)
func isSquare(n int) bool {
s := int(math.Sqrt(float64(n)))
return s*s == n
}
func main() {
limit := 200000 // say
d := rcu.PrimeSieve(limit-1, true)
d[1] = false
for i := 2; i < limit; i++ {
if !d[i] {
continue
}
if i%2 == 0 && !isSquare(i) && !isSquare(i/2) {
d[i] = false
continue
}
sigmaSum := rcu.SumInts(rcu.Divisors(i))
if rcu.Gcd(sigmaSum, i) != 1 {
d[i] = false
}
}
var duff []int
for i := 1; i < len(d); i++ {
if d[i] {
duff = append(duff, i)
}
}
fmt.Println("First 50 Duffinian numbers:")
rcu.PrintTable(duff[0:50], 10, 3, false)
var triplets [][3]int
for i := 2; i < limit; i++ {
if d[i] && d[i-1] && d[i-2] {
triplets = append(triplets, [3]int{i - 2, i - 1, i})
}
}
fmt.Println("\nFirst 56 Duffinian triplets:")
for i := 0; i < 14; i++ {
s := fmt.Sprintf("%6v", triplets[i*4:i*4+4])
fmt.Println(s[1 : len(s)-1])
}
} |
http://rosettacode.org/wiki/Element-wise_operations | Element-wise operations | This task is similar to:
Matrix multiplication
Matrix transposition
Task
Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks.
Implement:
addition
subtraction
multiplication
division
exponentiation
Extend the task if necessary to include additional basic operations, which should not require their own specialised task.
| #Excel | Excel | EVAL
=LAMBDA(s, EVALUATE(s))
matrix
={1,2,3;4,5,6;7,8,9} |
http://rosettacode.org/wiki/Dynamic_variable_names | Dynamic variable names | Task
Create a variable with a user-defined name.
The variable name should not be written in the program text, but should be taken from the user dynamically.
See also
Eval in environment is a similar task.
| #BBC_BASIC | BBC BASIC | INPUT "Enter a variable name: " name$
INPUT "Enter a numeric value: " numeric$
dummy% = EVAL("FNassign("+name$+","+numeric$+")")
PRINT "Variable " name$ " now has the value "; EVAL(name$)
END
DEF FNassign(RETURN n, v) : n = v : = 0 |
http://rosettacode.org/wiki/Dynamic_variable_names | Dynamic variable names | Task
Create a variable with a user-defined name.
The variable name should not be written in the program text, but should be taken from the user dynamically.
See also
Eval in environment is a similar task.
| #Bracmat | Bracmat | ( put$"Enter a variable name: "
& get$:?name
& whl
' ( put$"Enter a numeric value: "
& get$:?numeric:~#
)
& !numeric:?!name
& put$(str$("Variable " !name " now has the value " !!name \n))
); |
http://rosettacode.org/wiki/Dynamic_variable_names | Dynamic variable names | Task
Create a variable with a user-defined name.
The variable name should not be written in the program text, but should be taken from the user dynamically.
See also
Eval in environment is a similar task.
| #C.23 | C# | using System;
using System.Dynamic;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
string varname = Console.ReadLine();
//Let's pretend the user has entered "foo"
dynamic expando = new ExpandoObject();
var map = expando as IDictionary<string, object>;
map.Add(varname, "Hello world!");
Console.WriteLine(expando.foo);
}
} |
http://rosettacode.org/wiki/Egyptian_division | Egyptian division | Egyptian division is a method of dividing integers using addition and
doubling that is similar to the algorithm of Ethiopian multiplication
Algorithm:
Given two numbers where the dividend is to be divided by the divisor:
Start the construction of a table of two columns: powers_of_2, and doublings; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column.
Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order.
Continue with successive i’th rows of 2^i and 2^i * divisor.
Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend.
We now assemble two separate sums that both start as zero, called here answer and accumulator
Consider each row of the table, in the reverse order of its construction.
If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer.
When the first row has been considered as above, then the integer division of dividend by divisor is given by answer.
(And the remainder is given by the absolute value of accumulator - dividend).
Example: 580 / 34
Table creation:
powers_of_2
doublings
1
34
2
68
4
136
8
272
16
544
Initialization of sums:
powers_of_2
doublings
answer
accumulator
1
34
2
68
4
136
8
272
16
544
0
0
Considering table rows, bottom-up:
When a row is considered it is shown crossed out if it is not accumulated, or bold if the row causes summations.
powers_of_2
doublings
answer
accumulator
1
34
2
68
4
136
8
272
16
544
16
544
powers_of_2
doublings
answer
accumulator
1
34
2
68
4
136
8
272
16
544
16
544
powers_of_2
doublings
answer
accumulator
1
34
2
68
4
136
16
544
8
272
16
544
powers_of_2
doublings
answer
accumulator
1
34
2
68
16
544
4
136
8
272
16
544
powers_of_2
doublings
answer
accumulator
1
34
17
578
2
68
4
136
8
272
16
544
Answer
So 580 divided by 34 using the Egyptian method is 17 remainder (578 - 580) or 2.
Task
The task is to create a function that does Egyptian division. The function should
closely follow the description above in using a list/array of powers of two, and
another of doublings.
Functions should be clear interpretations of the algorithm.
Use the function to divide 580 by 34 and show the answer here, on this page.
Related tasks
Egyptian fractions
References
Egyptian Number System
| #Common_Lisp | Common Lisp |
(defun egyptian-division (dividend divisor)
(let* ((doublings (reverse (loop for n = divisor then (* 2 n)
until (> n dividend)
collect n)))
(powers-of-two (reverse (loop for n = 1 then (* 2 n)
repeat (length doublings)
collect n))))
(loop
for d in doublings
for p in powers-of-two
with accumulator = 0
with answer = 0
finally (return (values answer (- dividend (* answer divisor))))
when (<= (+ accumulator d) dividend)
do (incf answer p)
(incf accumulator d))))
|
http://rosettacode.org/wiki/Egyptian_division | Egyptian division | Egyptian division is a method of dividing integers using addition and
doubling that is similar to the algorithm of Ethiopian multiplication
Algorithm:
Given two numbers where the dividend is to be divided by the divisor:
Start the construction of a table of two columns: powers_of_2, and doublings; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column.
Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order.
Continue with successive i’th rows of 2^i and 2^i * divisor.
Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend.
We now assemble two separate sums that both start as zero, called here answer and accumulator
Consider each row of the table, in the reverse order of its construction.
If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer.
When the first row has been considered as above, then the integer division of dividend by divisor is given by answer.
(And the remainder is given by the absolute value of accumulator - dividend).
Example: 580 / 34
Table creation:
powers_of_2
doublings
1
34
2
68
4
136
8
272
16
544
Initialization of sums:
powers_of_2
doublings
answer
accumulator
1
34
2
68
4
136
8
272
16
544
0
0
Considering table rows, bottom-up:
When a row is considered it is shown crossed out if it is not accumulated, or bold if the row causes summations.
powers_of_2
doublings
answer
accumulator
1
34
2
68
4
136
8
272
16
544
16
544
powers_of_2
doublings
answer
accumulator
1
34
2
68
4
136
8
272
16
544
16
544
powers_of_2
doublings
answer
accumulator
1
34
2
68
4
136
16
544
8
272
16
544
powers_of_2
doublings
answer
accumulator
1
34
2
68
16
544
4
136
8
272
16
544
powers_of_2
doublings
answer
accumulator
1
34
17
578
2
68
4
136
8
272
16
544
Answer
So 580 divided by 34 using the Egyptian method is 17 remainder (578 - 580) or 2.
Task
The task is to create a function that does Egyptian division. The function should
closely follow the description above in using a list/array of powers of two, and
another of doublings.
Functions should be clear interpretations of the algorithm.
Use the function to divide 580 by 34 and show the answer here, on this page.
Related tasks
Egyptian fractions
References
Egyptian Number System
| #D | D |
import std.stdio;
version(unittest) {
// empty
} else {
int main(string[] args) {
import std.conv;
if (args.length < 3) {
stderr.writeln("Usage: ", args[0], " dividend divisor");
return 1;
}
ulong dividend = to!ulong(args[1]);
ulong divisor = to!ulong(args[2]);
ulong remainder;
auto ans = egyptian_division(dividend, divisor, remainder);
writeln(dividend, " / ", divisor, " = ", ans, " rem ", remainder);
return 0;
}
}
ulong egyptian_division(ulong dividend, ulong divisor, out ulong remainder) {
enum SIZE = 64;
ulong[SIZE] powers;
ulong[SIZE] doublings;
int i;
for (; i<SIZE; ++i) {
powers[i] = 1 << i;
doublings[i] = divisor << i;
if (doublings[i] > dividend) {
break;
}
}
ulong answer;
ulong accumulator;
for (i=i-1; i>=0; --i) {
if (accumulator + doublings[i] <= dividend) {
accumulator += doublings[i];
answer += powers[i];
}
}
remainder = dividend - accumulator;
return answer;
}
unittest {
ulong remainder;
assert(egyptian_division(580UL, 34UL, remainder) == 17UL);
assert(remainder == 2);
}
|
http://rosettacode.org/wiki/Egyptian_fractions | Egyptian fractions | An Egyptian fraction is the sum of distinct unit fractions such as:
1
2
+
1
3
+
1
16
(
=
43
48
)
{\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})}
Each fraction in the expression has a numerator equal to 1 (unity) and a denominator that is a positive integer, and all the denominators are distinct (i.e., no repetitions).
Fibonacci's Greedy algorithm for Egyptian fractions expands the fraction
x
y
{\displaystyle {\tfrac {x}{y}}}
to be represented by repeatedly performing the replacement
x
y
=
1
⌈
y
/
x
⌉
+
(
−
y
)
mod
x
y
⌈
y
/
x
⌉
{\displaystyle {\frac {x}{y}}={\frac {1}{\lceil y/x\rceil }}+{\frac {(-y)\!\!\!\!\mod x}{y\lceil y/x\rceil }}}
(simplifying the 2nd term in this replacement as necessary, and where
⌈
x
⌉
{\displaystyle \lceil x\rceil }
is the ceiling function).
For this task, Proper and improper fractions must be able to be expressed.
Proper fractions are of the form
a
b
{\displaystyle {\tfrac {a}{b}}}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are positive integers, such that
a
<
b
{\displaystyle a<b}
, and
improper fractions are of the form
a
b
{\displaystyle {\tfrac {a}{b}}}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are positive integers, such that a ≥ b.
(See the REXX programming example to view one method of expressing the whole number part of an improper fraction.)
For improper fractions, the integer part of any improper fraction should be first isolated and shown preceding the Egyptian unit fractions, and be surrounded by square brackets [n].
Task requirements
show the Egyptian fractions for:
43
48
{\displaystyle {\tfrac {43}{48}}}
and
5
121
{\displaystyle {\tfrac {5}{121}}}
and
2014
59
{\displaystyle {\tfrac {2014}{59}}}
for all proper fractions,
a
b
{\displaystyle {\tfrac {a}{b}}}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are positive one-or two-digit (decimal) integers, find and show an Egyptian fraction that has:
the largest number of terms,
the largest denominator.
for all one-, two-, and three-digit integers, find and show (as above). {extra credit}
Also see
Wolfram MathWorld™ entry: Egyptian fraction
| #Factor | Factor | USING: backtrack formatting fry kernel locals make math
math.functions math.ranges sequences ;
IN: rosetta-code.egyptian-fractions
: >improper ( r -- str ) >fraction "%d/%d" sprintf ;
: improper ( x y -- a b ) [ /i ] [ [ rem ] [ nip ] 2bi / ] 2bi ;
:: proper ( x y -- a b )
y x / ceiling :> d1 1 d1 / y neg x rem y d1 * / ;
: expand ( a -- b c )
>fraction 2dup > [ improper ] [ proper ] if ;
: egyptian-fractions ( x -- seq )
[ [ expand [ , ] dip dup 0 = not ] loop drop ] { } make ;
: part1 ( -- )
43/48 5/121 2014/59 [
[ >improper ] [ egyptian-fractions ] bi
"%s => %[%u, %]\n" printf
] tri@ ;
: all-longest ( seq -- seq )
dup longest length '[ length _ = ] filter ;
: (largest-denominator) ( seq -- n )
[ denominator ] map supremum ;
: most-terms ( seq -- )
all-longest [ [ sum ] map ] [ first length ] bi
"most terms: %[%u, %] => %d\n" printf ;
: largest-denominator ( seq -- )
[ (largest-denominator) ] supremum-by
[ sum ] [ (largest-denominator) ] bi
"largest denominator: %u => %d\n" printf ;
: part2 ( -- )
[
99 [1,b] amb-lazy dup [1,b] amb-lazy swap /
egyptian-fractions
] bag-of [ most-terms ] [ largest-denominator ] bi ;
: egyptian-fractions-demo ( -- ) part1 part2 ;
MAIN: egyptian-fractions-demo |
http://rosettacode.org/wiki/Eertree | Eertree | An eertree is a data structure designed for efficient processing of certain palindrome tasks, for instance counting the number of sub-palindromes in an input string.
The data structure has commonalities to both tries and suffix trees.
See links below.
Task
Construct an eertree for the string "eertree", then output all sub-palindromes by traversing the tree.
See also
Wikipedia entry: trie.
Wikipedia entry: suffix tree
Cornell University Library, Computer Science, Data Structures and Algorithms ───► EERTREE: An Efficient Data Structure for Processing Palindromes in Strings.
| #Ruby | Ruby | class Node
def initialize(length, edges = {}, suffix = 0)
@length = length
@edges = edges
@suffix = suffix
end
attr_reader :length
attr_reader :edges
attr_accessor :suffix
end
EVEN_ROOT = 0
ODD_ROOT = 1
def eertree(s)
tree = [
Node.new(0, {}, ODD_ROOT),
Node.new(-1, {}, ODD_ROOT)
]
suffix = ODD_ROOT
s.each_char.with_index { |c, i|
n = suffix
k = 0
loop do
k = tree[n].length
b = i - k - 1
if b >= 0 and s[b] == c then
break
end
n = tree[n].suffix
end
if tree[n].edges.key?(c) then
suffix = tree[n].edges[c]
next
end
suffix = tree.length
tree << Node.new(k + 2)
tree[n].edges[c] = suffix
if tree[suffix].length == 1 then
tree[suffix].suffix = 0
next
end
loop do
n = tree[n].suffix
b = i - tree[n].length - 1
if b >= 0 and s[b] == c then
break
end
end
tree[suffix].suffix = tree[n].edges[c]
}
return tree
end
def subPalindromes(tree)
s = []
children = lambda { |n,p,f|
for c,v in tree[n].edges
m = tree[n].edges[c]
p = c + p + c
s << p
f.call(m, p, f)
end
}
children.call(0, '', children)
for c,n in tree[1].edges
s << c
children.call(n, c, children)
end
return s
end
tree = eertree("eertree")
print subPalindromes(tree), "\n" |
http://rosettacode.org/wiki/Ethiopian_multiplication | Ethiopian multiplication | Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving.
Method:
Take two numbers to be multiplied and write them down at the top of two columns.
In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last in the same column, until you write a value of 1.
In the right-hand column repeatedly double the last number and write the result below. stop when you add a result in the same row as where the left hand column shows 1.
Examine the table produced and discard any row where the value in the left column is even.
Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together
For example: 17 × 34
17 34
Halving the first column:
17 34
8
4
2
1
Doubling the second column:
17 34
8 68
4 136
2 272
1 544
Strike-out rows whose first cell is even:
17 34
8 68
4 136
2 272
1 544
Sum the remaining numbers in the right-hand column:
17 34
8 --
4 ---
2 ---
1 544
====
578
So 17 multiplied by 34, by the Ethiopian method is 578.
Task
The task is to define three named functions/methods/procedures/subroutines:
one to halve an integer,
one to double an integer, and
one to state if an integer is even.
Use these functions to create a function that does Ethiopian multiplication.
References
Ethiopian multiplication explained (BBC Video clip)
A Night Of Numbers - Go Forth And Multiply (Video)
Russian Peasant Multiplication
Programming Praxis: Russian Peasant Multiplication
| #Red | Red | Red["Ethiopian multiplication"]
halve: function [n][n >> 1]
double: function [n][n << 1]
;== even? already exists
ethiopian-multiply: function [
"Returns the product of two integers using Ethiopian multiplication"
a [integer!] "The multiplicand"
b [integer!] "The multiplier"
][
result: 0
while [a <> 0][
if odd? a [result: result + b]
a: halve a
b: double b
]
result
]
print ethiopian-multiply 17 34 |
http://rosettacode.org/wiki/Elementary_cellular_automaton | Elementary cellular automaton | An elementary cellular automaton is a one-dimensional cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three bits.
The rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101.
Task
Create a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice.
The space state should wrap: this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally.
This task is basically a generalization of one-dimensional cellular automata.
See also
Cellular automata (natureofcode.com)
| #Haskell | Haskell | import Data.Array (listArray, (!), bounds, elems)
step rule a = listArray (l,r) res
where (l,r) = bounds a
res = [rule (a!r) (a!l) (a!(l+1)) ] ++
[rule (a!(i-1)) (a!i) (a!(i+1)) | i <- [l+1..r-1] ] ++
[rule (a!(r-1)) (a!r) (a!l) ]
runCA rule = iterate (step rule) |
http://rosettacode.org/wiki/Factorial | Factorial | Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a number.
Solutions can be iterative or recursive.
Support for trapping negative n errors is optional.
Related task
Primorial numbers
| #True_BASIC | True BASIC | DEF FNfactorial(n)
LET f = 1
FOR i = 2 TO n
LET f = f*i
NEXT i
LET FNfactorial = f
END DEF
END |
http://rosettacode.org/wiki/Even_or_odd | Even or odd | Task
Test whether an integer is even or odd.
There is more than one way to solve this task:
Use the even and odd predicates, if the language provides them.
Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd.
Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd.
Use modular congruences:
i ≡ 0 (mod 2) iff i is even.
i ≡ 1 (mod 2) iff i is odd.
| #x86-64_Assembly | x86-64 Assembly |
evenOdd:
mov rax,1
and rax,rdi
ret
|
http://rosettacode.org/wiki/Even_or_odd | Even or odd | Task
Test whether an integer is even or odd.
There is more than one way to solve this task:
Use the even and odd predicates, if the language provides them.
Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd.
Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd.
Use modular congruences:
i ≡ 0 (mod 2) iff i is even.
i ≡ 1 (mod 2) iff i is odd.
| #XBS | XBS | #>
Typed XBS
evenOrOdd function
true = even
false = odd
<#
func evenOrOdd(a:number=0){
send a%2==0;
}
set arr:array = [0,1,2,3,4,5,6,7,9,10];
foreach(v of arr){
log(v+" is even? "+evenOrOdd(v))
} |
http://rosettacode.org/wiki/Echo_server | Echo server | Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary to support connections from localhost (127.0.0.1 or perhaps ::1). Logging of connection information to standard output is recommended.
The implementation must be able to handle simultaneous connections from multiple clients. A multi-threaded or multi-process solution may be used. Each connection must be able to echo more than a single line.
The implementation must not stop responding to other clients if one client sends a partial line or stops reading responses.
| #Java | Java | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
public class EchoServer {
public static void main(String[] args) throws IOException {
try (ServerSocket listener = new ServerSocket(12321)) {
while (true) {
Socket conn = listener.accept();
Thread clientThread = new Thread(() -> handleClient(conn));
clientThread.start();
}
}
}
private static void handleClient(Socket connArg) {
Charset utf8 = StandardCharsets.UTF_8;
try (Socket conn = connArg) {
BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream(), utf8));
PrintWriter out = new PrintWriter(
new OutputStreamWriter(conn.getOutputStream(), utf8),
true);
String line;
while ((line = in.readLine()) != null) {
out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
} |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Tiny_BASIC | Tiny BASIC | |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Toka | Toka | bye
|
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Trith | Trith | |
http://rosettacode.org/wiki/Eban_numbers | Eban numbers |
Definition
An eban number is a number that has no letter e in it when the number is spelled in English.
Or more literally, spelled numbers that contain the letter e are banned.
The American version of spelling numbers will be used here (as opposed to the British).
2,000,000,000 is two billion, not two milliard.
Only numbers less than one sextillion (1021) will be considered in/for this task.
This will allow optimizations to be used.
Task
show all eban numbers ≤ 1,000 (in a horizontal format), and a count
show all eban numbers between 1,000 and 4,000 (inclusive), and a count
show a count of all eban numbers up and including 10,000
show a count of all eban numbers up and including 100,000
show a count of all eban numbers up and including 1,000,000
show a count of all eban numbers up and including 10,000,000
show all output here.
See also
The MathWorld entry: eban numbers.
The OEIS entry: A6933, eban numbers.
| #C | C | #include "stdio.h"
#include "stdbool.h"
#define ARRAY_LEN(a,T) (sizeof(a) / sizeof(T))
struct Interval {
int start, end;
bool print;
};
int main() {
struct Interval intervals[] = {
{2, 1000, true},
{1000, 4000, true},
{2, 10000, false},
{2, 100000, false},
{2, 1000000, false},
{2, 10000000, false},
{2, 100000000, false},
{2, 1000000000, false},
};
int idx;
for (idx = 0; idx < ARRAY_LEN(intervals, struct Interval); ++idx) {
struct Interval intv = intervals[idx];
int count = 0, i;
if (intv.start == 2) {
printf("eban numbers up to and including %d:\n", intv.end);
} else {
printf("eban numbers between %d and %d (inclusive:)", intv.start, intv.end);
}
for (i = intv.start; i <= intv.end; i += 2) {
int b = i / 1000000000;
int r = i % 1000000000;
int m = r / 1000000;
int t;
r = i % 1000000;
t = r / 1000;
r %= 1000;
if (m >= 30 && m <= 66) m %= 10;
if (t >= 30 && t <= 66) t %= 10;
if (r >= 30 && r <= 66) r %= 10;
if (b == 0 || b == 2 || b == 4 || b == 6) {
if (m == 0 || m == 2 || m == 4 || m == 6) {
if (t == 0 || t == 2 || t == 4 || t == 6) {
if (r == 0 || r == 2 || r == 4 || r == 6) {
if (intv.print) printf("%d ", i);
count++;
}
}
}
}
}
if (intv.print) {
printf("\n");
}
printf("count = %d\n\n", count);
}
return 0;
} |
http://rosettacode.org/wiki/Duffinian_numbers | Duffinian numbers | A Duffinian number is a composite number k that is relatively prime to its sigma sum σ.
The sigma sum of k is the sum of the divisors of k.
E.G.
161 is a Duffinian number.
It is composite. (7 × 23)
The sigma sum 192 (1 + 7 + 23 + 161) is relatively prime to 161.
Duffinian numbers are very common.
It is not uncommon for two consecutive integers to be Duffinian (a Duffinian twin) (8, 9), (35, 36), (49, 50), etc.
Less common are Duffinian triplets; three consecutive Duffinian numbers. (63, 64, 65), (323, 324, 325), etc.
Much, much less common are Duffinian quadruplets and quintuplets. The first Duffinian quintuplet is (202605639573839041, 202605639573839042, 202605639573839043, 202605639573839044, 202605639573839045).
It is not possible to have six consecutive Duffinian numbers
Task
Find and show the first 50 Duffinian numbers.
Find and show at least the first 15 Duffinian triplets.
See also
Numbers Aplenty - Duffinian numbers
OEIS:A003624 - Duffinian numbers: composite numbers k relatively prime to sigma(k)
| #J | J | sigmasum=: >:@#.~/.~&.q:
composite=: 1&< * 0 = 1&p:
duffinian=: composite * 1 = ] +. sigmasum |
http://rosettacode.org/wiki/Duffinian_numbers | Duffinian numbers | A Duffinian number is a composite number k that is relatively prime to its sigma sum σ.
The sigma sum of k is the sum of the divisors of k.
E.G.
161 is a Duffinian number.
It is composite. (7 × 23)
The sigma sum 192 (1 + 7 + 23 + 161) is relatively prime to 161.
Duffinian numbers are very common.
It is not uncommon for two consecutive integers to be Duffinian (a Duffinian twin) (8, 9), (35, 36), (49, 50), etc.
Less common are Duffinian triplets; three consecutive Duffinian numbers. (63, 64, 65), (323, 324, 325), etc.
Much, much less common are Duffinian quadruplets and quintuplets. The first Duffinian quintuplet is (202605639573839041, 202605639573839042, 202605639573839043, 202605639573839044, 202605639573839045).
It is not possible to have six consecutive Duffinian numbers
Task
Find and show the first 50 Duffinian numbers.
Find and show at least the first 15 Duffinian triplets.
See also
Numbers Aplenty - Duffinian numbers
OEIS:A003624 - Duffinian numbers: composite numbers k relatively prime to sigma(k)
| #Julia | Julia | using Primes
function σ(n)
f = [one(n)]
for (p,e) in factor(n)
f = reduce(vcat, [f*p^j for j in 1:e], init=f)
end
return sum(f)
end
isDuffinian(n) = !isprime(n) && gcd(n, σ(n)) == 1
function testDuffinians()
println("First 50 Duffinian numbers:")
foreach(p -> print(rpad(p[2], 4), p[1] % 25 == 0 ? "\n" : ""),
enumerate(filter(isDuffinian, 2:217)))
n, found = 2, 0
println("\nFifteen Duffinian triplets:")
while found < 15
if isDuffinian(n) && isDuffinian(n + 1) && isDuffinian(n + 2)
println(lpad(n, 6), lpad(n +1, 6), lpad(n + 2, 6))
found += 1
end
n += 1
end
end
testDuffinians()
|
http://rosettacode.org/wiki/Duffinian_numbers | Duffinian numbers | A Duffinian number is a composite number k that is relatively prime to its sigma sum σ.
The sigma sum of k is the sum of the divisors of k.
E.G.
161 is a Duffinian number.
It is composite. (7 × 23)
The sigma sum 192 (1 + 7 + 23 + 161) is relatively prime to 161.
Duffinian numbers are very common.
It is not uncommon for two consecutive integers to be Duffinian (a Duffinian twin) (8, 9), (35, 36), (49, 50), etc.
Less common are Duffinian triplets; three consecutive Duffinian numbers. (63, 64, 65), (323, 324, 325), etc.
Much, much less common are Duffinian quadruplets and quintuplets. The first Duffinian quintuplet is (202605639573839041, 202605639573839042, 202605639573839043, 202605639573839044, 202605639573839045).
It is not possible to have six consecutive Duffinian numbers
Task
Find and show the first 50 Duffinian numbers.
Find and show at least the first 15 Duffinian triplets.
See also
Numbers Aplenty - Duffinian numbers
OEIS:A003624 - Duffinian numbers: composite numbers k relatively prime to sigma(k)
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[DuffianQ]
DuffianQ[n_Integer] := CompositeQ[n] \[And] CoprimeQ[DivisorSigma[1, n], n]
dns = Select[DuffianQ][Range[1000000]];
Take[dns, UpTo[50]]
triplets = ToString[dns[[#]]] <> "\[LongDash]" <> ToString[dns[[# + 2]]] & /@ SequencePosition[Differences[dns], {1, 1}][[All, 1]]
Multicolumn[triplets, {Automatic, 5}, Appearance -> "Horizontal"] |
http://rosettacode.org/wiki/Duffinian_numbers | Duffinian numbers | A Duffinian number is a composite number k that is relatively prime to its sigma sum σ.
The sigma sum of k is the sum of the divisors of k.
E.G.
161 is a Duffinian number.
It is composite. (7 × 23)
The sigma sum 192 (1 + 7 + 23 + 161) is relatively prime to 161.
Duffinian numbers are very common.
It is not uncommon for two consecutive integers to be Duffinian (a Duffinian twin) (8, 9), (35, 36), (49, 50), etc.
Less common are Duffinian triplets; three consecutive Duffinian numbers. (63, 64, 65), (323, 324, 325), etc.
Much, much less common are Duffinian quadruplets and quintuplets. The first Duffinian quintuplet is (202605639573839041, 202605639573839042, 202605639573839043, 202605639573839044, 202605639573839045).
It is not possible to have six consecutive Duffinian numbers
Task
Find and show the first 50 Duffinian numbers.
Find and show at least the first 15 Duffinian triplets.
See also
Numbers Aplenty - Duffinian numbers
OEIS:A003624 - Duffinian numbers: composite numbers k relatively prime to sigma(k)
| #Perl | Perl | use strict;
use warnings;
use feature <say state>;
use List::Util 'max';
use ntheory qw<divisor_sum is_prime gcd>;
sub table { my $t = shift() * (my $c = 1 + max map {length} @_); ( sprintf( ('%'.$c.'s')x@_, @_) ) =~ s/.{1,$t}\K/\n/gr }
sub duffinian {
my($n) = @_;
state $c = 1; state @D;
do { push @D, $c if ! is_prime ++$c and 1 == gcd($c,divisor_sum($c)) } until @D > $n;
$D[$n];
}
say "First 50 Duffinian numbers:";
say table 10, map { duffinian $_-1 } 1..50;
my(@d3,@triples) = (4, 8, 9); my $n = 3;
while (@triples < 39) {
push @triples, '('.join(', ',@d3).')' if $d3[1] == 1+$d3[0] and $d3[2] == 2+$d3[0];
shift @d3 and push @d3, duffinian ++$n;
}
say 'First 39 Duffinian triplets:';
say table 3, @triples; |
http://rosettacode.org/wiki/Element-wise_operations | Element-wise operations | This task is similar to:
Matrix multiplication
Matrix transposition
Task
Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks.
Implement:
addition
subtraction
multiplication
division
exponentiation
Extend the task if necessary to include additional basic operations, which should not require their own specialised task.
| #Factor | Factor | USING: combinators.extras formatting kernel math.functions
math.matrices math.vectors prettyprint sequences ;
: show ( a b words -- )
[
3dup execute( x x -- x ) [ unparse ] dip
"%u %u %s = %u\n" printf
] 2with each ; inline
: m^n ( m n -- m ) [ ^ ] curry matrix-map ;
: m^ ( m m -- m ) [ v^ ] 2map ;
{ { 1 2 } { 3 4 } } { { 5 6 } { 7 8 } } { m+ m- m* m/ m^ }
{ { -1 9 4 } { 5 -13 0 } } 3 { m+n m-n m*n m/n m^n }
[ show ] 3bi@ |
http://rosettacode.org/wiki/Dynamic_variable_names | Dynamic variable names | Task
Create a variable with a user-defined name.
The variable name should not be written in the program text, but should be taken from the user dynamically.
See also
Eval in environment is a similar task.
| #Clojure | Clojure | (eval `(def ~(symbol (read)) 42)) |
http://rosettacode.org/wiki/Dynamic_variable_names | Dynamic variable names | Task
Create a variable with a user-defined name.
The variable name should not be written in the program text, but should be taken from the user dynamically.
See also
Eval in environment is a similar task.
| #Common_Lisp | Common Lisp |
(setq var-name (read)) ; reads a name into var-name
(set var-name 1) ; assigns the value 1 to a variable named as entered by the user
|
http://rosettacode.org/wiki/Egyptian_division | Egyptian division | Egyptian division is a method of dividing integers using addition and
doubling that is similar to the algorithm of Ethiopian multiplication
Algorithm:
Given two numbers where the dividend is to be divided by the divisor:
Start the construction of a table of two columns: powers_of_2, and doublings; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column.
Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order.
Continue with successive i’th rows of 2^i and 2^i * divisor.
Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend.
We now assemble two separate sums that both start as zero, called here answer and accumulator
Consider each row of the table, in the reverse order of its construction.
If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer.
When the first row has been considered as above, then the integer division of dividend by divisor is given by answer.
(And the remainder is given by the absolute value of accumulator - dividend).
Example: 580 / 34
Table creation:
powers_of_2
doublings
1
34
2
68
4
136
8
272
16
544
Initialization of sums:
powers_of_2
doublings
answer
accumulator
1
34
2
68
4
136
8
272
16
544
0
0
Considering table rows, bottom-up:
When a row is considered it is shown crossed out if it is not accumulated, or bold if the row causes summations.
powers_of_2
doublings
answer
accumulator
1
34
2
68
4
136
8
272
16
544
16
544
powers_of_2
doublings
answer
accumulator
1
34
2
68
4
136
8
272
16
544
16
544
powers_of_2
doublings
answer
accumulator
1
34
2
68
4
136
16
544
8
272
16
544
powers_of_2
doublings
answer
accumulator
1
34
2
68
16
544
4
136
8
272
16
544
powers_of_2
doublings
answer
accumulator
1
34
17
578
2
68
4
136
8
272
16
544
Answer
So 580 divided by 34 using the Egyptian method is 17 remainder (578 - 580) or 2.
Task
The task is to create a function that does Egyptian division. The function should
closely follow the description above in using a list/array of powers of two, and
another of doublings.
Functions should be clear interpretations of the algorithm.
Use the function to divide 580 by 34 and show the answer here, on this page.
Related tasks
Egyptian fractions
References
Egyptian Number System
| #Delphi | Delphi |
program Egyptian_division;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.Math,
System.Console; //https://github.com/JensBorrisholt/DelphiConsole
type
TIntegerDynArray = TArray<Integer>;
TIntegerDynArrayHelper = record helper for TIntegerDynArray
public
procedure Add(value: Integer);
end;
procedure Divide(dividend, divisor: Integer);
var
result, reminder, powers_of_two, doublings, answer, accumulator, two, pow, row: Integer;
table_powers_of_two, table_doublings: TIntegerDynArray;
begin
result := 0;
reminder := 0;
powers_of_two := 0;
doublings := 0;
answer := 0;
accumulator := 0;
two := 2;
pow := 0;
row := 0;
writeln(' ');
writeln(' powers_of_2 doublings ');
writeln(' ');
powers_of_two := 1;
doublings := divisor;
while doublings <= dividend do
begin
table_powers_of_two.Add(powers_of_two);
table_doublings.Add(doublings);
Writeln(Format('%8d %16d', [powers_of_two, doublings]));
Inc(pow);
powers_of_two := Trunc(IntPower(two, pow));
doublings := powers_of_two * divisor;
end;
writeln(' ');
row := pow - 1;
writeln(' ');
writeln(' powers_of_2 doublings answer accumulator');
writeln(' ');
Console.SetCursorPosition(Console.CursorLeft, Console.CursorTop + row);
Dec(pow);
while (pow >= 0) and (accumulator < dividend) do
begin
doublings := Trunc(table_doublings[pow]);
powers_of_two := Trunc(table_powers_of_two[pow]);
if (accumulator + Trunc(table_doublings[pow])) <= dividend then
begin
accumulator := accumulator + doublings;
answer := answer + powers_of_two;
Console.ForegroundColor := TConsoleColor.Green;
Write(Format('%8d %16d', [powers_of_two, doublings]));
Console.ForegroundColor := TConsoleColor.Green;
writeln(format('%10d %12d', [answer, accumulator]));
Console.SetCursorPosition(Console.CursorLeft, Console.CursorTop - 2);
end
else
begin
Console.ForegroundColor := TConsoleColor.DarkGray;
Write(Format('%8d %16d', [powers_of_two, doublings]));
Console.ForegroundColor := TConsoleColor.Gray;
writeln(format('%10d %12d', [answer, accumulator]));
Console.SetCursorPosition(Console.CursorLeft, Console.CursorTop - 2);
end;
Dec(pow);
end;
writeln;
Console.SetCursorPosition(Console.CursorLeft, Console.CursorTop + row + 2);
Console.ResetColor();
result := answer;
if accumulator < dividend then
begin
reminder := dividend - accumulator;
Console.WriteLine(' So ' + dividend.ToString + ' divided by ' + divisor.ToString
+ ' using the Egyptian method is '#10' ' + result.ToString +
' remainder (' + dividend.ToString + ' - ' + accumulator.ToString +
') or ' + reminder.ToString);
writeln;
end
else
begin
reminder := 0;
Console.WriteLine(' So ' + dividend.ToString + ' divided by ' + divisor.ToString
+ ' using the Egyptian method is '#10' ' + result.ToString + ' remainder '
+ reminder.ToString);
writeln;
end;
end;
{ TIntegerDynArrayHelper }
procedure TIntegerDynArrayHelper.Add(value: Integer);
begin
SetLength(self, length(self) + 1);
Self[high(self)] := value;
end;
function parseInt(s: string): Integer;
var
c: Char;
s2: string;
begin
s2 := '';
for c in s do
begin
if c in ['0'..'9'] then
s2 := s2 + c;
end;
result := s2.ToInteger();
end;
var
dividend, divisor: Integer;
begin
Console.Clear();
writeln;
writeln(' Egyptian division ');
writeln;
Console.Write(' Enter value of dividend : ');
dividend := parseInt(Console.ReadLine());
Console.Write(' Enter value of divisor : ');
divisor := parseInt(Console.ReadLine());
Divide(dividend, divisor);
writeln;
Console.Write('Press any key to continue . . . ');
Console.ReadKey(true);
end. |
http://rosettacode.org/wiki/Egyptian_fractions | Egyptian fractions | An Egyptian fraction is the sum of distinct unit fractions such as:
1
2
+
1
3
+
1
16
(
=
43
48
)
{\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})}
Each fraction in the expression has a numerator equal to 1 (unity) and a denominator that is a positive integer, and all the denominators are distinct (i.e., no repetitions).
Fibonacci's Greedy algorithm for Egyptian fractions expands the fraction
x
y
{\displaystyle {\tfrac {x}{y}}}
to be represented by repeatedly performing the replacement
x
y
=
1
⌈
y
/
x
⌉
+
(
−
y
)
mod
x
y
⌈
y
/
x
⌉
{\displaystyle {\frac {x}{y}}={\frac {1}{\lceil y/x\rceil }}+{\frac {(-y)\!\!\!\!\mod x}{y\lceil y/x\rceil }}}
(simplifying the 2nd term in this replacement as necessary, and where
⌈
x
⌉
{\displaystyle \lceil x\rceil }
is the ceiling function).
For this task, Proper and improper fractions must be able to be expressed.
Proper fractions are of the form
a
b
{\displaystyle {\tfrac {a}{b}}}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are positive integers, such that
a
<
b
{\displaystyle a<b}
, and
improper fractions are of the form
a
b
{\displaystyle {\tfrac {a}{b}}}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are positive integers, such that a ≥ b.
(See the REXX programming example to view one method of expressing the whole number part of an improper fraction.)
For improper fractions, the integer part of any improper fraction should be first isolated and shown preceding the Egyptian unit fractions, and be surrounded by square brackets [n].
Task requirements
show the Egyptian fractions for:
43
48
{\displaystyle {\tfrac {43}{48}}}
and
5
121
{\displaystyle {\tfrac {5}{121}}}
and
2014
59
{\displaystyle {\tfrac {2014}{59}}}
for all proper fractions,
a
b
{\displaystyle {\tfrac {a}{b}}}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are positive one-or two-digit (decimal) integers, find and show an Egyptian fraction that has:
the largest number of terms,
the largest denominator.
for all one-, two-, and three-digit integers, find and show (as above). {extra credit}
Also see
Wolfram MathWorld™ entry: Egyptian fraction
| #FreeBASIC | FreeBASIC | ' version 16-01-2017
' compile with: fbc -s console
#Define max 30
#Include Once "gmp.bi"
Dim Shared As Mpz_ptr num(max), den(max)
Function Egyptian_fraction(fraction As String, ByRef whole As Integer, range As Integer = 0) As Integer
If InStr(fraction,"/") = 0 Then
Print "Not a fraction, program will end"
Sleep 5000, 1
End
End If
Dim As Integer i, count
Dim As Mpz_ptr tmp_num, tmp_den, x, y, q
tmp_num = Allocate(Len(__Mpz_struct)) : Mpz_init(tmp_num)
tmp_den = Allocate(Len(__Mpz_struct)) : Mpz_init(tmp_den)
x = Allocate(Len(__Mpz_struct)) : Mpz_init(x)
y = Allocate(Len(__Mpz_struct)) : Mpz_init(y)
q = Allocate(Len(__Mpz_struct)) : Mpz_init(q)
For i = 1 To max ' clear the list
Mpz_set_ui(num(i), 0)
Mpz_set_ui(den(i), 0)
Next
i = InStr(fraction,"/")
Mpz_set_str(x, Left(fraction, i -1), 10)
Mpz_set_str(y, Right(fraction, Len(fraction) - i), 10)
' if it's a improper fraction make it proper fraction
If Mpz_cmp(x , y) > 0 Then
Mpz_fdiv_q(q, x, y)
whole = Mpz_get_ui(q)
Mpz_fdiv_r(x, x, q)
Else
whole = 0
End If
Mpz_gcd(q, x, y) ' check if reduction is possible
If Mpz_cmp_ui(q, 1) > 0 Then
If range <> 0 Then ' return if we do a range test
Return -1
Else
Mpz_fdiv_q(x, x, q)
Mpz_fdiv_q(y, y, q)
End If
End If
Mpz_set(num(count), x)
Mpz_set(den(count), y)
' Fibonacci's Greedy algorithm for Egyptian fractions
Do
If Mpz_cmp_ui(num(count), 1) = 0 Then Exit Do
Mpz_set(x, num(count))
Mpz_set(y, den(count))
Mpz_cdiv_q(q, y, x)
Mpz_set_ui(num(count), 1)
Mpz_set(den(count), q)
Mpz_mul(tmp_den, y, q)
Mpz_neg(y, y)
Mpz_mod(tmp_num, y, x)
count += 1
Mpz_gcd(q, tmp_num, tmp_den) ' check if reduction is possible
If Mpz_cmp_ui(q, 1) > 0 Then
Mpz_fdiv_q(tmp_num, tmp_num, q)
Mpz_fdiv_q(tmp_den, tmp_den, q)
End If
Mpz_set(num(count), tmp_num)
Mpz_set(den(count), tmp_den)
Loop
Mpz_clear(tmp_num) : Mpz_clear(tmp_den)
Mpz_clear(x) : Mpz_clear(y) :Mpz_clear(q)
Return count
End Function
Sub prt_solution(fraction As String, whole As Integer, count As Integer)
Print fraction; " = ";
If whole <> 0 Then
Print "["; Str(whole); "] + ";
End If
For i As Integer = 0 To count
Gmp_printf("%Zd/%Zd ", num(i), den(i))
If i <> count Then Print "+ ";
Next
Print
End Sub
' ------=< MAIN >=------
Dim As Integer n, d, number, improper, max_term, max_size
Dim As String str_in, max_term_str, max_size_str, m_str
Dim As ZString Ptr gmp_str : gmp_str = Allocate(1000000)
For n = 0 To max
num(n) = Allocate(Len(__Mpz_struct)) : Mpz_init(num(n))
den(n) = Allocate(Len(__Mpz_struct)) : Mpz_init(den(n))
Next
Data "43/48", "5/121", "2014/59"
' 4/121 = 12/363 = 11/363 + 1/363 = 1/33 + 1/363
' 5/121 = 4/121 + 1/121 = 1/33 + 1/121 + 1/363
' 2014/59 = 34 + 8/59
' 8/59 = 1/8 + 5/472 = 1/8 + 4/472 + 1/472 = 1/8 + 1/118 + 1/472
For n = 1 To 3
Read str_in
number = Egyptian_fraction(str_in, improper)
prt_solution(str_in, improper, number)
Print
Next
Dim As Integer a = 1 , b = 99
Do
For d = a To b
For n = 1 To d -1
str_in = Str(n) + "/" + Str(d)
number = Egyptian_fraction(str_in, improper,1)
If number = -1 Then Continue For ' skip
If number > max_term Then
max_term = number
max_term_str = str_in
ElseIf number = max_term Then
max_term_str += ", " & str_in
End If
Mpz_get_str(gmp_str, 10, den(number))
If Len(*gmp_str) > max_size Then
max_size = Len(*gmp_str)
max_size_str = str_in
m_str = *gmp_str
ElseIf max_size = Len(*gmp_str) Then
max_size_str += ", " & str_in
End If
Next
Next
Print
Print "for 1 to"; Len(Str(b)); " digits"
Print "Largest number of terms is"; max_term +1; " for "; max_term_str
Print "Largest size for denominator is"; max_size; " for "; max_size_str
If b = 999 Then Exit Do
a = b +1 : b = b * 10 +9
Loop
For n = 0 To max
Mpz_clear(num(n))
Mpz_clear(den(n))
Next
DeAllocate(gmp_str)
' empty keyboard buffer
While InKey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End |
http://rosettacode.org/wiki/Eertree | Eertree | An eertree is a data structure designed for efficient processing of certain palindrome tasks, for instance counting the number of sub-palindromes in an input string.
The data structure has commonalities to both tries and suffix trees.
See links below.
Task
Construct an eertree for the string "eertree", then output all sub-palindromes by traversing the tree.
See also
Wikipedia entry: trie.
Wikipedia entry: suffix tree
Cornell University Library, Computer Science, Data Structures and Algorithms ───► EERTREE: An Efficient Data Structure for Processing Palindromes in Strings.
| #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Class Node
Public Sub New(Len As Integer)
Length = Len
Edges = New Dictionary(Of Char, Integer)
End Sub
Public Sub New(len As Integer, edg As Dictionary(Of Char, Integer), suf As Integer)
Length = len
Edges = If(IsNothing(edg), New Dictionary(Of Char, Integer), edg)
Suffix = suf
End Sub
Property Edges As Dictionary(Of Char, Integer)
Property Length As Integer
Property Suffix As Integer
End Class
ReadOnly EVEN_ROOT As Integer = 0
ReadOnly ODD_ROOT As Integer = 1
Function Eertree(s As String) As List(Of Node)
Dim tree As New List(Of Node) From {
New Node(0, New Dictionary(Of Char, Integer), ODD_ROOT),
New Node(-1, New Dictionary(Of Char, Integer), ODD_ROOT)
}
Dim suffix = ODD_ROOT
Dim n As Integer
Dim k As Integer
For i = 1 To s.Length
Dim c = s(i - 1)
n = suffix
While True
k = tree(n).Length
Dim b = i - k - 2
If b >= 0 AndAlso s(b) = c Then
Exit While
End If
n = tree(n).Suffix
End While
If tree(n).Edges.ContainsKey(c) Then
suffix = tree(n).Edges(c)
Continue For
End If
suffix = tree.Count
tree.Add(New Node(k + 2))
tree(n).Edges(c) = suffix
If tree(suffix).Length = 1 Then
tree(suffix).Suffix = 0
Continue For
End If
While True
n = tree(n).Suffix
Dim b = i - tree(n).Length - 2
If b >= 0 AndAlso s(b) = c Then
Exit While
End If
End While
Dim a = tree(n)
Dim d = a.Edges(c)
Dim e = tree(suffix)
e.Suffix = d
Next
Return tree
End Function
Function SubPalindromes(tree As List(Of Node)) As List(Of String)
Dim s As New List(Of String)
Dim children As Action(Of Integer, String) = Sub(n As Integer, p As String)
For Each c In tree(n).Edges.Keys
Dim m = tree(n).Edges(c)
Dim p1 = c + p + c
s.Add(p1)
children(m, p1)
Next
End Sub
children(0, "")
For Each c In tree(1).Edges.Keys
Dim m = tree(1).Edges(c)
Dim ct = c.ToString()
s.Add(ct)
children(m, ct)
Next
Return s
End Function
Sub Main()
Dim tree = Eertree("eertree")
Dim result = SubPalindromes(tree)
Dim listStr = String.Join(", ", result)
Console.WriteLine("[{0}]", listStr)
End Sub
End Module |
http://rosettacode.org/wiki/Ethiopian_multiplication | Ethiopian multiplication | Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving.
Method:
Take two numbers to be multiplied and write them down at the top of two columns.
In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last in the same column, until you write a value of 1.
In the right-hand column repeatedly double the last number and write the result below. stop when you add a result in the same row as where the left hand column shows 1.
Examine the table produced and discard any row where the value in the left column is even.
Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together
For example: 17 × 34
17 34
Halving the first column:
17 34
8
4
2
1
Doubling the second column:
17 34
8 68
4 136
2 272
1 544
Strike-out rows whose first cell is even:
17 34
8 68
4 136
2 272
1 544
Sum the remaining numbers in the right-hand column:
17 34
8 --
4 ---
2 ---
1 544
====
578
So 17 multiplied by 34, by the Ethiopian method is 578.
Task
The task is to define three named functions/methods/procedures/subroutines:
one to halve an integer,
one to double an integer, and
one to state if an integer is even.
Use these functions to create a function that does Ethiopian multiplication.
References
Ethiopian multiplication explained (BBC Video clip)
A Night Of Numbers - Go Forth And Multiply (Video)
Russian Peasant Multiplication
Programming Praxis: Russian Peasant Multiplication
| #Relation | Relation |
function half(x)
set result = floor(x/2)
end function
function double(x)
set result = 2*x
end function
function even(x)
set result = (x/2 > floor(x/2))
end function
program ethiopian_mul(a,b)
relation first, second
while a >= 1
insert a, b
set a = half(a)
set b = double(b)
end while
extend third = even(first) * second
project third sum
end program
run ethiopian_mul(17,34)
print
|
http://rosettacode.org/wiki/Elementary_cellular_automaton | Elementary cellular automaton | An elementary cellular automaton is a one-dimensional cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three bits.
The rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101.
Task
Create a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice.
The space state should wrap: this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally.
This task is basically a generalization of one-dimensional cellular automata.
See also
Cellular automata (natureofcode.com)
| #J | J | next=: ((8$2) #: [) {~ 2 #. 1 - [: |: |.~"1 0&_1 0 1@]
' *'{~90 next^:(i.9) 0 0 0 0 0 0 1 0 0 0 0 0
*
* *
* *
* * * *
* *
* * * *
* *
* * * *
* * |
http://rosettacode.org/wiki/Elementary_cellular_automaton | Elementary cellular automaton | An elementary cellular automaton is a one-dimensional cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three bits.
The rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101.
Task
Create a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice.
The space state should wrap: this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally.
This task is basically a generalization of one-dimensional cellular automata.
See also
Cellular automata (natureofcode.com)
| #Java | Java | import java.awt.*;
import java.awt.event.ActionEvent;
import javax.swing.*;
import javax.swing.Timer;
public class WolframCA extends JPanel {
final int[] ruleSet = {30, 45, 50, 57, 62, 70, 73, 75, 86, 89, 90, 99,
101, 105, 109, 110, 124, 129, 133, 135, 137, 139, 141, 164,170, 232};
byte[][] cells;
int rule = 0;
public WolframCA() {
Dimension dim = new Dimension(900, 450);
setPreferredSize(dim);
setBackground(Color.white);
setFont(new Font("SansSerif", Font.BOLD, 28));
cells = new byte[dim.height][dim.width];
cells[0][dim.width / 2] = 1;
new Timer(5000, (ActionEvent e) -> {
rule++;
if (rule == ruleSet.length)
rule = 0;
repaint();
}).start();
}
private byte rules(int lhs, int mid, int rhs) {
int idx = (lhs << 2 | mid << 1 | rhs);
return (byte) (ruleSet[rule] >> idx & 1);
}
void drawCa(Graphics2D g) {
g.setColor(Color.black);
for (int r = 0; r < cells.length - 1; r++) {
for (int c = 1; c < cells[r].length - 1; c++) {
byte lhs = cells[r][c - 1];
byte mid = cells[r][c];
byte rhs = cells[r][c + 1];
cells[r + 1][c] = rules(lhs, mid, rhs); // next generation
if (cells[r][c] == 1) {
g.fillRect(c, r, 1, 1);
}
}
}
}
void drawLegend(Graphics2D g) {
String s = String.valueOf(ruleSet[rule]);
int sw = g.getFontMetrics().stringWidth(s);
g.setColor(Color.white);
g.fillRect(16, 5, 55, 30);
g.setColor(Color.darkGray);
g.drawString(s, 16 + (55 - sw) / 2, 30);
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
drawCa(g);
drawLegend(g);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Wolfram CA");
f.setResizable(false);
f.add(new WolframCA(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
} |
http://rosettacode.org/wiki/Factorial | Factorial | Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a number.
Solutions can be iterative or recursive.
Support for trapping negative n errors is optional.
Related task
Primorial numbers
| #TUSCRIPT | TUSCRIPT | $$ MODE TUSCRIPT
LOOP num=-1,12
IF (num==0,1) THEN
f=1
ELSEIF (num<0) THEN
PRINT num," is negative number"
CYCLE
ELSE
f=VALUE(num)
LOOP n=#num,2,-1
f=f*(n-1)
ENDLOOP
ENDIF
formatnum=CENTER(num,+2," ")
PRINT "factorial of ",formatnum," = ",f
ENDLOOP |
http://rosettacode.org/wiki/Even_or_odd | Even or odd | Task
Test whether an integer is even or odd.
There is more than one way to solve this task:
Use the even and odd predicates, if the language provides them.
Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd.
Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd.
Use modular congruences:
i ≡ 0 (mod 2) iff i is even.
i ≡ 1 (mod 2) iff i is odd.
| #xEec | xEec |
>100 p i# jz-1 o# t h#1 ms jz2003 p >0110 h#2 r ms t h#1 ms p
jz1002 h? jz2003 p jn0110 h#10 o$ p jn100 >2003 p p h#0 h#10
h$d h$d h$o h#32 h$s h$i h#32 jn0000 >1002 p p h#0 h#10
h$n h$e h$v h$e h#32 h$s h$i h#32 >0000 o$ p jn0000 jz100
|
http://rosettacode.org/wiki/Even_or_odd | Even or odd | Task
Test whether an integer is even or odd.
There is more than one way to solve this task:
Use the even and odd predicates, if the language provides them.
Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd.
Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd.
Use modular congruences:
i ≡ 0 (mod 2) iff i is even.
i ≡ 1 (mod 2) iff i is odd.
| #XLISP | XLISP | (defun my-evenp (x)
(= (logand x 1) 0) )
(defun my-oddp (x)
(/= (logand x 1) 0) ) |
http://rosettacode.org/wiki/Echo_server | Echo server | Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary to support connections from localhost (127.0.0.1 or perhaps ::1). Logging of connection information to standard output is recommended.
The implementation must be able to handle simultaneous connections from multiple clients. A multi-threaded or multi-process solution may be used. Each connection must be able to echo more than a single line.
The implementation must not stop responding to other clients if one client sends a partial line or stops reading responses.
| #JavaScript | JavaScript | const net = require('net');
function handleClient(conn) {
console.log('Connection from ' + conn.remoteAddress + ' on port ' + conn.remotePort);
conn.setEncoding('utf-8');
let buffer = '';
function handleData(data) {
for (let i = 0; i < data.length; i++) {
const char = data.charAt(i);
buffer += char;
if (char === '\n') {
conn.write(buffer);
buffer = '';
}
}
}
conn.on('data', handleData);
}
net.createServer(handleClient).listen(12321, 'localhost'); |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #True_BASIC | True BASIC | END |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #TUSCRIPT | TUSCRIPT | $$ MODE TUSCRIPT |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #UNIX_Shell | UNIX Shell | #!/bin/sh |
http://rosettacode.org/wiki/Eban_numbers | Eban numbers |
Definition
An eban number is a number that has no letter e in it when the number is spelled in English.
Or more literally, spelled numbers that contain the letter e are banned.
The American version of spelling numbers will be used here (as opposed to the British).
2,000,000,000 is two billion, not two milliard.
Only numbers less than one sextillion (1021) will be considered in/for this task.
This will allow optimizations to be used.
Task
show all eban numbers ≤ 1,000 (in a horizontal format), and a count
show all eban numbers between 1,000 and 4,000 (inclusive), and a count
show a count of all eban numbers up and including 10,000
show a count of all eban numbers up and including 100,000
show a count of all eban numbers up and including 1,000,000
show a count of all eban numbers up and including 10,000,000
show all output here.
See also
The MathWorld entry: eban numbers.
The OEIS entry: A6933, eban numbers.
| #C.23 | C# | using System;
namespace EbanNumbers {
struct Interval {
public int start, end;
public bool print;
public Interval(int start, int end, bool print) {
this.start = start;
this.end = end;
this.print = print;
}
}
class Program {
static void Main() {
Interval[] intervals = {
new Interval(2, 1_000, true),
new Interval(1_000, 4_000, true),
new Interval(2, 10_000, false),
new Interval(2, 100_000, false),
new Interval(2, 1_000_000, false),
new Interval(2, 10_000_000, false),
new Interval(2, 100_000_000, false),
new Interval(2, 1_000_000_000, false),
};
foreach (var intv in intervals) {
if (intv.start == 2) {
Console.WriteLine("eban numbers up to and including {0}:", intv.end);
} else {
Console.WriteLine("eban numbers between {0} and {1} (inclusive):", intv.start, intv.end);
}
int count = 0;
for (int i = intv.start; i <= intv.end; i += 2) {
int b = i / 1_000_000_000;
int r = i % 1_000_000_000;
int m = r / 1_000_000;
r = i % 1_000_000;
int t = r / 1_000;
r %= 1_000;
if (m >= 30 && m <= 66) m %= 10;
if (t >= 30 && t <= 66) t %= 10;
if (r >= 30 && r <= 66) r %= 10;
if (b == 0 || b == 2 || b == 4 || b == 6) {
if (m == 0 || m == 2 || m == 4 || m == 6) {
if (t == 0 || t == 2 || t == 4 || t == 6) {
if (r == 0 || r == 2 || r == 4 || r == 6) {
if (intv.print) Console.Write("{0} ", i);
count++;
}
}
}
}
}
if (intv.print) {
Console.WriteLine();
}
Console.WriteLine("count = {0}\n", count);
}
}
}
} |
http://rosettacode.org/wiki/Duffinian_numbers | Duffinian numbers | A Duffinian number is a composite number k that is relatively prime to its sigma sum σ.
The sigma sum of k is the sum of the divisors of k.
E.G.
161 is a Duffinian number.
It is composite. (7 × 23)
The sigma sum 192 (1 + 7 + 23 + 161) is relatively prime to 161.
Duffinian numbers are very common.
It is not uncommon for two consecutive integers to be Duffinian (a Duffinian twin) (8, 9), (35, 36), (49, 50), etc.
Less common are Duffinian triplets; three consecutive Duffinian numbers. (63, 64, 65), (323, 324, 325), etc.
Much, much less common are Duffinian quadruplets and quintuplets. The first Duffinian quintuplet is (202605639573839041, 202605639573839042, 202605639573839043, 202605639573839044, 202605639573839045).
It is not possible to have six consecutive Duffinian numbers
Task
Find and show the first 50 Duffinian numbers.
Find and show at least the first 15 Duffinian triplets.
See also
Numbers Aplenty - Duffinian numbers
OEIS:A003624 - Duffinian numbers: composite numbers k relatively prime to sigma(k)
| #Phix | Phix | with javascript_semantics
sequence duffinian = {false}
integer n = 2, count = 0, triplet = 0, triple_count = 0
while triple_count<50 do
bool bDuff = not is_prime(n) and gcd(n,sum(factors(n,1)))=1
duffinian &= bDuff
if bDuff then
count += 1
if count=50 then
sequence s50 = apply(true,sprintf,{{"%3d"},find_all(true,duffinian)})
printf(1,"First 50 Duffinian numbers:\n%s\n",join_by(s50,1,25," "))
end if
triplet += 1
triple_count += (triplet>=3)
else
triplet = 0
end if
n += 1
end while
sequence s = apply(true,sq_add,{match_all({true,true,true},duffinian),{{0,1,2}}}),
p = apply(true,pad_tail,{apply(true,sprintf,{{"[%d,%d,%d]"},s}),24})
printf(1,"First 50 Duffinian triplets:\n%s\n",{join_by(p,1,4," ")})
|
http://rosettacode.org/wiki/Duffinian_numbers | Duffinian numbers | A Duffinian number is a composite number k that is relatively prime to its sigma sum σ.
The sigma sum of k is the sum of the divisors of k.
E.G.
161 is a Duffinian number.
It is composite. (7 × 23)
The sigma sum 192 (1 + 7 + 23 + 161) is relatively prime to 161.
Duffinian numbers are very common.
It is not uncommon for two consecutive integers to be Duffinian (a Duffinian twin) (8, 9), (35, 36), (49, 50), etc.
Less common are Duffinian triplets; three consecutive Duffinian numbers. (63, 64, 65), (323, 324, 325), etc.
Much, much less common are Duffinian quadruplets and quintuplets. The first Duffinian quintuplet is (202605639573839041, 202605639573839042, 202605639573839043, 202605639573839044, 202605639573839045).
It is not possible to have six consecutive Duffinian numbers
Task
Find and show the first 50 Duffinian numbers.
Find and show at least the first 15 Duffinian triplets.
See also
Numbers Aplenty - Duffinian numbers
OEIS:A003624 - Duffinian numbers: composite numbers k relatively prime to sigma(k)
| #Raku | Raku | use Prime::Factor;
my @duffinians = lazy (3..*).hyper.grep: { !.is-prime && $_ gcd .&divisors.sum == 1 };
put "First 50 Duffinian numbers:\n" ~
@duffinians[^50].batch(10)».fmt("%3d").join: "\n";
put "\nFirst 40 Duffinian triplets:\n" ~
((^∞).grep: -> $n { (@duffinians[$n] + 1 == @duffinians[$n + 1]) && (@duffinians[$n] + 2 == @duffinians[$n + 2]) })[^40]\
.map( { "({@duffinians[$_ .. $_+2].join: ', '})" } ).batch(4)».fmt("%-24s").join: "\n"; |
http://rosettacode.org/wiki/Element-wise_operations | Element-wise operations | This task is similar to:
Matrix multiplication
Matrix transposition
Task
Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks.
Implement:
addition
subtraction
multiplication
division
exponentiation
Extend the task if necessary to include additional basic operations, which should not require their own specialised task.
| #Fortran | Fortran |
program element_operations
implicit none
real(kind=4), dimension(3,3) :: a,b
integer :: i
a=reshape([(i,i=1,9)],shape(a))
print*,'addition'
b=a+a
call print_arr(b)
print*,'multiplication'
b=a*a
call print_arr(b)
print*,'division'
b=a/b
call print_arr(b)
print*,'exponentiation'
b=a**a
call print_arr(b)
print*,'trignometric'
b=cos(a)
call print_arr(b)
print*,'mod'
b=mod(int(a),3)
call print_arr(b)
print*,'element selection'
b=0
where(a>3) b=1
call print_arr(b)
print*,'elemental functions can be applied to single values:'
print*,square(3.0)
print*,'or element wise to arrays:'
b=square(a)
call print_arr(b)
contains
elemental real function square(a)
real, intent(in) :: a
square=a*a
end function square
subroutine print_arr(arr)
real, intent(in) :: arr(:,:)
integer :: i
do i=1,size(arr,dim=2)
print*,arr(:,i)
end do
end subroutine print_arr
end program element_operations
|
http://rosettacode.org/wiki/Dynamic_variable_names | Dynamic variable names | Task
Create a variable with a user-defined name.
The variable name should not be written in the program text, but should be taken from the user dynamically.
See also
Eval in environment is a similar task.
| #D.C3.A9j.C3.A0_Vu | Déjà Vu | local :var-name !run-blob !compile-string dup concat( ":" !prompt "Enter a variable name: " )
local var-name 42
#Assuming the user types THISISWEIRD, otherwise this'll error
!. THISISWEIRD |
http://rosettacode.org/wiki/Dynamic_variable_names | Dynamic variable names | Task
Create a variable with a user-defined name.
The variable name should not be written in the program text, but should be taken from the user dynamically.
See also
Eval in environment is a similar task.
| #E | E | def makeNounExpr := <elang:evm.makeNounExpr>
def dynVarName(name) {
def variable := makeNounExpr(null, name, null)
return e`{
def a := 1
def b := 2
def c := 3
{
def $variable := "BOO!"
[a, b, c]
}
}`.eval(safeScope)
}
? dynVarName("foo")
# value: [1, 2, 3]
? dynVarName("b")
# value: [1, "BOO!", 3]
? dynVarName("c")
# value: [1, 2, "BOO!"] |
http://rosettacode.org/wiki/Draw_a_pixel | Draw a pixel | Task
Create a window and draw a pixel in it, subject to the following:
the window is 320 x 240
the color of the pixel must be red (255,0,0)
the position of the pixel is x = 100, y = 100 | #Action.21 | Action! | PROC Main()
BYTE
CH=$02FC, ;Internal hardware value for last key pressed
PALNTSC=$D014 ;To check if PAL or NTSC system is used
Graphics(8+16) ;Graphics 320x192 with 2 luminances
IF PALNTSC=15 THEN
SetColor(1,4,6) ;Red color for NTSC
SetColor(2,4,15)
ELSE
SetColor(1,2,6) ;Red color for PAL
SetColor(2,2,15)
FI
Color=1
Plot(100,100)
DO UNTIL CH#$FF OD
CH=$FF
RETURN |
http://rosettacode.org/wiki/Egyptian_division | Egyptian division | Egyptian division is a method of dividing integers using addition and
doubling that is similar to the algorithm of Ethiopian multiplication
Algorithm:
Given two numbers where the dividend is to be divided by the divisor:
Start the construction of a table of two columns: powers_of_2, and doublings; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column.
Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order.
Continue with successive i’th rows of 2^i and 2^i * divisor.
Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend.
We now assemble two separate sums that both start as zero, called here answer and accumulator
Consider each row of the table, in the reverse order of its construction.
If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer.
When the first row has been considered as above, then the integer division of dividend by divisor is given by answer.
(And the remainder is given by the absolute value of accumulator - dividend).
Example: 580 / 34
Table creation:
powers_of_2
doublings
1
34
2
68
4
136
8
272
16
544
Initialization of sums:
powers_of_2
doublings
answer
accumulator
1
34
2
68
4
136
8
272
16
544
0
0
Considering table rows, bottom-up:
When a row is considered it is shown crossed out if it is not accumulated, or bold if the row causes summations.
powers_of_2
doublings
answer
accumulator
1
34
2
68
4
136
8
272
16
544
16
544
powers_of_2
doublings
answer
accumulator
1
34
2
68
4
136
8
272
16
544
16
544
powers_of_2
doublings
answer
accumulator
1
34
2
68
4
136
16
544
8
272
16
544
powers_of_2
doublings
answer
accumulator
1
34
2
68
16
544
4
136
8
272
16
544
powers_of_2
doublings
answer
accumulator
1
34
17
578
2
68
4
136
8
272
16
544
Answer
So 580 divided by 34 using the Egyptian method is 17 remainder (578 - 580) or 2.
Task
The task is to create a function that does Egyptian division. The function should
closely follow the description above in using a list/array of powers of two, and
another of doublings.
Functions should be clear interpretations of the algorithm.
Use the function to divide 580 by 34 and show the answer here, on this page.
Related tasks
Egyptian fractions
References
Egyptian Number System
| #Erlang | Erlang | -module(egypt).
-export([ediv/2]).
ediv(A, B) ->
{Twos, Ds} = genpowers(A, [1], [B]),
{Quot, C} = accumulate(A, Twos, Ds),
{Quot, abs(C - A)}.
genpowers(A, [_|Ts], [D|Ds]) when D > A -> {Ts, Ds};
genpowers(A, [T|_] = Twos, [D|_] = Ds) -> genpowers(A, [2*T|Twos], [D*2|Ds]).
accumulate(N, Twos, Ds) -> accumulate(N, Twos, Ds, 0, 0).
accumulate(_, [], [], Q, C) -> {Q, C};
accumulate(N, [T|Ts], [D|Ds], Q, C) when (C + D) =< N -> accumulate(N, Ts, Ds, Q+T, C+D);
accumulate(N, [_|Ts], [_|Ds], Q, C) -> accumulate(N, Ts, Ds, Q, C).
|
http://rosettacode.org/wiki/Egyptian_fractions | Egyptian fractions | An Egyptian fraction is the sum of distinct unit fractions such as:
1
2
+
1
3
+
1
16
(
=
43
48
)
{\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})}
Each fraction in the expression has a numerator equal to 1 (unity) and a denominator that is a positive integer, and all the denominators are distinct (i.e., no repetitions).
Fibonacci's Greedy algorithm for Egyptian fractions expands the fraction
x
y
{\displaystyle {\tfrac {x}{y}}}
to be represented by repeatedly performing the replacement
x
y
=
1
⌈
y
/
x
⌉
+
(
−
y
)
mod
x
y
⌈
y
/
x
⌉
{\displaystyle {\frac {x}{y}}={\frac {1}{\lceil y/x\rceil }}+{\frac {(-y)\!\!\!\!\mod x}{y\lceil y/x\rceil }}}
(simplifying the 2nd term in this replacement as necessary, and where
⌈
x
⌉
{\displaystyle \lceil x\rceil }
is the ceiling function).
For this task, Proper and improper fractions must be able to be expressed.
Proper fractions are of the form
a
b
{\displaystyle {\tfrac {a}{b}}}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are positive integers, such that
a
<
b
{\displaystyle a<b}
, and
improper fractions are of the form
a
b
{\displaystyle {\tfrac {a}{b}}}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are positive integers, such that a ≥ b.
(See the REXX programming example to view one method of expressing the whole number part of an improper fraction.)
For improper fractions, the integer part of any improper fraction should be first isolated and shown preceding the Egyptian unit fractions, and be surrounded by square brackets [n].
Task requirements
show the Egyptian fractions for:
43
48
{\displaystyle {\tfrac {43}{48}}}
and
5
121
{\displaystyle {\tfrac {5}{121}}}
and
2014
59
{\displaystyle {\tfrac {2014}{59}}}
for all proper fractions,
a
b
{\displaystyle {\tfrac {a}{b}}}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are positive one-or two-digit (decimal) integers, find and show an Egyptian fraction that has:
the largest number of terms,
the largest denominator.
for all one-, two-, and three-digit integers, find and show (as above). {extra credit}
Also see
Wolfram MathWorld™ entry: Egyptian fraction
| #Frink | Frink |
frac[p, q] :=
{
a = makeArray[[0]]
if p > q
{
a.push[floor[p / q]]
p = p mod q
}
while p > 1
{
d = ceil[q / p]
a.push[1/d]
[p, q] = [-q mod p, d q]
}
if p == 1
a.push[1/q]
a
}
showApproximations[false]
egypt[p, q] := join[" + ", frac[p, q]]
rosetta[] :=
{
lMax = 0
longest = 0
dMax = 0
biggest = 0
for n = 1 to 99
for d = n+1 to 99
{
egypt = frac[n, d]
if length[egypt] > lMax
{
lMax = length[egypt]
longest = n/d
}
d2 = denominator[last[egypt, 1]@0]
if d2 > dMax
{
dMax = d2
biggest = n/d
}
}
println["The fraction with the largest number of terms is $longest"]
println["The fraction with the largest denominator is $biggest"]
}
|
http://rosettacode.org/wiki/Eertree | Eertree | An eertree is a data structure designed for efficient processing of certain palindrome tasks, for instance counting the number of sub-palindromes in an input string.
The data structure has commonalities to both tries and suffix trees.
See links below.
Task
Construct an eertree for the string "eertree", then output all sub-palindromes by traversing the tree.
See also
Wikipedia entry: trie.
Wikipedia entry: suffix tree
Cornell University Library, Computer Science, Data Structures and Algorithms ───► EERTREE: An Efficient Data Structure for Processing Palindromes in Strings.
| #Wren | Wren | class Node {
construct new() {
_edges = {} // edges (or forward links)
_link = null // suffix link (backward links)
_len = 0 // the length of the node
}
edges { _edges }
link { _link }
link=(l) { _link = l }
len { _len }
len=(l) { _len = l }
}
class Eertree {
construct new(str) {
_nodes = []
_rto = Node.new() // odd length root node, or node -1
_rte = Node.new() // even length root node, or node 0
_s = "0" // accumulated input string, T = S[1..i]
_maxSufT = _rte // maximum suffix of tree T
// Initialize and build the tree
_rte.link = _rto
_rto.link = _rte
_rto.len = -1
_rte.len = 0
for (ch in str) add_(ch)
}
nodes { _nodes }
getMaxSuffixPal_(startNode, a) {
// We traverse the suffix-palindromes of T in the order of decreasing length.
// For each palindrome we read its length k and compare T[i-k] against a
// until we get an equality or arrive at the -1 node.
var u = startNode
var i = _s.count
var k = u.len
while (u != _rto && _s[i - k - 1] != a) {
if (u == u.link) Fiber.abort("Infinite loop detected")
u = u.link
k = u.len
}
return u
}
add_(a) {
// We need to find the maximum suffix-palindrome P of Ta
// Start by finding maximum suffix-palindrome Q of T.
// To do this, we traverse the suffix-palindromes of T
// in the order of decreasing length, starting with maxSuf(T)
var q = getMaxSuffixPal_(_maxSufT, a)
// We check Q to see whether it has an outgoing edge labeled by a.
var createANewNode = !q.edges.keys.contains(a)
if (createANewNode) {
// We create the node P of length Q + 2
var p = Node.new()
_nodes.add(p)
p.len = q.len + 2
if (p.len == 1) {
// if P = a, create the suffix link (P, 0)
p.link = _rte
} else {
// It remains to create the suffix link from P if |P|>1. Just
// continue traversing suffix-palindromes of T starting with the
// the suffix link of Q.
p.link = getMaxSuffixPal_(q.link, a).edges[a]
}
// create the edge (Q, P)
q.edges[a] = p
}
// P becomes the new maxSufT
_maxSufT = q.edges[a]
// Store accumulated input string
_s = _s + a
return createANewNode
}
getSubPalindromes() {
// Traverse tree to find sub-palindromes
var result = []
// Odd length words
getSubPalindromes_(_rto, [_rto], "", result)
// Even length words
getSubPalindromes_(_rte, [_rte], "", result)
return result
}
getSubPalindromes_(nd, nodesToHere, charsToHere, result) {
// Each node represents a palindrome, which can be reconstructed
// by the path from the root node to each non-root node.
// Traverse all edges, since they represent other palindromes
for (lnkName in nd.edges.keys) {
var nd2 = nd.edges[lnkName]
getSubPalindromes_(nd2, nodesToHere + [nd2], charsToHere + lnkName, result)
}
// Reconstruct based on charsToHere characters.
if (nd != _rto && nd != _rte) { // Don't print for root nodes
var assembled = charsToHere[-1..0] +
((nodesToHere[0] == _rte) ? charsToHere : charsToHere[1..-1])
result.add(assembled)
}
}
}
var str = "eertree"
System.print("Processing string '%(str)'")
var eertree = Eertree.new(str)
System.print("Number of sub-palindromes: %(eertree.nodes.count)")
var result = eertree.getSubPalindromes()
System.print("Sub-palindromes: %(result)") |
http://rosettacode.org/wiki/Ethiopian_multiplication | Ethiopian multiplication | Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving.
Method:
Take two numbers to be multiplied and write them down at the top of two columns.
In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last in the same column, until you write a value of 1.
In the right-hand column repeatedly double the last number and write the result below. stop when you add a result in the same row as where the left hand column shows 1.
Examine the table produced and discard any row where the value in the left column is even.
Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together
For example: 17 × 34
17 34
Halving the first column:
17 34
8
4
2
1
Doubling the second column:
17 34
8 68
4 136
2 272
1 544
Strike-out rows whose first cell is even:
17 34
8 68
4 136
2 272
1 544
Sum the remaining numbers in the right-hand column:
17 34
8 --
4 ---
2 ---
1 544
====
578
So 17 multiplied by 34, by the Ethiopian method is 578.
Task
The task is to define three named functions/methods/procedures/subroutines:
one to halve an integer,
one to double an integer, and
one to state if an integer is even.
Use these functions to create a function that does Ethiopian multiplication.
References
Ethiopian multiplication explained (BBC Video clip)
A Night Of Numbers - Go Forth And Multiply (Video)
Russian Peasant Multiplication
Programming Praxis: Russian Peasant Multiplication
| #REXX | REXX | /*REXX program multiplies two integers by the Ethiopian (or Russian peasant) method. */
numeric digits 3000 /*handle some gihugeic integers. */
parse arg a b . /*get two numbers from the command line*/
say 'a=' a /*display a formatted value of A. */
say 'b=' b /* " " " " " B. */
say 'product=' eMult(a, b) /*invoke eMult & multiple two integers.*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
eMult: procedure; parse arg x,y; s=sign(x) /*obtain the two arguments; sign for X.*/
$=0 /*product of the two integers (so far).*/
do while x\==0 /*keep processing while X not zero.*/
if \isEven(x) then $=$+y /*if odd, then add Y to product. */
x= halve(x) /*invoke the HALVE function. */
y=double(y) /* " " DOUBLE " */
end /*while*/ /* [↑] Ethiopian multiplication method*/
return $*s/1 /*maintain the correct sign for product*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
double: return arg(1) * 2 /* * is REXX's multiplication. */
halve: return arg(1) % 2 /* % " " integer division. */
isEven: return arg(1) // 2 == 0 /* // " " division remainder.*/ |
http://rosettacode.org/wiki/Elementary_cellular_automaton | Elementary cellular automaton | An elementary cellular automaton is a one-dimensional cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three bits.
The rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101.
Task
Create a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice.
The space state should wrap: this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally.
This task is basically a generalization of one-dimensional cellular automata.
See also
Cellular automata (natureofcode.com)
| #JavaScript | JavaScript | const alive = '#';
const dead = '.';
// ------------------------------------------------------------[ Bit banging ]--
const setBitAt = (val, idx) => BigInt(val) | (1n << BigInt(idx));
const clearBitAt = (val, idx) => BigInt(val) & ~(1n << BigInt(idx));
const getBitAt = val => idx => (BigInt(val) >> BigInt(idx)) & 1n;
const hasBitAt = val => idx => ((BigInt(val) >> BigInt(idx)) & 1n) === 1n;
// ----------------------------------------------------------------[ Utility ]--
const makeArr = n => Array(n).fill(0);
const reverse = x => Array.from(x).reduce((p, c) => [c, ...p], []);
const numToLine = width => int => {
const test = hasBitAt(int);
const looper = makeArr(width);
return reverse(looper.map((_, i) => test(i) ? alive : dead)).join('');
}
// -------------------------------------------------------------------[ Main ]--
const displayCA = (rule, width, lines, startIndex) => {
const result = [];
result.push(`Rule:${rule} Width:${width} Gen:${lines}\n`)
const ruleTest = hasBitAt(rule);
const lineLoop = makeArr(lines);
const looper = makeArr(width);
const pLine = numToLine(width);
let nTarget = setBitAt(0n, startIndex);
result.push(pLine(nTarget));
lineLoop.forEach(() => {
const bitTest = getBitAt(nTarget);
looper.forEach((e, i) => {
const l = bitTest(i === 0 ? width - 1 : i - 1);
const m = bitTest(i);
const r = bitTest(i === width - 1 ? 0 : i + 1);
nTarget = ruleTest(
parseInt([l, m, r].join(''), 2))
? setBitAt(nTarget, i)
: clearBitAt(nTarget, i);
});
result.push(pLine(nTarget));
});
return result.join('\n');
}
displayCA(90, 57, 31, 28); |
http://rosettacode.org/wiki/Factorial | Factorial | Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a number.
Solutions can be iterative or recursive.
Support for trapping negative n errors is optional.
Related task
Primorial numbers
| #TXR | TXR | $ txr -p '(n-perm-k 10 10)'
3628800 |
http://rosettacode.org/wiki/Even_or_odd | Even or odd | Task
Test whether an integer is even or odd.
There is more than one way to solve this task:
Use the even and odd predicates, if the language provides them.
Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd.
Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd.
Use modular congruences:
i ≡ 0 (mod 2) iff i is even.
i ≡ 1 (mod 2) iff i is odd.
| #Xojo | Xojo |
For num As Integer = 1 To 5
If num Mod 2 = 0 Then
MsgBox(Str(num) + " is even.")
Else
MsgBox(Str(num) + " is odd.")
End If
Next
|
http://rosettacode.org/wiki/Even_or_odd | Even or odd | Task
Test whether an integer is even or odd.
There is more than one way to solve this task:
Use the even and odd predicates, if the language provides them.
Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd.
Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd.
Use modular congruences:
i ≡ 0 (mod 2) iff i is even.
i ≡ 1 (mod 2) iff i is odd.
| #XPL0 | XPL0 | include c:\cxpl\codes;
int I;
[for I:= -4 to +3 do
[IntOut(0, I);
Text(0, if I&1 then " is odd " else " is even ");
Text(0, if rem(I/2)#0 then "odd" else "even");
CrLf(0);
];
] |
http://rosettacode.org/wiki/Echo_server | Echo server | Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary to support connections from localhost (127.0.0.1 or perhaps ::1). Logging of connection information to standard output is recommended.
The implementation must be able to handle simultaneous connections from multiple clients. A multi-threaded or multi-process solution may be used. Each connection must be able to echo more than a single line.
The implementation must not stop responding to other clients if one client sends a partial line or stops reading responses.
| #Julia | Julia |
using Sockets # for version 1.0
println("Echo server on port 12321")
try
server = listen(12321)
instance = 0
while true
sock = accept(server)
instance += 1
socklabel = "$(getsockname(sock)) number $instance"
@async begin
println("Server connected to socket $socklabel")
write(sock, "Connected to echo server.\r\n")
while isopen(sock)
str = readline(sock)
write(sock,"$str\r\n")
println("Echoed $str to socket $socklabel")
end
println("Closed socket $socklabel")
end
end
catch y
println("Caught exception: $y")
end
|
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Unlambda | Unlambda | i
|
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Ursa | Ursa | |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Vala | Vala | void main() {} |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #VAX_Assembly | VAX Assembly | 0000 0000 1 .entry main,0 ;register save mask
04 0002 2 ret ;return from main procedure
0003 3 .end main ;start address for linker |
http://rosettacode.org/wiki/Eban_numbers | Eban numbers |
Definition
An eban number is a number that has no letter e in it when the number is spelled in English.
Or more literally, spelled numbers that contain the letter e are banned.
The American version of spelling numbers will be used here (as opposed to the British).
2,000,000,000 is two billion, not two milliard.
Only numbers less than one sextillion (1021) will be considered in/for this task.
This will allow optimizations to be used.
Task
show all eban numbers ≤ 1,000 (in a horizontal format), and a count
show all eban numbers between 1,000 and 4,000 (inclusive), and a count
show a count of all eban numbers up and including 10,000
show a count of all eban numbers up and including 100,000
show a count of all eban numbers up and including 1,000,000
show a count of all eban numbers up and including 10,000,000
show all output here.
See also
The MathWorld entry: eban numbers.
The OEIS entry: A6933, eban numbers.
| #C.2B.2B | C++ | #include <iostream>
struct Interval {
int start, end;
bool print;
};
int main() {
Interval intervals[] = {
{2, 1000, true},
{1000, 4000, true},
{2, 10000, false},
{2, 100000, false},
{2, 1000000, false},
{2, 10000000, false},
{2, 100000000, false},
{2, 1000000000, false},
};
for (auto intv : intervals) {
if (intv.start == 2) {
std::cout << "eban numbers up to and including " << intv.end << ":\n";
} else {
std::cout << "eban numbers bwteen " << intv.start << " and " << intv.end << " (inclusive):\n";
}
int count = 0;
for (int i = intv.start; i <= intv.end; i += 2) {
int b = i / 1000000000;
int r = i % 1000000000;
int m = r / 1000000;
r = i % 1000000;
int t = r / 1000;
r %= 1000;
if (m >= 30 && m <= 66) m %= 10;
if (t >= 30 && t <= 66) t %= 10;
if (r >= 30 && r <= 66) r %= 10;
if (b == 0 || b == 2 || b == 4 || b == 6) {
if (m == 0 || m == 2 || m == 4 || m == 6) {
if (t == 0 || t == 2 || t == 4 || t == 6) {
if (r == 0 || r == 2 || r == 4 || r == 6) {
if (intv.print) std::cout << i << ' ';
count++;
}
}
}
}
}
if (intv.print) {
std::cout << '\n';
}
std::cout << "count = " << count << "\n\n";
}
return 0;
} |
http://rosettacode.org/wiki/Duffinian_numbers | Duffinian numbers | A Duffinian number is a composite number k that is relatively prime to its sigma sum σ.
The sigma sum of k is the sum of the divisors of k.
E.G.
161 is a Duffinian number.
It is composite. (7 × 23)
The sigma sum 192 (1 + 7 + 23 + 161) is relatively prime to 161.
Duffinian numbers are very common.
It is not uncommon for two consecutive integers to be Duffinian (a Duffinian twin) (8, 9), (35, 36), (49, 50), etc.
Less common are Duffinian triplets; three consecutive Duffinian numbers. (63, 64, 65), (323, 324, 325), etc.
Much, much less common are Duffinian quadruplets and quintuplets. The first Duffinian quintuplet is (202605639573839041, 202605639573839042, 202605639573839043, 202605639573839044, 202605639573839045).
It is not possible to have six consecutive Duffinian numbers
Task
Find and show the first 50 Duffinian numbers.
Find and show at least the first 15 Duffinian triplets.
See also
Numbers Aplenty - Duffinian numbers
OEIS:A003624 - Duffinian numbers: composite numbers k relatively prime to sigma(k)
| #Sidef | Sidef | func is_duffinian(n) {
n.is_composite && n.is_coprime(n.sigma)
}
say "First 50 Duffinian numbers:"
say 50.by(is_duffinian)
say "\nFirst 15 Duffinian triplets:"
15.by{|n| ^3 -> all {|k| is_duffinian(n+k) } }.each {|n|
printf("(%s, %s, %s)\n", n, n+1, n+2)
} |
http://rosettacode.org/wiki/Duffinian_numbers | Duffinian numbers | A Duffinian number is a composite number k that is relatively prime to its sigma sum σ.
The sigma sum of k is the sum of the divisors of k.
E.G.
161 is a Duffinian number.
It is composite. (7 × 23)
The sigma sum 192 (1 + 7 + 23 + 161) is relatively prime to 161.
Duffinian numbers are very common.
It is not uncommon for two consecutive integers to be Duffinian (a Duffinian twin) (8, 9), (35, 36), (49, 50), etc.
Less common are Duffinian triplets; three consecutive Duffinian numbers. (63, 64, 65), (323, 324, 325), etc.
Much, much less common are Duffinian quadruplets and quintuplets. The first Duffinian quintuplet is (202605639573839041, 202605639573839042, 202605639573839043, 202605639573839044, 202605639573839045).
It is not possible to have six consecutive Duffinian numbers
Task
Find and show the first 50 Duffinian numbers.
Find and show at least the first 15 Duffinian triplets.
See also
Numbers Aplenty - Duffinian numbers
OEIS:A003624 - Duffinian numbers: composite numbers k relatively prime to sigma(k)
| #Wren | Wren | import "./math" for Int, Nums
import "./seq" for Lst
import "./fmt" for Fmt
var limit = 200000 // say
var d = Int.primeSieve(limit-1, false)
d[1] = false
for (i in 2...limit) {
if (!d[i]) continue
if (i % 2 == 0 && !Int.isSquare(i) && !Int.isSquare(i/2)) {
d[i] = false
continue
}
var sigmaSum = Nums.sum(Int.divisors(i))
if (Int.gcd(sigmaSum, i) != 1) d[i] = false
}
var duff = (1...d.count).where { |i| d[i] }.toList
System.print("First 50 Duffinian numbers:")
for (chunk in Lst.chunks(duff[0..49], 10)) Fmt.print("$3d", chunk)
var triplets = []
for (i in 2...limit) {
if (d[i] && d[i-1] && d[i-2]) triplets.add([i-2, i-1, i])
}
System.print("\nFirst 50 Duffinian triplets:")
for (chunk in Lst.chunks(triplets[0..49], 4)) Fmt.print("$-25s", chunk) |
http://rosettacode.org/wiki/Element-wise_operations | Element-wise operations | This task is similar to:
Matrix multiplication
Matrix transposition
Task
Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks.
Implement:
addition
subtraction
multiplication
division
exponentiation
Extend the task if necessary to include additional basic operations, which should not require their own specialised task.
| #FreeBASIC | FreeBASIC | Dim Shared As Double a(1,2) = {{7, 8, 7}, {4, 0, 9}}
Dim Shared As Double b(1,2) = {{4, 5, 1}, {6, 2, 1}}
Dim Shared As Double c(1,2)
Dim Shared As Double fila, columna
Dim Shared As String p
Sub list(a() As Double)
p = "["
For fila = 0 To Ubound(a,1)
p &= "["
For columna = 0 To Ubound(b,2)
p &= Str(a(fila, columna)) + ", "
Next columna
p = Left(p,Len(p)-2) + "]"
Next fila
p &= "]"
Print p;
End Sub
REM Matrix-Matrix:
Sub Mostrarmm(a() As Double, op As String, b() As Double, c() As Double)
list(a()) : Print " "; op; " "; : list(b()) : Print " = "; : list(c()) : Print
End Sub
Sub addmm(a() As Double, b() As Double, c() As Double)
REM adición
For fila = Lbound(a,1) To Ubound(a,1)
For columna = Lbound(b,2) To Ubound(b,2)
c(fila, columna) = a(fila,columna) + b(fila,columna)
Next columna
Next fila
End Sub
Sub resmm(a() As Double, b() As Double, c() As Double)
REM sustracción
For fila = Lbound(a,1) To Ubound(a,1)
For columna = Lbound(b,2) To Ubound(b,2)
c(fila, columna) = a(fila,columna) - b(fila,columna)
Next columna
Next fila
End Sub
Sub mulmm(a() As Double, b() As Double, c() As Double)
REM multiplicación
For fila = Lbound(a,1) To Ubound(a,1)
For columna = Lbound(b,2) To Ubound(b,2)
c(fila, columna) = a(fila,columna) * b(fila,columna)
Next columna
Next fila
End Sub
Sub divmm(a() As Double, b() As Double, c() As Double)
REM división
For fila = Lbound(a,1) To Ubound(a,1)
For columna = Lbound(b,2) To Ubound(b,2)
c(fila, columna) = a(fila,columna) / b(fila,columna)
Next columna
Next fila
End Sub
Sub powmm(a() As Double, b() As Double, c() As Double)
REM exponenciación
For fila = Lbound(a,1) To Ubound(a,1)
For columna = Lbound(b,2) To Ubound(b,2)
c(fila, columna) = a(fila,columna) ^ b(fila,columna)
Next columna
Next fila
End Sub
REM Matrix-Scalar:
Sub Mostrarms(a() As Double, op As String, b As Double, c() As Double)
list(a()) : Print " "; op; " "; Str(b); " = "; : list(c()) : Print
End Sub
Sub addms(a() As Double, b As Double, c() As Double)
REM adición
For fila = Lbound(a,1) To Ubound(a,1)
For columna = Lbound(a,2) To Ubound(a,2)
c(fila, columna) = a(fila,columna) + b
Next columna
Next fila
End Sub
Sub resms(a() As Double, b As Double, c() As Double)
REM sustracción
For fila = Lbound(a,1) To Ubound(a,1)
For columna = Lbound(a,2) To Ubound(a,2)
c(fila, columna) = a(fila,columna) - b
Next columna
Next fila
End Sub
Sub mulms(a() As Double, b As Double, c() As Double)
REM multiplicación
For fila = Lbound(a,1) To Ubound(a,1)
For columna = Lbound(a,2) To Ubound(a,2)
c(fila, columna) = a(fila,columna) * b
Next columna
Next fila
End Sub
Sub divms(a() As Double, b As Double, c() As Double)
REM división
For fila = Lbound(a,1) To Ubound(a,1)
For columna = Lbound(a,2) To Ubound(a,2)
c(fila, columna) = a(fila,columna) / b
Next columna
Next fila
End Sub
Sub powms(a() As Double, b As Double, c() As Double)
REM exponenciación
For fila = Lbound(a,1) To Ubound(a,1)
For columna = Lbound(a,2) To Ubound(a,2)
c(fila, columna) = a(fila,columna) ^ b
Next columna
Next fila
End Sub
REM Matrix-Matrix:
addmm(a(), b(), c()) : Mostrarmm(a(), "+", b(), c())
resmm(a(), b(), c()) : Mostrarmm(a(), "-", b(), c())
mulmm(a(), b(), c()) : Mostrarmm(a(), "*", b(), c())
divmm(a(), b(), c()) : Mostrarmm(a(), "/", b(), c())
powmm(a(), b(), c()) : Mostrarmm(a(), "^", b(), c())
Print
REM Matrix-Scalar:
addms(a(), 3, c()) : Mostrarms(a(), "+", 3, c())
resms(a(), 3, c()) : Mostrarms(a(), "-", 3, c())
mulms(a(), 3, c()) : Mostrarms(a(), "*", 3, c())
divms(a(), 3, c()) : Mostrarms(a(), "/", 3, c())
powms(a(), 3, c()) : Mostrarms(a(), "^", 3, c())
Sleep |
http://rosettacode.org/wiki/Dynamic_variable_names | Dynamic variable names | Task
Create a variable with a user-defined name.
The variable name should not be written in the program text, but should be taken from the user dynamically.
See also
Eval in environment is a similar task.
| #Delphi | Delphi | import system'dynamic;
import extensions;
class TestClass
{
object theVariables;
constructor()
{
theVariables := new DynamicStruct()
}
function()
{
auto prop := new MessageName(console.write:"Enter the variable name:".readLine());
(prop.setPropertyMessage())(theVariables,42);
console.printLine(prop.toPrintable(),"=",(prop.getPropertyMessage())(theVariables)).readChar()
}
}
public program = new TestClass(); |
http://rosettacode.org/wiki/Dynamic_variable_names | Dynamic variable names | Task
Create a variable with a user-defined name.
The variable name should not be written in the program text, but should be taken from the user dynamically.
See also
Eval in environment is a similar task.
| #Elena | Elena | import system'dynamic;
import extensions;
class TestClass
{
object theVariables;
constructor()
{
theVariables := new DynamicStruct()
}
function()
{
auto prop := new MessageName(console.write:"Enter the variable name:".readLine());
(prop.setPropertyMessage())(theVariables,42);
console.printLine(prop.toPrintable(),"=",(prop.getPropertyMessage())(theVariables)).readChar()
}
}
public program = new TestClass(); |
http://rosettacode.org/wiki/Dynamic_variable_names | Dynamic variable names | Task
Create a variable with a user-defined name.
The variable name should not be written in the program text, but should be taken from the user dynamically.
See also
Eval in environment is a similar task.
| #Emacs_Lisp | Emacs Lisp | (set (intern (read-string "Enter variable name: ")) 123) |
http://rosettacode.org/wiki/Draw_a_pixel | Draw a pixel | Task
Create a window and draw a pixel in it, subject to the following:
the window is 320 x 240
the color of the pixel must be red (255,0,0)
the position of the pixel is x = 100, y = 100 | #Ada | Ada | with SDL.Video.Windows.Makers;
with SDL.Video.Renderers.Makers;
with SDL.Events.Events;
procedure Draw_A_Pixel is
Width : constant := 320;
Height : constant := 200;
Window : SDL.Video.Windows.Window;
Renderer : SDL.Video.Renderers.Renderer;
procedure Wait is
use type SDL.Events.Event_Types;
Event : SDL.Events.Events.Events;
begin
loop
while SDL.Events.Events.Poll (Event) loop
if Event.Common.Event_Type = SDL.Events.Quit then
return;
end if;
end loop;
delay 0.100;
end loop;
end Wait;
begin
if not SDL.Initialise (Flags => SDL.Enable_Screen) then
return;
end if;
SDL.Video.Windows.Makers.Create (Win => Window,
Title => "Draw a pixel",
Position => SDL.Natural_Coordinates'(X => 10, Y => 10),
Size => SDL.Positive_Sizes'(Width, Height),
Flags => 0);
SDL.Video.Renderers.Makers.Create (Renderer, Window.Get_Surface);
Renderer.Set_Draw_Colour ((0, 0, 0, 255));
Renderer.Fill (Rectangle => (0, 0, Width, Height));
Renderer.Set_Draw_Colour ((255, 0, 0, 255));
Renderer.Draw (Point => (100, 100));
Window.Update_Surface;
Wait;
Window.Finalize;
SDL.Finalise;
end Draw_A_Pixel; |
http://rosettacode.org/wiki/Egyptian_division | Egyptian division | Egyptian division is a method of dividing integers using addition and
doubling that is similar to the algorithm of Ethiopian multiplication
Algorithm:
Given two numbers where the dividend is to be divided by the divisor:
Start the construction of a table of two columns: powers_of_2, and doublings; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column.
Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order.
Continue with successive i’th rows of 2^i and 2^i * divisor.
Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend.
We now assemble two separate sums that both start as zero, called here answer and accumulator
Consider each row of the table, in the reverse order of its construction.
If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer.
When the first row has been considered as above, then the integer division of dividend by divisor is given by answer.
(And the remainder is given by the absolute value of accumulator - dividend).
Example: 580 / 34
Table creation:
powers_of_2
doublings
1
34
2
68
4
136
8
272
16
544
Initialization of sums:
powers_of_2
doublings
answer
accumulator
1
34
2
68
4
136
8
272
16
544
0
0
Considering table rows, bottom-up:
When a row is considered it is shown crossed out if it is not accumulated, or bold if the row causes summations.
powers_of_2
doublings
answer
accumulator
1
34
2
68
4
136
8
272
16
544
16
544
powers_of_2
doublings
answer
accumulator
1
34
2
68
4
136
8
272
16
544
16
544
powers_of_2
doublings
answer
accumulator
1
34
2
68
4
136
16
544
8
272
16
544
powers_of_2
doublings
answer
accumulator
1
34
2
68
16
544
4
136
8
272
16
544
powers_of_2
doublings
answer
accumulator
1
34
17
578
2
68
4
136
8
272
16
544
Answer
So 580 divided by 34 using the Egyptian method is 17 remainder (578 - 580) or 2.
Task
The task is to create a function that does Egyptian division. The function should
closely follow the description above in using a list/array of powers of two, and
another of doublings.
Functions should be clear interpretations of the algorithm.
Use the function to divide 580 by 34 and show the answer here, on this page.
Related tasks
Egyptian fractions
References
Egyptian Number System
| #F.23 | F# | // A function to perform Egyptian Division: Nigel Galloway August 11th., 2017
let egyptianDivision N G =
let rec fn n g = seq{yield (n,g); yield! fn (n+n) (g+g)}
Seq.foldBack (fun (n,i) (g,e)->if (i<=g) then ((g-i),(e+n)) else (g,e)) (fn 1 G |> Seq.takeWhile(fun (_,g)->g<=N)) (N,0)
|
http://rosettacode.org/wiki/Egyptian_fractions | Egyptian fractions | An Egyptian fraction is the sum of distinct unit fractions such as:
1
2
+
1
3
+
1
16
(
=
43
48
)
{\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})}
Each fraction in the expression has a numerator equal to 1 (unity) and a denominator that is a positive integer, and all the denominators are distinct (i.e., no repetitions).
Fibonacci's Greedy algorithm for Egyptian fractions expands the fraction
x
y
{\displaystyle {\tfrac {x}{y}}}
to be represented by repeatedly performing the replacement
x
y
=
1
⌈
y
/
x
⌉
+
(
−
y
)
mod
x
y
⌈
y
/
x
⌉
{\displaystyle {\frac {x}{y}}={\frac {1}{\lceil y/x\rceil }}+{\frac {(-y)\!\!\!\!\mod x}{y\lceil y/x\rceil }}}
(simplifying the 2nd term in this replacement as necessary, and where
⌈
x
⌉
{\displaystyle \lceil x\rceil }
is the ceiling function).
For this task, Proper and improper fractions must be able to be expressed.
Proper fractions are of the form
a
b
{\displaystyle {\tfrac {a}{b}}}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are positive integers, such that
a
<
b
{\displaystyle a<b}
, and
improper fractions are of the form
a
b
{\displaystyle {\tfrac {a}{b}}}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are positive integers, such that a ≥ b.
(See the REXX programming example to view one method of expressing the whole number part of an improper fraction.)
For improper fractions, the integer part of any improper fraction should be first isolated and shown preceding the Egyptian unit fractions, and be surrounded by square brackets [n].
Task requirements
show the Egyptian fractions for:
43
48
{\displaystyle {\tfrac {43}{48}}}
and
5
121
{\displaystyle {\tfrac {5}{121}}}
and
2014
59
{\displaystyle {\tfrac {2014}{59}}}
for all proper fractions,
a
b
{\displaystyle {\tfrac {a}{b}}}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are positive one-or two-digit (decimal) integers, find and show an Egyptian fraction that has:
the largest number of terms,
the largest denominator.
for all one-, two-, and three-digit integers, find and show (as above). {extra credit}
Also see
Wolfram MathWorld™ entry: Egyptian fraction
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | package main
import (
"fmt"
"math/big"
"strings"
)
var zero = new(big.Int)
var one = big.NewInt(1)
func toEgyptianRecursive(br *big.Rat, fracs []*big.Rat) []*big.Rat {
if br.Num().Cmp(zero) == 0 {
return fracs
}
iquo := new(big.Int)
irem := new(big.Int)
iquo.QuoRem(br.Denom(), br.Num(), irem)
if irem.Cmp(zero) > 0 {
iquo.Add(iquo, one)
}
rquo := new(big.Rat).SetFrac(one, iquo)
fracs = append(fracs, rquo)
num2 := new(big.Int).Neg(br.Denom())
num2.Rem(num2, br.Num())
if num2.Cmp(zero) < 0 {
num2.Add(num2, br.Num())
}
denom2 := new(big.Int)
denom2.Mul(br.Denom(), iquo)
f := new(big.Rat).SetFrac(num2, denom2)
if f.Num().Cmp(one) == 0 {
fracs = append(fracs, f)
return fracs
}
fracs = toEgyptianRecursive(f, fracs)
return fracs
}
func toEgyptian(rat *big.Rat) []*big.Rat {
if rat.Num().Cmp(zero) == 0 {
return []*big.Rat{rat}
}
var fracs []*big.Rat
if rat.Num().CmpAbs(rat.Denom()) >= 0 {
iquo := new(big.Int)
iquo.Quo(rat.Num(), rat.Denom())
rquo := new(big.Rat).SetFrac(iquo, one)
rrem := new(big.Rat)
rrem.Sub(rat, rquo)
fracs = append(fracs, rquo)
fracs = toEgyptianRecursive(rrem, fracs)
} else {
fracs = toEgyptianRecursive(rat, fracs)
}
return fracs
}
func main() {
fracs := []*big.Rat{big.NewRat(43, 48), big.NewRat(5, 121), big.NewRat(2014, 59)}
for _, frac := range fracs {
list := toEgyptian(frac)
if list[0].Denom().Cmp(one) == 0 {
first := fmt.Sprintf("[%v]", list[0].Num())
temp := make([]string, len(list)-1)
for i := 1; i < len(list); i++ {
temp[i-1] = list[i].String()
}
rest := strings.Join(temp, " + ")
fmt.Printf("%v -> %v + %s\n", frac, first, rest)
} else {
temp := make([]string, len(list))
for i := 0; i < len(list); i++ {
temp[i] = list[i].String()
}
all := strings.Join(temp, " + ")
fmt.Printf("%v -> %s\n", frac, all)
}
}
for _, r := range [2]int{98, 998} {
if r == 98 {
fmt.Println("\nFor proper fractions with 1 or 2 digits:")
} else {
fmt.Println("\nFor proper fractions with 1, 2 or 3 digits:")
}
maxSize := 0
var maxSizeFracs []*big.Rat
maxDen := zero
var maxDenFracs []*big.Rat
var sieve = make([][]bool, r+1) // to eliminate duplicates
for i := 0; i <= r; i++ {
sieve[i] = make([]bool, r+2)
}
for i := 1; i <= r; i++ {
for j := i + 1; j <= r+1; j++ {
if sieve[i][j] {
continue
}
f := big.NewRat(int64(i), int64(j))
list := toEgyptian(f)
listSize := len(list)
if listSize > maxSize {
maxSize = listSize
maxSizeFracs = maxSizeFracs[0:0]
maxSizeFracs = append(maxSizeFracs, f)
} else if listSize == maxSize {
maxSizeFracs = append(maxSizeFracs, f)
}
listDen := list[len(list)-1].Denom()
if listDen.Cmp(maxDen) > 0 {
maxDen = listDen
maxDenFracs = maxDenFracs[0:0]
maxDenFracs = append(maxDenFracs, f)
} else if listDen.Cmp(maxDen) == 0 {
maxDenFracs = append(maxDenFracs, f)
}
if i < r/2 {
k := 2
for {
if j*k > r+1 {
break
}
sieve[i*k][j*k] = true
k++
}
}
}
}
fmt.Println(" largest number of items =", maxSize)
fmt.Println(" fraction(s) with this number :", maxSizeFracs)
md := maxDen.String()
fmt.Print(" largest denominator = ", len(md), " digits, ")
fmt.Print(md[0:20], "...", md[len(md)-20:], "\b\n")
fmt.Println(" fraction(s) with this denominator :", maxDenFracs)
}
} |
http://rosettacode.org/wiki/Eertree | Eertree | An eertree is a data structure designed for efficient processing of certain palindrome tasks, for instance counting the number of sub-palindromes in an input string.
The data structure has commonalities to both tries and suffix trees.
See links below.
Task
Construct an eertree for the string "eertree", then output all sub-palindromes by traversing the tree.
See also
Wikipedia entry: trie.
Wikipedia entry: suffix tree
Cornell University Library, Computer Science, Data Structures and Algorithms ───► EERTREE: An Efficient Data Structure for Processing Palindromes in Strings.
| #zkl | zkl | class Node{
fcn init(length){
var edges=Dictionary(), # edges (or forward links). (char:Node)
link=Void, # suffix link (backward links)
sz =length; # node length.
}
}
class Eertree{
fcn init(string=Void){
var nodes=List(),
# two initial root nodes
rto=Node(-1), # odd length root node, or node -1
rte=Node(0); # even length root node, or node 0
rto.link=rte.link=rto; # Initialize empty tree
var S =Data(Void,0), # accumulated input string, T=S[1..i], byte buffer
maxSufT=rte; # maximum suffix of tree T
if(string) string.pump(addChar); // go ahead and build the tree
}
fcn get_max_suffix_pal(startNode,a){
# We traverse the suffix-palindromes of T in the order of decreasing length.
# For each palindrome we read its length k and compare T[i-k] against a
# until we get an equality or arrive at the -1 node.
u,i,k := startNode, S.len(), u.sz;
while(u.id!=rto.id and S.charAt(i - k - 1)!=a){
_assert_(u.id!=u.link.id); # Prevent infinte loop
u,k = u.link,u.sz;
}
return(u);
}
fcn addChar(a){
# We need to find the maximum suffix-palindrome P of Ta
# Start by finding maximum suffix-palindrome Q of T.
# To do this, we traverse the suffix-palindromes of T
# in the order of decreasing length, starting with maxSuf(T)
Q:=get_max_suffix_pal(maxSufT,a);
# We check Q to see whether it has an outgoing edge labeled by a.
createANewNode:=(not Q.edges.holds(a));
if(createANewNode){
P:=Node(Q.sz + 2); nodes.append(P);
if(P.sz==1) P.link=rte; # if P = a, create the suffix link (P,0)
else # It remains to create the suffix link from P if |P|>1. Just
# continue traversing suffix-palindromes of T starting with the suffix
# link of Q.
P.link=get_max_suffix_pal(Q.link,a).edges[a];
Q.edges[a]=P; # create the edge (Q,P)
}
maxSufT=Q.edges[a]; # P becomes the new maxSufT
S.append(a); # Store accumulated input string
return(createANewNode); // in case anyone wants to know a is new edge
}
fcn get_sub_palindromes{
result:=List();
sub_palindromes(rto, T(rto),"", result); # Odd length words
sub_palindromes(rte, T(rte),"", result); # Even length words
result
}
fcn [private] sub_palindromes(nd, nodesToHere, charsToHere, result){
// nodesToHere needs to be read only
# Each node represents a palindrome, which can be reconstructed
# by the path from the root node to each non-root node.
# Traverse all edges, since they represent other palindromes
nd.edges.pump(Void,'wrap([(lnkName,nd2)]){
sub_palindromes(nd2, nodesToHere+nd2, charsToHere+lnkName, result);
});
# Reconstruct based on charsToHere characters.
if(nd.id!=rto.id and nd.id!=rte.id){ # Don't print for root nodes
if(nodesToHere[0].id==rte.id) # Even string
assembled:=charsToHere.reverse() + charsToHere;
else assembled:=charsToHere.reverse() + charsToHere[1,*]; # Odd string
result.append(assembled);
}
}
} |
http://rosettacode.org/wiki/Ethiopian_multiplication | Ethiopian multiplication | Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving.
Method:
Take two numbers to be multiplied and write them down at the top of two columns.
In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last in the same column, until you write a value of 1.
In the right-hand column repeatedly double the last number and write the result below. stop when you add a result in the same row as where the left hand column shows 1.
Examine the table produced and discard any row where the value in the left column is even.
Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together
For example: 17 × 34
17 34
Halving the first column:
17 34
8
4
2
1
Doubling the second column:
17 34
8 68
4 136
2 272
1 544
Strike-out rows whose first cell is even:
17 34
8 68
4 136
2 272
1 544
Sum the remaining numbers in the right-hand column:
17 34
8 --
4 ---
2 ---
1 544
====
578
So 17 multiplied by 34, by the Ethiopian method is 578.
Task
The task is to define three named functions/methods/procedures/subroutines:
one to halve an integer,
one to double an integer, and
one to state if an integer is even.
Use these functions to create a function that does Ethiopian multiplication.
References
Ethiopian multiplication explained (BBC Video clip)
A Night Of Numbers - Go Forth And Multiply (Video)
Russian Peasant Multiplication
Programming Praxis: Russian Peasant Multiplication
| #Ring | Ring |
x = 17
y = 34
p = 0
while x != 0
if not even(x)
p += y
see "" + x + " " + " " + y + nl
else
see "" + x + " ---" + nl ok
x = halve(x)
y = double(y)
end
see " " + " ===" + nl
see " " + p
func double n return (n * 2)
func halve n return floor(n / 2)
func even n return ((n & 1) = 0)
|
http://rosettacode.org/wiki/Elementary_cellular_automaton | Elementary cellular automaton | An elementary cellular automaton is a one-dimensional cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three bits.
The rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101.
Task
Create a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice.
The space state should wrap: this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally.
This task is basically a generalization of one-dimensional cellular automata.
See also
Cellular automata (natureofcode.com)
| #jq | jq | # The ordinal value of the relevant states:
def states:
{"111": 1, "110": 2, "101": 3, "100": 4, "011": 5, "010": 6, "001": 7, "000": 8};
# Compute the next "state"
# input: a state ("111" or "110" ...)
# rule: the rule represented as a string of 0s and 1s
# output: the next state "0" or "1" depending on the rule
def next(rule):
states[.] as $n | rule[($n-1):$n] ;
# The state of cell $n, using 0-based indexing
def triple($n):
if $n == 0 then .[-1:] + .[0:2]
elif $n == (length-1) then .[-2:] + .[0:1]
else .[$n-1:$n+2]
end;
# input: non-negative decimal integer
# output: 0-1 binary string
def binary_digits:
if . == 0 then "0"
else [recurse( if . == 0 then empty else ./2 | floor end ) % 2 | tostring]
| reverse
| .[1:] # remove the leading 0
| join("")
end ; |
http://rosettacode.org/wiki/Elementary_cellular_automaton | Elementary cellular automaton | An elementary cellular automaton is a one-dimensional cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three bits.
The rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101.
Task
Create a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice.
The space state should wrap: this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally.
This task is basically a generalization of one-dimensional cellular automata.
See also
Cellular automata (natureofcode.com)
| #Julia | Julia |
const lines = 10
const start = ".........#........."
const rules = [90, 30, 14]
rule2poss(rule) = [rule & (1 << (i - 1)) != 0 for i in 1:8]
cells2bools(cells) = [cells[i] == '#' for i in 1:length(cells)]
bools2cells(bset) = prod([bset[i] ? "#" : "." for i in 1:length(bset)])
function transform(bset, ruleposs)
newbset = map(x->ruleposs[x],
[bset[i - 1] * 4 + bset[i] * 2 + bset[i + 1] + 1
for i in 2:length(bset)-1])
vcat(newbset[end], newbset, newbset[1])
end
const startset = cells2bools(start)
for rul in rules
println("\nUsing Rule $rul:")
bset = vcat(startset[end], startset, startset[1]) # wrap ends
rp = rule2poss(rul)
for _ in 1:lines
println(bools2cells(bset[2:end-1])) # unwrap ends
bset = transform(bset, rp)
end
end
|
http://rosettacode.org/wiki/Factorial | Factorial | Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a number.
Solutions can be iterative or recursive.
Support for trapping negative n errors is optional.
Related task
Primorial numbers
| #UNIX_Shell | UNIX Shell | factorial() {
set -- "$1" 1
until test "$1" -lt 2; do
set -- "`expr "$1" - 1`" "`expr "$2" \* "$1"`"
done
echo "$2"
} |
http://rosettacode.org/wiki/Even_or_odd | Even or odd | Task
Test whether an integer is even or odd.
There is more than one way to solve this task:
Use the even and odd predicates, if the language provides them.
Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd.
Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd.
Use modular congruences:
i ≡ 0 (mod 2) iff i is even.
i ≡ 1 (mod 2) iff i is odd.
| #Yabasic | Yabasic | for i = -5 to 5
print i, and(i,1), mod(i,2)
next
|
http://rosettacode.org/wiki/Even_or_odd | Even or odd | Task
Test whether an integer is even or odd.
There is more than one way to solve this task:
Use the even and odd predicates, if the language provides them.
Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd.
Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd.
Use modular congruences:
i ≡ 0 (mod 2) iff i is even.
i ≡ 1 (mod 2) iff i is odd.
| #Z80_Assembly | Z80 Assembly | rrca
jp nc,isEven |
http://rosettacode.org/wiki/Echo_server | Echo server | Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary to support connections from localhost (127.0.0.1 or perhaps ::1). Logging of connection information to standard output is recommended.
The implementation must be able to handle simultaneous connections from multiple clients. A multi-threaded or multi-process solution may be used. Each connection must be able to echo more than a single line.
The implementation must not stop responding to other clients if one client sends a partial line or stops reading responses.
| #Kotlin | Kotlin | import java.net.ServerSocket
import java.net.Socket
fun main() {
fun handleClient(conn: Socket) {
conn.use {
val input = conn.inputStream.bufferedReader()
val output = conn.outputStream.bufferedWriter()
input.forEachLine { line ->
output.write(line)
output.newLine()
output.flush()
}
}
}
ServerSocket(12321).use { listener ->
while (true) {
val conn = listener.accept()
Thread { handleClient(conn) }.start()
}
}
}
|
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #VBA | VBA | Sub Demo()
End Sub |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #VBScript | VBScript | ' |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Verbexx | Verbexx | |
http://rosettacode.org/wiki/Eban_numbers | Eban numbers |
Definition
An eban number is a number that has no letter e in it when the number is spelled in English.
Or more literally, spelled numbers that contain the letter e are banned.
The American version of spelling numbers will be used here (as opposed to the British).
2,000,000,000 is two billion, not two milliard.
Only numbers less than one sextillion (1021) will be considered in/for this task.
This will allow optimizations to be used.
Task
show all eban numbers ≤ 1,000 (in a horizontal format), and a count
show all eban numbers between 1,000 and 4,000 (inclusive), and a count
show a count of all eban numbers up and including 10,000
show a count of all eban numbers up and including 100,000
show a count of all eban numbers up and including 1,000,000
show a count of all eban numbers up and including 10,000,000
show all output here.
See also
The MathWorld entry: eban numbers.
The OEIS entry: A6933, eban numbers.
| #CLU | CLU | eban = cluster is numbers
rep = null
% Next valid E-ban number in the range [0..999]
next = proc (n: int) returns (int) signals (no_more)
if n>=66 then signal no_more end
if n<0 then return(0) end
% advance low digit (two four six)
if (n//10=0) then n := (n/10)*10 + 2
elseif (n//10=2) then n := (n/10)*10 + 4
elseif (n//10=4) then n := (n/10)*10 + 6
elseif (n//10=6) then n := (n/10)*10 + 10
end
% this might put us into tEn, twEnty which are invalid
if (n//100/10 = 1) then n := n + 20 % ten + 20 = 30
elseif (n//100/10 = 2) then n := n + 10 % twEnty + 10 = 30
end
return(n)
end next
% Yield all valid E_ban numbers
% (sextillion and upwards aren't handled)
numbers = iter () yields (int)
parts: array[int] := array[int]$[0: 2]
while true do
num: int := 0
for m: int in array[int]$indexes(parts) do
num := num + parts[m] * 1000 ** m
end
yield(num)
for m: int in array[int]$indexes(parts) do
begin
parts[m] := next(parts[m])
break
end except when no_more:
parts[m] := 0
end
end
if array[int]$top(parts) = 0 then
array[int]$addh(parts,2)
end
end
end numbers
end eban
start_up = proc ()
maxmagn = 1000000000000
po: stream := stream$primary_output()
count: int := 0
upto_1k: int := 0
between_1k_4k: int := 0
disp_1k: bool := false
disp_4k: bool := false
nextmagn: int := 10000
for i: int in eban$numbers() do
while i>nextmagn do
stream$putl(po, int$unparse(count)
|| " eban numbers <= "
|| int$unparse(nextmagn))
nextmagn := nextmagn * 10
end
count := count + 1
if i<1000 then upto_1k := upto_1k + 1
elseif i<=4000 then between_1k_4k := between_1k_4k + 1
end
if i>1000 & ~disp_1k then
disp_1k := true
stream$putl(po, "\n" || int$unparse(upto_1k)
|| " eban numbers <= 1000\n")
end
if i<=4000 then stream$putright(po, int$unparse(i), 5) end
if i>4000 & ~disp_4k then
disp_4k := true
stream$putl(po, "\n" || int$unparse(between_1k_4k)
|| " eban numbers 1000 <= x <= 4000\n")
end
if nextmagn>maxmagn then break end
end
end start_up |
http://rosettacode.org/wiki/Eban_numbers | Eban numbers |
Definition
An eban number is a number that has no letter e in it when the number is spelled in English.
Or more literally, spelled numbers that contain the letter e are banned.
The American version of spelling numbers will be used here (as opposed to the British).
2,000,000,000 is two billion, not two milliard.
Only numbers less than one sextillion (1021) will be considered in/for this task.
This will allow optimizations to be used.
Task
show all eban numbers ≤ 1,000 (in a horizontal format), and a count
show all eban numbers between 1,000 and 4,000 (inclusive), and a count
show a count of all eban numbers up and including 10,000
show a count of all eban numbers up and including 100,000
show a count of all eban numbers up and including 1,000,000
show a count of all eban numbers up and including 10,000,000
show all output here.
See also
The MathWorld entry: eban numbers.
The OEIS entry: A6933, eban numbers.
| #D | D | import std.stdio;
struct Interval {
int start, end;
bool print;
}
void main() {
Interval[] intervals = [
{2, 1_000, true},
{1_000, 4_000, true},
{2, 10_000, false},
{2, 100_000, false},
{2, 1_000_000, false},
{2, 10_000_000, false},
{2, 100_000_000, false},
{2, 1_000_000_000, false},
];
foreach (intv; intervals) {
if (intv.start == 2) {
writeln("eban numbers up to an including ", intv.end, ':');
} else {
writeln("eban numbers between ", intv.start ," and ", intv.end, " (inclusive):");
}
int count;
for (int i = intv.start; i <= intv.end; i = i + 2) {
int b = i / 1_000_000_000;
int r = i % 1_000_000_000;
int m = r / 1_000_000;
r = i % 1_000_000;
int t = r / 1_000;
r %= 1_000;
if (m >= 30 && m <= 66) m %= 10;
if (t >= 30 && t <= 66) t %= 10;
if (r >= 30 && r <= 66) r %= 10;
if (b == 0 || b == 2 || b == 4 || b == 6) {
if (m == 0 || m == 2 || m == 4 || m == 6) {
if (t == 0 || t == 2 || t == 4 || t == 6) {
if (r == 0 || r == 2 || r == 4 || r == 6) {
if (intv.print) write(i, ' ');
count++;
}
}
}
}
}
if (intv.print) {
writeln();
}
writeln("count = ", count);
writeln;
}
} |
http://rosettacode.org/wiki/Duffinian_numbers | Duffinian numbers | A Duffinian number is a composite number k that is relatively prime to its sigma sum σ.
The sigma sum of k is the sum of the divisors of k.
E.G.
161 is a Duffinian number.
It is composite. (7 × 23)
The sigma sum 192 (1 + 7 + 23 + 161) is relatively prime to 161.
Duffinian numbers are very common.
It is not uncommon for two consecutive integers to be Duffinian (a Duffinian twin) (8, 9), (35, 36), (49, 50), etc.
Less common are Duffinian triplets; three consecutive Duffinian numbers. (63, 64, 65), (323, 324, 325), etc.
Much, much less common are Duffinian quadruplets and quintuplets. The first Duffinian quintuplet is (202605639573839041, 202605639573839042, 202605639573839043, 202605639573839044, 202605639573839045).
It is not possible to have six consecutive Duffinian numbers
Task
Find and show the first 50 Duffinian numbers.
Find and show at least the first 15 Duffinian triplets.
See also
Numbers Aplenty - Duffinian numbers
OEIS:A003624 - Duffinian numbers: composite numbers k relatively prime to sigma(k)
| #XPL0 | XPL0 | func IsPrime(N); \Return 'true' if N is prime
int N, I;
[if N <= 2 then return N = 2;
if (N&1) = 0 then \even >2\ return false;
for I:= 3 to sqrt(N) do
[if rem(N/I) = 0 then return false;
I:= I+1;
];
return true;
];
func SumDiv(Num); \Return sum of proper divisors of Num
int Num, Div, Sum, Quot;
[Div:= 2;
Sum:= 0;
loop [Quot:= Num/Div;
if Div > Quot then quit;
if rem(0) = 0 then
[Sum:= Sum + Div;
if Div # Quot then Sum:= Sum + Quot;
];
Div:= Div+1;
];
return Sum+1;
];
func GCD(A, B); \Return greatest common divisor of A and B
int A, B;
[while A#B do
if A>B then A:= A-B
else B:= B-A;
return A;
];
func Duff(N); \Return 'true' if N is a Duffinian number
int N;
[if IsPrime(N) then return false;
return GCD(SumDiv(N), N) = 1;
];
int C, N;
[Format(4, 0);
C:= 0; N:= 4;
loop [if Duff(N) then
[RlOut(0, float(N));
C:= C+1;
if C >= 50 then quit;
if rem(C/20) = 0 then CrLf(0);
];
N:= N+1;
];
CrLf(0); CrLf(0);
Format(5, 0);
C:= 0; N:= 4;
loop [if Duff(N) & Duff(N+1) & Duff(N+2) then
[RlOut(0, float(N)); RlOut(0, float(N+1)); RlOut(0, float(N+2));
CrLf(0);
C:= C+1;
if C >= 15 then quit;
];
N:= N+1;
];
] |
http://rosettacode.org/wiki/Element-wise_operations | Element-wise operations | This task is similar to:
Matrix multiplication
Matrix transposition
Task
Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks.
Implement:
addition
subtraction
multiplication
division
exponentiation
Extend the task if necessary to include additional basic operations, which should not require their own specialised task.
| #Go | Go | package element
import (
"fmt"
"math"
)
type Matrix struct {
ele []float64
stride int
}
func MatrixFromRows(rows [][]float64) Matrix {
if len(rows) == 0 {
return Matrix{nil, 0}
}
m := Matrix{make([]float64, len(rows)*len(rows[0])), len(rows[0])}
for rx, row := range rows {
copy(m.ele[rx*m.stride:(rx+1)*m.stride], row)
}
return m
}
func like(m Matrix) Matrix {
return Matrix{make([]float64, len(m.ele)), m.stride}
}
func (m Matrix) String() string {
s := ""
for e := 0; e < len(m.ele); e += m.stride {
s += fmt.Sprintf("%6.3f \n", m.ele[e:e+m.stride])
}
return s
}
type binaryFunc64 func(float64, float64) float64
func elementWiseMM(m1, m2 Matrix, f binaryFunc64) Matrix {
z := like(m1)
for i, m1e := range m1.ele {
z.ele[i] = f(m1e, m2.ele[i])
}
return z
}
func elementWiseMS(m Matrix, s float64, f binaryFunc64) Matrix {
z := like(m)
for i, e := range m.ele {
z.ele[i] = f(e, s)
}
return z
}
func add(a, b float64) float64 { return a + b }
func sub(a, b float64) float64 { return a - b }
func mul(a, b float64) float64 { return a * b }
func div(a, b float64) float64 { return a / b }
func exp(a, b float64) float64 { return math.Pow(a, b) }
func AddMatrix(m1, m2 Matrix) Matrix { return elementWiseMM(m1, m2, add) }
func SubMatrix(m1, m2 Matrix) Matrix { return elementWiseMM(m1, m2, sub) }
func MulMatrix(m1, m2 Matrix) Matrix { return elementWiseMM(m1, m2, mul) }
func DivMatrix(m1, m2 Matrix) Matrix { return elementWiseMM(m1, m2, div) }
func ExpMatrix(m1, m2 Matrix) Matrix { return elementWiseMM(m1, m2, exp) }
func AddScalar(m Matrix, s float64) Matrix { return elementWiseMS(m, s, add) }
func SubScalar(m Matrix, s float64) Matrix { return elementWiseMS(m, s, sub) }
func MulScalar(m Matrix, s float64) Matrix { return elementWiseMS(m, s, mul) }
func DivScalar(m Matrix, s float64) Matrix { return elementWiseMS(m, s, div) }
func ExpScalar(m Matrix, s float64) Matrix { return elementWiseMS(m, s, exp) } |
http://rosettacode.org/wiki/Dynamic_variable_names | Dynamic variable names | Task
Create a variable with a user-defined name.
The variable name should not be written in the program text, but should be taken from the user dynamically.
See also
Eval in environment is a similar task.
| #Epoxy | Epoxy | --Add user-defined variable to the stack
const VarName: io.prompt("Input Variable Name: "),
VarValue: io.prompt("Input Variable Value: ")
debug.newvar(VarName,VarValue)
--Outputting the results
log(debug.getvar(VarName)) |
http://rosettacode.org/wiki/Dynamic_variable_names | Dynamic variable names | Task
Create a variable with a user-defined name.
The variable name should not be written in the program text, but should be taken from the user dynamically.
See also
Eval in environment is a similar task.
| #Erlang | Erlang |
-module( dynamic_variable_names ).
-export( [task/0] ).
task() ->
{ok,[Variable_name]} = io:fread( "Variable name? ", "~a" ),
Form = runtime_evaluation:form_from_string( erlang:atom_to_list(Variable_name) ++ "." ),
io:fwrite( "~p has value ~p~n", [Variable_name, runtime_evaluation:evaluate_form(Form, {Variable_name, 42})] ).
|
http://rosettacode.org/wiki/Draw_a_pixel | Draw a pixel | Task
Create a window and draw a pixel in it, subject to the following:
the window is 320 x 240
the color of the pixel must be red (255,0,0)
the position of the pixel is x = 100, y = 100 | #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program dpixel.s */
/* compile with as */
/* link with gcc and options -lX11 -L/usr/lpp/X11/lib */
/********************************************/
/*Constantes */
/********************************************/
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
/* constantes X11 */
.equ KeyPressed, 2
.equ ButtonPress, 4
.equ MotionNotify, 6
.equ EnterNotify, 7
.equ LeaveNotify, 8
.equ Expose, 12
.equ ClientMessage, 33
.equ KeyPressMask, 1
.equ ButtonPressMask, 4
.equ ButtonReleaseMask, 8
.equ ExposureMask, 1<<15
.equ StructureNotifyMask, 1<<17
.equ EnterWindowMask, 1<<4
.equ LeaveWindowMask, 1<<5
.equ ConfigureNotify, 22
/*******************************************/
/* DONNEES INITIALISEES */
/*******************************************/
.data
szWindowName: .asciz "Windows Raspberry"
szRetourligne: .asciz "\n"
szMessDebutPgm: .asciz "Program start. \n"
szMessErreur: .asciz "Server X not found.\n"
szMessErrfen: .asciz "Can not create window.\n"
szMessErreurX11: .asciz "Error call function X11. \n"
szMessErrGc: .asciz "Can not create graphics context.\n"
szTitreFenRed: .asciz "Pi"
szTexte1: .asciz "<- red pixel is here !!"
.equ LGTEXTE1, . - szTexte1
szTexte2: .asciz "Press q for close window or clic X in system menu."
.equ LGTEXTE2, . - szTexte2
szLibDW: .asciz "WM_DELETE_WINDOW" @ special label for correct close error
/*************************************************/
szMessErr: .ascii "Error code hexa : "
sHexa: .space 9,' '
.ascii " decimal : "
sDeci: .space 15,' '
.asciz "\n"
/*******************************************/
/* DONNEES NON INITIALISEES */
/*******************************************/
.bss
.align 4
ptDisplay: .skip 4 @ pointer display
ptEcranDef: .skip 4 @ pointer screen default
ptFenetre: .skip 4 @ pointer window
ptGC: .skip 4 @ pointer graphic context
ptGC1: .skip 4 @ pointer graphic context1
key: .skip 4 @ key code
wmDeleteMessage: .skip 8 @ ident close message
event: .skip 400 @ TODO event size ??
PrpNomFenetre: .skip 100 @ window name proprety
buffer: .skip 500
iWhite: .skip 4 @ rgb code for white pixel
iBlack: .skip 4 @ rgb code for black pixel
/**********************************************/
/* -- Code section */
/**********************************************/
.text
.global main
main: @ entry of program
ldr r0,iAdrszMessDebutPgm @
bl affichageMess @ display start message on console linux
/* attention r6 pointer display*/
/* attention r8 pointer graphic context */
/* attention r9 ident window */
/*****************************/
/* OPEN SERVER X11 */
/*****************************/
mov r0,#0
bl XOpenDisplay @ open X server
cmp r0,#0 @ error ?
beq erreurServeur
ldr r1,iAdrptDisplay
str r0,[r1] @ store display address
mov r6,r0 @ and in register r6
ldr r2,[r0,#+132] @ load default_screen
ldr r1,iAdrptEcranDef
str r2,[r1] @ store default_screen
mov r2,r0
ldr r0,[r2,#+140] @ load pointer screen list
ldr r5,[r0,#+52] @ load value white pixel
ldr r4,iAdrWhite @ and store in memory
str r5,[r4]
ldr r3,[r0,#+56] @ load value black pixel
ldr r4,iAdrBlack @ and store in memory
str r3,[r4]
ldr r4,[r0,#+28] @ load bits par pixel
ldr r1,[r0,#+8] @ load root windows
/**************************/
/* CREATE WINDOW */
/**************************/
mov r0,r6 @ address display
mov r2,#0 @ window position X
mov r3,#0 @ window position Y
mov r8,#0 @ for stack alignement
push {r8}
push {r3} @ background = black pixel
push {r5} @ border = white pixel
mov r8,#2 @ border size
push {r8}
mov r8,#240 @ hauteur
push {r8}
mov r8,#320 @ largeur
push {r8}
bl XCreateSimpleWindow
add sp,#24 @ stack alignement 6 push (4 bytes * 6)
cmp r0,#0 @ error ?
beq erreurF
ldr r1,iAdrptFenetre
str r0,[r1] @ store window address in memory
mov r9,r0 @ and in register r9
/*****************************/
/* add window property */
/*****************************/
mov r0,r6 @ display address
mov r1,r9 @ window address
ldr r2,iAdrszWindowName @ window name
ldr r3,iAdrszTitreFenRed @ window name reduced
mov r4,#0
push {r4} @ parameters not use
push {r4}
push {r4}
push {r4}
bl XSetStandardProperties
add sp,sp,#16 @ stack alignement for 4 push
/**************************************/
/* for correction window close error */
/**************************************/
mov r0,r6 @ display address
ldr r1,iAdrszLibDW @ atom address
mov r2,#1 @ False créate atom if not exists
bl XInternAtom
cmp r0,#0 @ error X11 ?
ble erreurX11
ldr r1,iAdrwmDeleteMessage @ recept address
str r0,[r1]
mov r2,r1 @ return address
mov r0,r6 @ display address
mov r1,r9 @ window address
mov r3,#1 @ number of protocols
bl XSetWMProtocols
cmp r0,#0 @ error X11 ?
ble erreurX11
/**********************************/
/* create graphic context */
/**********************************/
mov r0,r6 @ display address
mov r1,r9 @ window address
mov r2,#0 @ not use for simply context
mov r3,#0
bl XCreateGC
cmp r0,#0 @ error ?
beq erreurGC
ldr r1,iAdrptGC
str r0,[r1] @ store address graphic context
mov r8,r0 @ and in r8
@ create other GC
mov r0,r6 @ display address
mov r1,r9 @ window address
mov r2,#0 @ not use for simply context
mov r3,#0
bl XCreateGC
cmp r0,#0 @ error ?
beq erreurGC
ldr r1,iAdrptGC1
str r0,[r1] @ store address graphic context 1
mov r1,r0
mov r0,r6
mov r2,#0xFF0000 @ color red
bl XSetForeground
cmp r0,#0
beq erreurGC
/****************************/
/* modif window background */
/****************************/
mov r0,r6 @ display address
mov r1,r9 @ window address
ldr r2,iGris1 @ background color
bl XSetWindowBackground
cmp r0,#0 @ error ?
ble erreurX11
/***************************/
/* OUF!! window display */
/***************************/
mov r0,r6 @ display address
mov r1,r9 @ window address
bl XMapWindow
/****************************/
/* Write text1 in the window */
/****************************/
mov r0,r6 @ display address
mov r1,r9 @ window address
mov r2,r8 @ address graphic context
mov r3,#105 @ position x
sub sp,#4 @ stack alignement
mov r4,#LGTEXTE1 - 1 @ size string
push {r4} @ on the stack
ldr r4,iAdrszTexte1 @ string address
push {r4}
mov r4,#105 @ position y
push {r4}
bl XDrawString
add sp,sp,#16 @ stack alignement 3 push and 1 stack alignement
cmp r0,#0 @ error ?
blt erreurX11
/****************************/
/* Write text2 in the window */
/****************************/
mov r0,r6 @ display address
mov r1,r9 @ window address
mov r2,r8 @ address graphic context
mov r3,#10 @ position x
sub sp,#4 @ stack alignement
mov r4,#LGTEXTE2 - 1 @ size string
push {r4} @ on the stack
ldr r4,iAdrszTexte2 @ string address
push {r4}
mov r4,#200 @ position y
push {r4}
bl XDrawString
add sp,sp,#16 @ stack alignement 3 push and 1 stack alignement
cmp r0,#0 @ error ?
blt erreurX11
/****************************************/
/* draw pixel */
/****************************************/
mov r0,r6 @ display address
mov r1,r9 @ window address
ldr r2,iAdrptGC1
ldr r2,[r2] @ address graphic context 1
mov r3,#100 @ position x
sub sp,sp,#4 @ stack alignement
mov r4,#100 @ position y
push {r4} @ on the stack
bl XDrawPoint
add sp,sp,#8 @ stack alignement 1 push and 1 stack alignement
cmp r0,#0 @ error ?
blt erreurX11
/****************************/
/* Autorisations */
/****************************/
mov r0,r6 @ display address
mov r1,r9 @ window address
ldr r2,iFenetreMask @ autorisation mask
bl XSelectInput
cmp r0,#0 @ error ?
ble erreurX11
/****************************/
/* Events loop */
/****************************/
1:
mov r0,r6 @ display address
ldr r1,iAdrevent @ events address
bl XNextEvent @ event ?
ldr r0,iAdrevent
ldr r0,[r0] @ code event
cmp r0,#KeyPressed @ key ?
bne 2f
ldr r0,iAdrevent @ yes read key in buffer
ldr r1,iAdrbuffer
mov r2,#255
ldr r3,iAdrkey
mov r4,#0
push {r4} @ stack alignement
push {r4}
bl XLookupString
add sp,#8 @ stack alignement 2 push
cmp r0,#1 @ is character key ?
bne 2f
ldr r0,iAdrbuffer @ yes -> load first buffer character
ldrb r0,[r0]
cmp r0,#0x71 @ character q for quit
beq 5f @ yes -> end
b 4f
2:
/* */
/* for example clic mouse button */
/************************************/
cmp r0,#ButtonPress @ clic mouse buton
bne 3f
ldr r0,iAdrevent
ldr r1,[r0,#+32] @ position X mouse clic
ldr r2,[r0,#+36] @ position Y
@ etc for eventuel use
b 4f
3:
cmp r0,#ClientMessage @ code for close window within error
bne 4f
ldr r0,iAdrevent
ldr r1,[r0,#+28] @ code message address
ldr r2,iAdrwmDeleteMessage @ equal code window créate ???
ldr r2,[r2]
cmp r1,r2
beq 5f @ yes -> end window
4: @ loop for other event
b 1b
/***********************************/
/* Close window -> free ressources */
/***********************************/
5:
mov r0,r6 @ display address
ldr r1,iAdrptGC
ldr r1,[r1] @ load context graphic address
bl XFreeGC
cmp r0,#0
blt erreurX11
mov r0,r6 @ display address
mov r1,r9 @ window address
bl XDestroyWindow
cmp r0,#0
blt erreurX11
mov r0,r6 @ display address
bl XCloseDisplay
cmp r0,#0
blt erreurX11
mov r0,#0 @ return code OK
b 100f
erreurF: @ create error window but possible not necessary. Display error by server
ldr r1,iAdrszMessErrfen
bl displayError
mov r0,#1 @ return error code
b 100f
erreurGC: @ error create graphic context
ldr r1,iAdrszMessErrGc
bl displayError
mov r0,#1
b 100f
erreurX11: @ erreur X11
ldr r1,iAdrszMessErreurX11
bl displayError
mov r0,#1
b 100f
erreurServeur: @ error no found X11 server see doc putty and Xming
ldr r1,iAdrszMessErreur
bl displayError
mov r0,#1
b 100f
100: @ standard end of the program
mov r7, #EXIT
svc 0
iFenetreMask: .int KeyPressMask|ButtonPressMask|StructureNotifyMask
iGris1: .int 0xFFA0A0A0
iAdrWhite: .int iWhite
iAdrBlack: .int iBlack
iAdrptDisplay: .int ptDisplay
iAdrptEcranDef: .int ptEcranDef
iAdrptFenetre: .int ptFenetre
iAdrptGC: .int ptGC
iAdrptGC1: .int ptGC1
iAdrevent: .int event
iAdrbuffer: .int buffer
iAdrkey: .int key
iAdrszLibDW: .int szLibDW
iAdrszMessDebutPgm: .int szMessDebutPgm
iAdrszMessErreurX11: .int szMessErreurX11
iAdrszMessErrGc: .int szMessErrGc
iAdrszMessErreur: .int szMessErreur
iAdrszMessErrfen: .int szMessErrfen
iAdrszWindowName: .int szWindowName
iAdrszTitreFenRed: .int szTitreFenRed
iAdrszTexte1: .int szTexte1
iAdrszTexte2: .int szTexte2
iAdrPrpNomFenetre: .int PrpNomFenetre
iAdrwmDeleteMessage: .int wmDeleteMessage
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {r0,r1,r2,r7,lr} @ save registres
mov r2,#0 @ counter length
1: @ loop length calculation
ldrb r1,[r0,r2] @ read octet start position + index
cmp r1,#0 @ if 0 its over
addne r2,r2,#1 @ else add 1 in the length
bne 1b @ and loop
@ so here r2 contains the length of the message
mov r1,r0 @ address message in r1
mov r0,#STDOUT @ code to write to the standard output Linux
mov r7, #WRITE @ code call system "write"
svc #0 @ call systeme
pop {r0,r1,r2,r7,lr} @ restaur registers
bx lr @ return
/***************************************************/
/* display error message */
/***************************************************/
/* r0 contains error code r1 : message address */
displayError:
push {r0-r2,lr} @ save registers
mov r2,r0 @ save error code
mov r0,r1
bl affichageMess
mov r0,r2 @ error code
ldr r1,iAdrsHexa
bl conversion16 @ conversion hexa
mov r0,r2 @ error code
ldr r1,iAdrsDeci @ result address
bl conversion10 @ conversion decimale
ldr r0,iAdrszMessErr @ display error message
bl affichageMess
100:
pop {r0-r2,lr} @ restaur registers
bx lr @ return
iAdrszMessErr: .int szMessErr
iAdrsHexa: .int sHexa
iAdrsDeci: .int sDeci
/******************************************************************/
/* Converting a register to hexadecimal */
/******************************************************************/
/* r0 contains value and r1 address area */
conversion16:
push {r1-r4,lr} @ save registers
mov r2,#28 @ start bit position
mov r4,#0xF0000000 @ mask
mov r3,r0 @ save entry value
1: @ start loop
and r0,r3,r4 @value register and mask
lsr r0,r2 @ move right
cmp r0,#10 @ compare value
addlt r0,#48 @ <10 ->digit
addge r0,#55 @ >10 ->letter A-F
strb r0,[r1],#1 @ store digit on area and + 1 in area address
lsr r4,#4 @ shift mask 4 positions
subs r2,#4 @ counter bits - 4 <= zero ?
bge 1b @ no -> loop
100:
pop {r1-r4,lr} @ restaur registers
bx lr @return
/******************************************************************/
/* Converting a register to a decimal unsigned */
/******************************************************************/
/* r0 contains value and r1 address area */
/* r0 return size of result (no zero final in area) */
/* area size => 11 bytes */
.equ LGZONECAL, 10
conversion10:
push {r1-r4,lr} @ save registers
mov r3,r1
mov r2,#LGZONECAL
1: @ start loop
bl divisionpar10U @ unsigned r0 <- dividende. quotient ->r0 reste -> r1
add r1,#48 @ digit
strb r1,[r3,r2] @ store digit on area
cmp r0,#0 @ stop if quotient = 0
subne r2,#1 @ else previous position
bne 1b @ and loop
@ and move digit from left of area
mov r4,#0
2:
ldrb r1,[r3,r2]
strb r1,[r3,r4]
add r2,#1
add r4,#1
cmp r2,#LGZONECAL
ble 2b
@ and move spaces in end on area
mov r0,r4 @ result length
mov r1,#' ' @ space
3:
strb r1,[r3,r4] @ store space in area
add r4,#1 @ next position
cmp r4,#LGZONECAL
ble 3b @ loop if r4 <= area size
100:
pop {r1-r4,lr} @ restaur registres
bx lr @return
/***************************************************/
/* division par 10 unsigned */
/***************************************************/
/* r0 dividende */
/* r0 quotient */
/* r1 remainder */
divisionpar10U:
push {r2,r3,r4, lr}
mov r4,r0 @ save value
ldr r3,iMagicNumber @ r3 <- magic_number raspberry 1 2
umull r1, r2, r3, r0 @ r1<- Lower32Bits(r1*r0) r2<- Upper32Bits(r1*r0)
mov r0, r2, LSR #3 @ r2 <- r2 >> shift 3
add r2,r0,r0, lsl #2 @ r2 <- r0 * 5
sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10)
pop {r2,r3,r4,lr}
bx lr @ leave function
iMagicNumber: .int 0xCCCCCCCD
/***************************************************/
/* integer division unsigned */
/***************************************************/
division:
/* r0 contains dividend */
/* r1 contains divisor */
/* r2 returns quotient */
/* r3 returns remainder */
push {r4, lr}
mov r2, #0 @ init quotient
mov r3, #0 @ init remainder
mov r4, #32 @ init counter bits
b 2f
1: @ loop
movs r0, r0, LSL #1 @ r0 <- r0 << 1 updating cpsr (sets C if 31st bit of r0 was 1)
adc r3, r3, r3 @ r3 <- r3 + r3 + C. This is equivalent to r3 ? (r3 << 1) + C
cmp r3, r1 @ compute r3 - r1 and update cpsr
subhs r3, r3, r1 @ if r3 >= r1 (C=1) then r3 <- r3 - r1
adc r2, r2, r2 @ r2 <- r2 + r2 + C. This is equivalent to r2 <- (r2 << 1) + C
2:
subs r4, r4, #1 @ r4 <- r4 - 1
bpl 1b @ if r4 >= 0 (N=0) then loop
pop {r4, lr}
bx lr
|
http://rosettacode.org/wiki/Egyptian_division | Egyptian division | Egyptian division is a method of dividing integers using addition and
doubling that is similar to the algorithm of Ethiopian multiplication
Algorithm:
Given two numbers where the dividend is to be divided by the divisor:
Start the construction of a table of two columns: powers_of_2, and doublings; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column.
Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order.
Continue with successive i’th rows of 2^i and 2^i * divisor.
Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend.
We now assemble two separate sums that both start as zero, called here answer and accumulator
Consider each row of the table, in the reverse order of its construction.
If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer.
When the first row has been considered as above, then the integer division of dividend by divisor is given by answer.
(And the remainder is given by the absolute value of accumulator - dividend).
Example: 580 / 34
Table creation:
powers_of_2
doublings
1
34
2
68
4
136
8
272
16
544
Initialization of sums:
powers_of_2
doublings
answer
accumulator
1
34
2
68
4
136
8
272
16
544
0
0
Considering table rows, bottom-up:
When a row is considered it is shown crossed out if it is not accumulated, or bold if the row causes summations.
powers_of_2
doublings
answer
accumulator
1
34
2
68
4
136
8
272
16
544
16
544
powers_of_2
doublings
answer
accumulator
1
34
2
68
4
136
8
272
16
544
16
544
powers_of_2
doublings
answer
accumulator
1
34
2
68
4
136
16
544
8
272
16
544
powers_of_2
doublings
answer
accumulator
1
34
2
68
16
544
4
136
8
272
16
544
powers_of_2
doublings
answer
accumulator
1
34
17
578
2
68
4
136
8
272
16
544
Answer
So 580 divided by 34 using the Egyptian method is 17 remainder (578 - 580) or 2.
Task
The task is to create a function that does Egyptian division. The function should
closely follow the description above in using a list/array of powers of two, and
another of doublings.
Functions should be clear interpretations of the algorithm.
Use the function to divide 580 by 34 and show the answer here, on this page.
Related tasks
Egyptian fractions
References
Egyptian Number System
| #Factor | Factor | USING: assocs combinators formatting kernel make math sequences ;
IN: rosetta-code.egyptian-division
: table ( dividend divisor -- table )
[ [ 2dup >= ] [ dup , 2 * ] while ] { } make 2nip
dup length <iota> [ 2^ ] map zip <reversed> ;
: accum ( a b dividend -- c )
[ 2dup [ first ] bi@ + ] dip < [ [ + ] 2map ] [ drop ] if ;
: ediv ( dividend divisor -- quotient remainder )
{
[ table ]
[ 2drop { 0 0 } ]
[ drop [ accum ] curry reduce first2 swap ]
[ drop - abs ]
} 2cleave ;
580 34 ediv "580 divided by 34 is %d remainder %d\n" printf |
http://rosettacode.org/wiki/Egyptian_division | Egyptian division | Egyptian division is a method of dividing integers using addition and
doubling that is similar to the algorithm of Ethiopian multiplication
Algorithm:
Given two numbers where the dividend is to be divided by the divisor:
Start the construction of a table of two columns: powers_of_2, and doublings; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column.
Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order.
Continue with successive i’th rows of 2^i and 2^i * divisor.
Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend.
We now assemble two separate sums that both start as zero, called here answer and accumulator
Consider each row of the table, in the reverse order of its construction.
If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer.
When the first row has been considered as above, then the integer division of dividend by divisor is given by answer.
(And the remainder is given by the absolute value of accumulator - dividend).
Example: 580 / 34
Table creation:
powers_of_2
doublings
1
34
2
68
4
136
8
272
16
544
Initialization of sums:
powers_of_2
doublings
answer
accumulator
1
34
2
68
4
136
8
272
16
544
0
0
Considering table rows, bottom-up:
When a row is considered it is shown crossed out if it is not accumulated, or bold if the row causes summations.
powers_of_2
doublings
answer
accumulator
1
34
2
68
4
136
8
272
16
544
16
544
powers_of_2
doublings
answer
accumulator
1
34
2
68
4
136
8
272
16
544
16
544
powers_of_2
doublings
answer
accumulator
1
34
2
68
4
136
16
544
8
272
16
544
powers_of_2
doublings
answer
accumulator
1
34
2
68
16
544
4
136
8
272
16
544
powers_of_2
doublings
answer
accumulator
1
34
17
578
2
68
4
136
8
272
16
544
Answer
So 580 divided by 34 using the Egyptian method is 17 remainder (578 - 580) or 2.
Task
The task is to create a function that does Egyptian division. The function should
closely follow the description above in using a list/array of powers of two, and
another of doublings.
Functions should be clear interpretations of the algorithm.
Use the function to divide 580 by 34 and show the answer here, on this page.
Related tasks
Egyptian fractions
References
Egyptian Number System
| #Forth | Forth |
variable tab-end
: build ( m n -- )
pad tab-end !
swap >r 1 swap \ dividend on ret stack
begin dup r@ <= while
2dup tab-end @ 2!
[ 2 cells ] literal tab-end +!
swap dup +
swap dup +
repeat 2drop rdrop ;
: e/mod ( m n -- q r )
over >r build
0 r> \ initial quotient = 0, remainder = dividend
pad tab-end @ [ 2 cells ] literal - do
dup i @ >= if
i @ - swap i cell+ @ + swap
then
[ -2 cells ] literal +loop ;
: .egypt ( m n -- )
cr 2dup swap . ." divided by " . ." is " e/mod swap . ." remainder " . ;
|
http://rosettacode.org/wiki/Egyptian_fractions | Egyptian fractions | An Egyptian fraction is the sum of distinct unit fractions such as:
1
2
+
1
3
+
1
16
(
=
43
48
)
{\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})}
Each fraction in the expression has a numerator equal to 1 (unity) and a denominator that is a positive integer, and all the denominators are distinct (i.e., no repetitions).
Fibonacci's Greedy algorithm for Egyptian fractions expands the fraction
x
y
{\displaystyle {\tfrac {x}{y}}}
to be represented by repeatedly performing the replacement
x
y
=
1
⌈
y
/
x
⌉
+
(
−
y
)
mod
x
y
⌈
y
/
x
⌉
{\displaystyle {\frac {x}{y}}={\frac {1}{\lceil y/x\rceil }}+{\frac {(-y)\!\!\!\!\mod x}{y\lceil y/x\rceil }}}
(simplifying the 2nd term in this replacement as necessary, and where
⌈
x
⌉
{\displaystyle \lceil x\rceil }
is the ceiling function).
For this task, Proper and improper fractions must be able to be expressed.
Proper fractions are of the form
a
b
{\displaystyle {\tfrac {a}{b}}}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are positive integers, such that
a
<
b
{\displaystyle a<b}
, and
improper fractions are of the form
a
b
{\displaystyle {\tfrac {a}{b}}}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are positive integers, such that a ≥ b.
(See the REXX programming example to view one method of expressing the whole number part of an improper fraction.)
For improper fractions, the integer part of any improper fraction should be first isolated and shown preceding the Egyptian unit fractions, and be surrounded by square brackets [n].
Task requirements
show the Egyptian fractions for:
43
48
{\displaystyle {\tfrac {43}{48}}}
and
5
121
{\displaystyle {\tfrac {5}{121}}}
and
2014
59
{\displaystyle {\tfrac {2014}{59}}}
for all proper fractions,
a
b
{\displaystyle {\tfrac {a}{b}}}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are positive one-or two-digit (decimal) integers, find and show an Egyptian fraction that has:
the largest number of terms,
the largest denominator.
for all one-, two-, and three-digit integers, find and show (as above). {extra credit}
Also see
Wolfram MathWorld™ entry: Egyptian fraction
| #Go | Go | package main
import (
"fmt"
"math/big"
"strings"
)
var zero = new(big.Int)
var one = big.NewInt(1)
func toEgyptianRecursive(br *big.Rat, fracs []*big.Rat) []*big.Rat {
if br.Num().Cmp(zero) == 0 {
return fracs
}
iquo := new(big.Int)
irem := new(big.Int)
iquo.QuoRem(br.Denom(), br.Num(), irem)
if irem.Cmp(zero) > 0 {
iquo.Add(iquo, one)
}
rquo := new(big.Rat).SetFrac(one, iquo)
fracs = append(fracs, rquo)
num2 := new(big.Int).Neg(br.Denom())
num2.Rem(num2, br.Num())
if num2.Cmp(zero) < 0 {
num2.Add(num2, br.Num())
}
denom2 := new(big.Int)
denom2.Mul(br.Denom(), iquo)
f := new(big.Rat).SetFrac(num2, denom2)
if f.Num().Cmp(one) == 0 {
fracs = append(fracs, f)
return fracs
}
fracs = toEgyptianRecursive(f, fracs)
return fracs
}
func toEgyptian(rat *big.Rat) []*big.Rat {
if rat.Num().Cmp(zero) == 0 {
return []*big.Rat{rat}
}
var fracs []*big.Rat
if rat.Num().CmpAbs(rat.Denom()) >= 0 {
iquo := new(big.Int)
iquo.Quo(rat.Num(), rat.Denom())
rquo := new(big.Rat).SetFrac(iquo, one)
rrem := new(big.Rat)
rrem.Sub(rat, rquo)
fracs = append(fracs, rquo)
fracs = toEgyptianRecursive(rrem, fracs)
} else {
fracs = toEgyptianRecursive(rat, fracs)
}
return fracs
}
func main() {
fracs := []*big.Rat{big.NewRat(43, 48), big.NewRat(5, 121), big.NewRat(2014, 59)}
for _, frac := range fracs {
list := toEgyptian(frac)
if list[0].Denom().Cmp(one) == 0 {
first := fmt.Sprintf("[%v]", list[0].Num())
temp := make([]string, len(list)-1)
for i := 1; i < len(list); i++ {
temp[i-1] = list[i].String()
}
rest := strings.Join(temp, " + ")
fmt.Printf("%v -> %v + %s\n", frac, first, rest)
} else {
temp := make([]string, len(list))
for i := 0; i < len(list); i++ {
temp[i] = list[i].String()
}
all := strings.Join(temp, " + ")
fmt.Printf("%v -> %s\n", frac, all)
}
}
for _, r := range [2]int{98, 998} {
if r == 98 {
fmt.Println("\nFor proper fractions with 1 or 2 digits:")
} else {
fmt.Println("\nFor proper fractions with 1, 2 or 3 digits:")
}
maxSize := 0
var maxSizeFracs []*big.Rat
maxDen := zero
var maxDenFracs []*big.Rat
var sieve = make([][]bool, r+1) // to eliminate duplicates
for i := 0; i <= r; i++ {
sieve[i] = make([]bool, r+2)
}
for i := 1; i <= r; i++ {
for j := i + 1; j <= r+1; j++ {
if sieve[i][j] {
continue
}
f := big.NewRat(int64(i), int64(j))
list := toEgyptian(f)
listSize := len(list)
if listSize > maxSize {
maxSize = listSize
maxSizeFracs = maxSizeFracs[0:0]
maxSizeFracs = append(maxSizeFracs, f)
} else if listSize == maxSize {
maxSizeFracs = append(maxSizeFracs, f)
}
listDen := list[len(list)-1].Denom()
if listDen.Cmp(maxDen) > 0 {
maxDen = listDen
maxDenFracs = maxDenFracs[0:0]
maxDenFracs = append(maxDenFracs, f)
} else if listDen.Cmp(maxDen) == 0 {
maxDenFracs = append(maxDenFracs, f)
}
if i < r/2 {
k := 2
for {
if j*k > r+1 {
break
}
sieve[i*k][j*k] = true
k++
}
}
}
}
fmt.Println(" largest number of items =", maxSize)
fmt.Println(" fraction(s) with this number :", maxSizeFracs)
md := maxDen.String()
fmt.Print(" largest denominator = ", len(md), " digits, ")
fmt.Print(md[0:20], "...", md[len(md)-20:], "\b\n")
fmt.Println(" fraction(s) with this denominator :", maxDenFracs)
}
} |
http://rosettacode.org/wiki/Ethiopian_multiplication | Ethiopian multiplication | Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving.
Method:
Take two numbers to be multiplied and write them down at the top of two columns.
In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last in the same column, until you write a value of 1.
In the right-hand column repeatedly double the last number and write the result below. stop when you add a result in the same row as where the left hand column shows 1.
Examine the table produced and discard any row where the value in the left column is even.
Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together
For example: 17 × 34
17 34
Halving the first column:
17 34
8
4
2
1
Doubling the second column:
17 34
8 68
4 136
2 272
1 544
Strike-out rows whose first cell is even:
17 34
8 68
4 136
2 272
1 544
Sum the remaining numbers in the right-hand column:
17 34
8 --
4 ---
2 ---
1 544
====
578
So 17 multiplied by 34, by the Ethiopian method is 578.
Task
The task is to define three named functions/methods/procedures/subroutines:
one to halve an integer,
one to double an integer, and
one to state if an integer is even.
Use these functions to create a function that does Ethiopian multiplication.
References
Ethiopian multiplication explained (BBC Video clip)
A Night Of Numbers - Go Forth And Multiply (Video)
Russian Peasant Multiplication
Programming Praxis: Russian Peasant Multiplication
| #Ruby | Ruby | def halve(x) x/2 end
def double(x) x*2 end
# iterative
def ethiopian_multiply(a, b)
product = 0
while a >= 1
p [a, b, a.even? ? "STRIKE" : "KEEP"] if $DEBUG
product += b unless a.even?
a = halve(a)
b = double(b)
end
product
end
# recursive
def rec_ethiopian_multiply(a, b)
return 0 if a < 1
p [a, b, a.even? ? "STRIKE" : "KEEP"] if $DEBUG
(a.even? ? 0 : b) + rec_ethiopian_multiply(halve(a), double(b))
end
$DEBUG = true # $DEBUG also set to true if "-d" option given
a, b = 20, 5
puts "#{a} * #{b} = #{ethiopian_multiply(a,b)}"; puts |
http://rosettacode.org/wiki/Elementary_cellular_automaton | Elementary cellular automaton | An elementary cellular automaton is a one-dimensional cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three bits.
The rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101.
Task
Create a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice.
The space state should wrap: this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally.
This task is basically a generalization of one-dimensional cellular automata.
See also
Cellular automata (natureofcode.com)
| #Kotlin | Kotlin | // version 1.1.51
import java.util.BitSet
const val SIZE = 32
const val LINES = SIZE / 2
const val RULE = 90
fun ruleTest(x: Int) = (RULE and (1 shl (7 and x))) != 0
infix fun Boolean.shl(bitCount: Int) = (if (this) 1 else 0) shl bitCount
fun Boolean.toInt() = if (this) 1 else 0
fun evolve(s: BitSet) {
val t = BitSet(SIZE) // all false by default
t[SIZE - 1] = ruleTest((s[0] shl 2) or (s[SIZE - 1] shl 1) or s[SIZE - 2].toInt())
t[0] = ruleTest((s[1] shl 2) or (s[0] shl 1) or s[SIZE - 1].toInt())
for (i in 1 until SIZE - 1) {
t[i] = ruleTest((s[i + 1] shl 2) or (s[i] shl 1) or s[i - 1].toInt())
}
for (i in 0 until SIZE) s[i] = t[i]
}
fun show(s: BitSet) {
for (i in SIZE - 1 downTo 0) print(if (s[i]) "*" else " ")
println()
}
fun main(args: Array<String>) {
var state = BitSet(SIZE)
state.set(LINES)
println("Rule $RULE:")
repeat(LINES) {
show(state)
evolve(state)
}
} |
http://rosettacode.org/wiki/Factorial | Factorial | Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a number.
Solutions can be iterative or recursive.
Support for trapping negative n errors is optional.
Related task
Primorial numbers
| #Ursa | Ursa | def factorial (int n)
decl int result
set result 1
decl int i
for (set i 1) (< i (+ n 1)) (inc i)
set result (* result i)
end
return result
end
|
http://rosettacode.org/wiki/Even_or_odd | Even or odd | Task
Test whether an integer is even or odd.
There is more than one way to solve this task:
Use the even and odd predicates, if the language provides them.
Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd.
Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd.
Use modular congruences:
i ≡ 0 (mod 2) iff i is even.
i ≡ 1 (mod 2) iff i is odd.
| #zkl | zkl | [-3..4].pump(fcn(n){ println(n," is ",n.isEven and "even" or "odd") }) |
http://rosettacode.org/wiki/Even_or_odd | Even or odd | Task
Test whether an integer is even or odd.
There is more than one way to solve this task:
Use the even and odd predicates, if the language provides them.
Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd.
Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd.
Use modular congruences:
i ≡ 0 (mod 2) iff i is even.
i ≡ 1 (mod 2) iff i is odd.
| #Zoea | Zoea |
program: even_or_odd
case: 1
input: 2
output: even
case: 2
input: 4
output: even
case: 3
input: 1
output: odd
case: 4
input: 7
output: odd
|
http://rosettacode.org/wiki/Echo_server | Echo server | Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary to support connections from localhost (127.0.0.1 or perhaps ::1). Logging of connection information to standard output is recommended.
The implementation must be able to handle simultaneous connections from multiple clients. A multi-threaded or multi-process solution may be used. Each connection must be able to echo more than a single line.
The implementation must not stop responding to other clients if one client sends a partial line or stops reading responses.
| #LFE | LFE |
(defun start ()
(spawn (lambda ()
(let ((`#(ok ,socket) (gen_tcp:listen 12321 `(#(packet line)))))
(echo-loop socket)))))
(defun echo-loop (socket)
(let* ((`#(ok ,conn) (gen_tcp:accept socket))
(handler (spawn (lambda () (handle conn)))))
(lfe_io:format "Got connection: ~p~n" (list conn))
(gen_tcp:controlling_process conn handler)
(echo-loop socket)))
(defun handle (conn)
(receive
(`#(tcp ,conn ,data)
(gen_tcp:send conn data))
(`#(tcp_closed ,conn)
(lfe_io:format "Connection closed: ~p~n" (list conn)))))
|
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Verilog | Verilog | module main;
endmodule |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #VHDL | VHDL | entity dummy is
end;
architecture empty of dummy is
begin
end; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.