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/Erd%C3%B6s-Selfridge_categorization_of_primes | Erdös-Selfridge categorization of primes | A prime p is in category 1 if the prime factors of p+1 are 2 and or 3. p is in category 2 if all the prime factors of p+1 are in category 1. p is in category g if all the prime factors of p+1 are in categories 1 to g-1.
The task is first to display the first 200 primes allocated to their category, then assign the first million primes to their category, displaying the smallest prime, the largest prime, and the count of primes allocated to each category.
| #Sidef | Sidef | func Erdös_Selfridge_class(n, s=1) is cached {
var f = factor_exp(n+s)
f.last.head > 3 || return 1
f.map {|p| __FUNC__(p.head, s) }.max + 1
}
say "First two hundred primes; Erdös-Selfridge categorized:"
200.pn_primes.group_by(Erdös_Selfridge_class).sort_by{.to_i}.each_2d {|k,v|
say "#{k} => #{v}"
}
say "\nSummary of first 10^6 primes; Erdös-Selfridge categorized:";
1e6.pn_primes.group_by(Erdös_Selfridge_class).sort_by{.to_i}.each_2d {|k,v|
printf("Category %2d: first: %9s last: %10s count: %s\n", k, v.first, v.last, v.len)
} |
http://rosettacode.org/wiki/Erd%C3%B6s-Selfridge_categorization_of_primes | Erdös-Selfridge categorization of primes | A prime p is in category 1 if the prime factors of p+1 are 2 and or 3. p is in category 2 if all the prime factors of p+1 are in category 1. p is in category g if all the prime factors of p+1 are in categories 1 to g-1.
The task is first to display the first 200 primes allocated to their category, then assign the first million primes to their category, displaying the smallest prime, the largest prime, and the count of primes allocated to each category.
| #Wren | Wren | import "./math" for Int
import "./fmt" for Fmt
var limit = (1e6.log * 1e6 * 1.2).floor // should be more than enough
var primes = Int.primeSieve(limit)
var prevCats = {}
var cat // recursive
cat = Fn.new { |p|
if (prevCats.containsKey(p)) return prevCats[p]
var pf = Int.primeFactors(p+1)
if (pf.all { |f| f == 2 || f == 3 }) return 1
if (p > 2) {
for (i in pf.count-1..1) {
if (pf[i-1] == pf[i]) pf.removeAt(i)
}
}
for (c in 2..11) {
if (pf.all { |f| cat.call(f) < c }) {
prevCats[p] = c
return c
}
}
return 12
}
var es = List.filled(12, null)
for (i in 0..11) es[i] = []
System.print("First 200 primes:\n ")
for (p in primes[0..199]) {
var c = cat.call(p)
es[c-1].add(p)
}
for (c in 1..6) {
if (es[c-1].count > 0) {
System.print("Category %(c):")
System.print(es[c-1])
System.print()
}
}
System.print("First million primes:\n")
for (p in primes[200...1e6]) {
var c = cat.call(p)
es[c-1].add(p)
}
for (c in 1..12) {
var e = es[c-1]
if (e.count > 0) {
Fmt.print("Category $-2d: First = $7d Last = $8d Count = $6d", c, e[0], e[-1], e.count)
}
} |
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
| #M4 | M4 | define(`factorial',`ifelse(`$1',0,1,`eval($1*factorial(decr($1)))')')dnl
dnl
factorial(5) |
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.
| #11l | 11l | F is_even(i)
R i % 2 == 0
F is_odd(i)
R i % 2 == 1 |
http://rosettacode.org/wiki/Euler_method | Euler method | Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value. It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page.
The ODE has to be provided in the following form:
d
y
(
t
)
d
t
=
f
(
t
,
y
(
t
)
)
{\displaystyle {\frac {dy(t)}{dt}}=f(t,y(t))}
with an initial value
y
(
t
0
)
=
y
0
{\displaystyle y(t_{0})=y_{0}}
To get a numeric solution, we replace the derivative on the LHS with a finite difference approximation:
d
y
(
t
)
d
t
≈
y
(
t
+
h
)
−
y
(
t
)
h
{\displaystyle {\frac {dy(t)}{dt}}\approx {\frac {y(t+h)-y(t)}{h}}}
then solve for
y
(
t
+
h
)
{\displaystyle y(t+h)}
:
y
(
t
+
h
)
≈
y
(
t
)
+
h
d
y
(
t
)
d
t
{\displaystyle y(t+h)\approx y(t)+h\,{\frac {dy(t)}{dt}}}
which is the same as
y
(
t
+
h
)
≈
y
(
t
)
+
h
f
(
t
,
y
(
t
)
)
{\displaystyle y(t+h)\approx y(t)+h\,f(t,y(t))}
The iterative solution rule is then:
y
n
+
1
=
y
n
+
h
f
(
t
n
,
y
n
)
{\displaystyle y_{n+1}=y_{n}+h\,f(t_{n},y_{n})}
where
h
{\displaystyle h}
is the step size, the most relevant parameter for accuracy of the solution. A smaller step size increases accuracy but also the computation cost, so it has always has to be hand-picked according to the problem at hand.
Example: Newton's Cooling Law
Newton's cooling law describes how an object of initial temperature
T
(
t
0
)
=
T
0
{\displaystyle T(t_{0})=T_{0}}
cools down in an environment of temperature
T
R
{\displaystyle T_{R}}
:
d
T
(
t
)
d
t
=
−
k
Δ
T
{\displaystyle {\frac {dT(t)}{dt}}=-k\,\Delta T}
or
d
T
(
t
)
d
t
=
−
k
(
T
(
t
)
−
T
R
)
{\displaystyle {\frac {dT(t)}{dt}}=-k\,(T(t)-T_{R})}
It says that the cooling rate
d
T
(
t
)
d
t
{\displaystyle {\frac {dT(t)}{dt}}}
of the object is proportional to the current temperature difference
Δ
T
=
(
T
(
t
)
−
T
R
)
{\displaystyle \Delta T=(T(t)-T_{R})}
to the surrounding environment.
The analytical solution, which we will compare to the numerical approximation, is
T
(
t
)
=
T
R
+
(
T
0
−
T
R
)
e
−
k
t
{\displaystyle T(t)=T_{R}+(T_{0}-T_{R})\;e^{-kt}}
Task
Implement a routine of Euler's method and then to use it to solve the given example of Newton's cooling law with it for three different step sizes of:
2 s
5 s and
10 s
and to compare with the analytical solution.
Initial values
initial temperature
T
0
{\displaystyle T_{0}}
shall be 100 °C
room temperature
T
R
{\displaystyle T_{R}}
shall be 20 °C
cooling constant
k
{\displaystyle k}
shall be 0.07
time interval to calculate shall be from 0 s ──► 100 s
A reference solution (Common Lisp) can be seen below. We see that bigger step sizes lead to reduced approximation accuracy.
| #Common_Lisp | Common Lisp | ;; 't' usually means "true" in CL, but we need 't' here for time/temperature.
(defconstant true 'cl:t)
(shadow 't)
;; Approximates y(t) in y'(t)=f(t,y) with y(a)=y0 and t=a..b and the step size h.
(defun euler (f y0 a b h)
;; Set the initial values and increments of the iteration variables.
(do ((t a (+ t h))
(y y0 (+ y (* h (funcall f t y)))))
;; End the iteration when t reaches the end b of the time interval.
((>= t b) 'DONE)
;; Print t and y(t) at every step of the do loop.
(format true "~6,3F ~6,3F~%" t y)))
;; Example: Newton's cooling law, f(t,T) = -0.07*(T-20)
(defun newton-cooling (time T) (* -0.07 (- T 20)))
;; Generate the data for all three step sizes (2,5 and 10).
(euler #'newton-cooling 100 0 100 2)
(euler #'newton-cooling 100 0 100 5)
(euler #'newton-cooling 100 0 100 10) |
http://rosettacode.org/wiki/Evaluate_binomial_coefficients | Evaluate binomial coefficients | This programming task, is to calculate ANY binomial coefficient.
However, it has to be able to output
(
5
3
)
{\displaystyle {\binom {5}{3}}}
, which is 10.
This formula is recommended:
(
n
k
)
=
n
!
(
n
−
k
)
!
k
!
=
n
(
n
−
1
)
(
n
−
2
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
(
k
−
2
)
…
1
{\displaystyle {\binom {n}{k}}={\frac {n!}{(n-k)!k!}}={\frac {n(n-1)(n-2)\ldots (n-k+1)}{k(k-1)(k-2)\ldots 1}}}
See Also:
Combinations and permutations
Pascal's triangle
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #360_Assembly | 360 Assembly | * Evaluate binomial coefficients - 29/09/2015
BINOMIAL CSECT
USING BINOMIAL,R15 set base register
SR R4,R4 clear for mult and div
LA R5,1 r=1
LA R7,1 i=1
L R8,N m=n
LOOP LR R4,R7 do while i<=k
C R4,K i<=k
BH LOOPEND if not then exit while
MR R4,R8 r*m
DR R4,R7 r=r*m/i
LA R7,1(R7) i=i+1
BCTR R8,0 m=m-1
B LOOP loop while
LOOPEND XDECO R5,PG edit r
XPRNT PG,12 print r
XR R15,R15 set return code
BR R14 return to caller
N DC F'10' <== input value
K DC F'4' <== input value
PG DS CL12 buffer
YREGS
END BINOMIAL |
http://rosettacode.org/wiki/Evaluate_binomial_coefficients | Evaluate binomial coefficients | This programming task, is to calculate ANY binomial coefficient.
However, it has to be able to output
(
5
3
)
{\displaystyle {\binom {5}{3}}}
, which is 10.
This formula is recommended:
(
n
k
)
=
n
!
(
n
−
k
)
!
k
!
=
n
(
n
−
1
)
(
n
−
2
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
(
k
−
2
)
…
1
{\displaystyle {\binom {n}{k}}={\frac {n!}{(n-k)!k!}}={\frac {n(n-1)(n-2)\ldots (n-k+1)}{k(k-1)(k-2)\ldots 1}}}
See Also:
Combinations and permutations
Pascal's triangle
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #ABAP | ABAP | CLASS lcl_binom DEFINITION CREATE PUBLIC.
PUBLIC SECTION.
CLASS-METHODS:
calc
IMPORTING n TYPE i
k TYPE i
RETURNING VALUE(r_result) TYPE f.
ENDCLASS.
CLASS lcl_binom IMPLEMENTATION.
METHOD calc.
r_result = 1.
DATA(i) = 1.
DATA(m) = n.
WHILE i <= k.
r_result = r_result * m / i.
i = i + 1.
m = m - 1.
ENDWHILE.
ENDMETHOD.
ENDCLASS. |
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
Fn = Fn+2 - Fn+1, if n<0
support for negative n in the solution is optional.
Related tasks
Fibonacci n-step number sequences
Leonardo numbers
References
Wikipedia, Fibonacci number
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #TUSCRIPT | TUSCRIPT |
$$ MODE TUSCRIPT
ASK "What fibionacci number do you want?": searchfib=""
IF (searchfib!='digits') STOP
Loop n=0,{searchfib}
IF (n==0) THEN
fib=fiba=n
ELSEIF (n==1) THEN
fib=fibb=n
ELSE
fib=fiba+fibb, fiba=fibb, fibb=fib
ENDIF
IF (n!=searchfib) CYCLE
PRINT "fibionacci number ",n,"=",fib
ENDLOOP
|
http://rosettacode.org/wiki/Esthetic_numbers | Esthetic numbers | An esthetic number is a positive integer where every adjacent digit differs from its neighbour by 1.
E.G.
12 is an esthetic number. One and two differ by 1.
5654 is an esthetic number. Each digit is exactly 1 away from its neighbour.
890 is not an esthetic number. Nine and zero differ by 9.
These examples are nominally in base 10 but the concept extends easily to numbers in other bases. Traditionally, single digit numbers are included in esthetic numbers; zero may or may not be. For our purposes, for this task, do not include zero (0) as an esthetic number. Do not include numbers with leading zeros.
Esthetic numbers are also sometimes referred to as stepping numbers.
Task
Write a routine (function, procedure, whatever) to find esthetic numbers in a given base.
Use that routine to find esthetic numbers in bases 2 through 16 and display, here on this page, the esthectic numbers from index (base × 4) through index (base × 6), inclusive. (E.G. for base 2: 8th through 12th, for base 6: 24th through 36th, etc.)
Find and display, here on this page, the base 10 esthetic numbers with a magnitude between 1000 and 9999.
Stretch: Find and display, here on this page, the base 10 esthetic numbers with a magnitude between 1.0e8 and 1.3e8.
Related task
numbers with equal rises and falls
See also
OEIS A033075 - Positive numbers n such that all pairs of consecutive decimal digits differ by 1
Numbers Aplenty - Esthetic numbers
Geeks for Geeks - Stepping numbers
| #C | C | #include <stdio.h>
#include <string.h>
#include <locale.h>
typedef int bool;
typedef unsigned long long ull;
#define TRUE 1
#define FALSE 0
char as_digit(int d) {
return (d >= 0 && d <= 9) ? d + '0' : d - 10 + 'a';
}
void revstr(char *str) {
int i, len = strlen(str);
char t;
for (i = 0; i < len/2; ++i) {
t = str[i];
str[i] = str[len - i - 1];
str[len - i - 1] = t;
}
}
char* to_base(char s[], ull n, int b) {
int i = 0;
while (n) {
s[i++] = as_digit(n % b);
n /= b;
}
s[i] = '\0';
revstr(s);
return s;
}
ull uabs(ull a, ull b) {
return a > b ? a - b : b - a;
}
bool is_esthetic(ull n, int b) {
int i, j;
if (!n) return FALSE;
i = n % b;
n /= b;
while (n) {
j = n % b;
if (uabs(i, j) != 1) return FALSE;
n /= b;
i = j;
}
return TRUE;
}
ull esths[45000];
int le = 0;
void dfs(ull n, ull m, ull i) {
ull d, i1, i2;
if (i >= n && i <= m) esths[le++] = i;
if (i == 0 || i > m) return;
d = i % 10;
i1 = i * 10 + d - 1;
i2 = i1 + 2;
if (d == 0) {
dfs(n, m, i2);
} else if (d == 9) {
dfs(n, m, i1);
} else {
dfs(n, m, i1);
dfs(n, m, i2);
}
}
void list_esths(ull n, ull n2, ull m, ull m2, int per_line, bool all) {
int i;
le = 0;
for (i = 0; i < 10; ++i) {
dfs(n2, m2, i);
}
printf("Base 10: %'d esthetic numbers between %'llu and %'llu:\n", le, n, m);
if (all) {
for (i = 0; i < le; ++i) {
printf("%llu ", esths[i]);
if (!(i+1)%per_line) printf("\n");
}
} else {
for (i = 0; i < per_line; ++i) printf("%llu ", esths[i]);
printf("\n............\n");
for (i = le - per_line; i < le; ++i) printf("%llu ", esths[i]);
}
printf("\n\n");
}
int main() {
ull n;
int b, c;
char ch[15] = {0};
for (b = 2; b <= 16; ++b) {
printf("Base %d: %dth to %dth esthetic numbers:\n", b, 4*b, 6*b);
for (n = 1, c = 0; c < 6 * b; ++n) {
if (is_esthetic(n, b)) {
if (++c >= 4 * b) printf("%s ", to_base(ch, n, b));
}
}
printf("\n\n");
}
char *oldLocale = setlocale(LC_NUMERIC, NULL);
setlocale(LC_NUMERIC, "");
// the following all use the obvious range limitations for the numbers in question
list_esths(1000, 1010, 9999, 9898, 16, TRUE);
list_esths(1e8, 101010101, 13*1e7, 123456789, 9, TRUE);
list_esths(1e11, 101010101010, 13*1e10, 123456789898, 7, FALSE);
list_esths(1e14, 101010101010101, 13*1e13, 123456789898989, 5, FALSE);
list_esths(1e17, 101010101010101010, 13*1e16, 123456789898989898, 4, FALSE);
setlocale(LC_NUMERIC, oldLocale);
return 0;
} |
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
| #MAD | MAD | NORMAL MODE IS INTEGER
R CALCULATE FACTORIAL OF N
INTERNAL FUNCTION(N)
ENTRY TO FACT.
RES = 1
THROUGH FACMUL, FOR MUL = 2, 1, MUL.G.N
FACMUL RES = RES * MUL
FUNCTION RETURN RES
END OF FUNCTION
R USE THE FUNCTION TO PRINT 0! THROUGH 12!
VECTOR VALUES FMT = $I2,6H ! IS ,I9*$
THROUGH PRNFAC, FOR NUM = 0, 1, NUM.G.12
PRNFAC PRINT FORMAT FMT, NUM, FACT.(NUM)
END OF PROGRAM |
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.
| #6502_Assembly | 6502 Assembly |
.lf evenodd6502.lst
.cr 6502
.tf evenodd6502.obj,ap1
;------------------------------------------------------
; Even or Odd for the 6502 by barrym95838 2014.12.10
; Thanks to sbprojects.com for a very nice assembler!
; The target for this assembly is an Apple II with
; mixed-case output capabilities. Apple IIs like to
; work in '+128' ascii, and this version is tailored
; to that preference.
; Tested and verified on AppleWin 1.20.0.0
;------------------------------------------------------
; Constant Section
;
CharIn = $fd0c ;Specific to the Apple II
CharOut = $fded ;Specific to the Apple II
;------------------------------------------------------
; The main program
;
main ldy #sIntro-sbase
jsr puts ;Print Intro
loop jsr CharIn ;Get a char from stdin
cmp #$83 ;Ctrl-C?
beq done ; yes: end program
jsr CharOut ;Echo char
ldy #sOdd-sbase ;Pre-load odd string
lsr ;LSB of char to carry flag
bcs isodd
ldy #sEven-sbase
isodd jsr puts ;Print appropriate response
beq loop ;Always taken
; Output NUL-terminated string @ offset Y
;
puts lda sbase,y ;Get string char
beq done ;Done if NUL
jsr CharOut ;Output the char
iny ;Point to next char
bne puts ;Loop up to 255 times
done rts ;Return to caller
;------------------------------------------------------
; String Constants (in '+128' ascii, Apple II style)
;
sbase: ;String base address
sIntro .az -"Hit any key (Ctrl-C to quit):",-#13
sEven .az -" is even.",-#13
sOdd .az -" is odd.",-#13
;------------------------------------------------------
.en
|
http://rosettacode.org/wiki/Euler_method | Euler method | Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value. It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page.
The ODE has to be provided in the following form:
d
y
(
t
)
d
t
=
f
(
t
,
y
(
t
)
)
{\displaystyle {\frac {dy(t)}{dt}}=f(t,y(t))}
with an initial value
y
(
t
0
)
=
y
0
{\displaystyle y(t_{0})=y_{0}}
To get a numeric solution, we replace the derivative on the LHS with a finite difference approximation:
d
y
(
t
)
d
t
≈
y
(
t
+
h
)
−
y
(
t
)
h
{\displaystyle {\frac {dy(t)}{dt}}\approx {\frac {y(t+h)-y(t)}{h}}}
then solve for
y
(
t
+
h
)
{\displaystyle y(t+h)}
:
y
(
t
+
h
)
≈
y
(
t
)
+
h
d
y
(
t
)
d
t
{\displaystyle y(t+h)\approx y(t)+h\,{\frac {dy(t)}{dt}}}
which is the same as
y
(
t
+
h
)
≈
y
(
t
)
+
h
f
(
t
,
y
(
t
)
)
{\displaystyle y(t+h)\approx y(t)+h\,f(t,y(t))}
The iterative solution rule is then:
y
n
+
1
=
y
n
+
h
f
(
t
n
,
y
n
)
{\displaystyle y_{n+1}=y_{n}+h\,f(t_{n},y_{n})}
where
h
{\displaystyle h}
is the step size, the most relevant parameter for accuracy of the solution. A smaller step size increases accuracy but also the computation cost, so it has always has to be hand-picked according to the problem at hand.
Example: Newton's Cooling Law
Newton's cooling law describes how an object of initial temperature
T
(
t
0
)
=
T
0
{\displaystyle T(t_{0})=T_{0}}
cools down in an environment of temperature
T
R
{\displaystyle T_{R}}
:
d
T
(
t
)
d
t
=
−
k
Δ
T
{\displaystyle {\frac {dT(t)}{dt}}=-k\,\Delta T}
or
d
T
(
t
)
d
t
=
−
k
(
T
(
t
)
−
T
R
)
{\displaystyle {\frac {dT(t)}{dt}}=-k\,(T(t)-T_{R})}
It says that the cooling rate
d
T
(
t
)
d
t
{\displaystyle {\frac {dT(t)}{dt}}}
of the object is proportional to the current temperature difference
Δ
T
=
(
T
(
t
)
−
T
R
)
{\displaystyle \Delta T=(T(t)-T_{R})}
to the surrounding environment.
The analytical solution, which we will compare to the numerical approximation, is
T
(
t
)
=
T
R
+
(
T
0
−
T
R
)
e
−
k
t
{\displaystyle T(t)=T_{R}+(T_{0}-T_{R})\;e^{-kt}}
Task
Implement a routine of Euler's method and then to use it to solve the given example of Newton's cooling law with it for three different step sizes of:
2 s
5 s and
10 s
and to compare with the analytical solution.
Initial values
initial temperature
T
0
{\displaystyle T_{0}}
shall be 100 °C
room temperature
T
R
{\displaystyle T_{R}}
shall be 20 °C
cooling constant
k
{\displaystyle k}
shall be 0.07
time interval to calculate shall be from 0 s ──► 100 s
A reference solution (Common Lisp) can be seen below. We see that bigger step sizes lead to reduced approximation accuracy.
| #D | D | import std.stdio, std.range, std.traits;
/// Approximates y(t) in y'(t)=f(t,y) with y(a)=y0 and t=a..b and the step size h.
void euler(F)(in F f, in double y0, in double a, in double b, in double h) @safe
if (isCallable!F && __traits(compiles, { real r = f(0.0, 0.0); })) {
double y = y0;
foreach (immutable t; iota(a, b, h)) {
writefln("%.3f %.3f", t, y);
y += h * f(t, y);
}
"done".writeln;
}
void main() {
/// Example: Newton's cooling law.
enum newtonCoolingLaw = (in double time, in double t)
pure nothrow @safe @nogc => -0.07 * (t - 20);
euler(newtonCoolingLaw, 100, 0, 100, 2);
euler(newtonCoolingLaw, 100, 0, 100, 5);
euler(newtonCoolingLaw, 100, 0, 100, 10);
} |
http://rosettacode.org/wiki/Evaluate_binomial_coefficients | Evaluate binomial coefficients | This programming task, is to calculate ANY binomial coefficient.
However, it has to be able to output
(
5
3
)
{\displaystyle {\binom {5}{3}}}
, which is 10.
This formula is recommended:
(
n
k
)
=
n
!
(
n
−
k
)
!
k
!
=
n
(
n
−
1
)
(
n
−
2
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
(
k
−
2
)
…
1
{\displaystyle {\binom {n}{k}}={\frac {n!}{(n-k)!k!}}={\frac {n(n-1)(n-2)\ldots (n-k+1)}{k(k-1)(k-2)\ldots 1}}}
See Also:
Combinations and permutations
Pascal's triangle
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #ACL2 | ACL2 | (defun fac (n)
(if (zp n)
1
(* n (fac (1- n)))))
(defun binom (n k)
(/ (fac n) (* (fac (- n k)) (fac k))) |
http://rosettacode.org/wiki/Evaluate_binomial_coefficients | Evaluate binomial coefficients | This programming task, is to calculate ANY binomial coefficient.
However, it has to be able to output
(
5
3
)
{\displaystyle {\binom {5}{3}}}
, which is 10.
This formula is recommended:
(
n
k
)
=
n
!
(
n
−
k
)
!
k
!
=
n
(
n
−
1
)
(
n
−
2
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
(
k
−
2
)
…
1
{\displaystyle {\binom {n}{k}}={\frac {n!}{(n-k)!k!}}={\frac {n(n-1)(n-2)\ldots (n-k+1)}{k(k-1)(k-2)\ldots 1}}}
See Also:
Combinations and permutations
Pascal's triangle
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #Ada | Ada |
with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Binomial is
function Binomial (N, K : Natural) return Natural is
Result : Natural := 1;
M : Natural;
begin
if N < K then
raise Constraint_Error;
end if;
if K > N/2 then -- Use symmetry
M := N - K;
else
M := K;
end if;
for I in 1..M loop
Result := Result * (N - M + I) / I;
end loop;
return Result;
end Binomial;
begin
for N in 0..17 loop
for K in 0..N loop
Put (Integer'Image (Binomial (N, K)));
end loop;
New_Line;
end loop;
end Test_Binomial;
|
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
Fn = Fn+2 - Fn+1, if n<0
support for negative n in the solution is optional.
Related tasks
Fibonacci n-step number sequences
Leonardo numbers
References
Wikipedia, Fibonacci number
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #UNIX_Shell | UNIX Shell | #!/bin/bash
a=0
b=1
max=$1
for (( n=1; "$n" <= "$max"; $((n++)) ))
do
a=$(($a + $b))
echo "F($n): $a"
b=$(($a - $b))
done |
http://rosettacode.org/wiki/Esthetic_numbers | Esthetic numbers | An esthetic number is a positive integer where every adjacent digit differs from its neighbour by 1.
E.G.
12 is an esthetic number. One and two differ by 1.
5654 is an esthetic number. Each digit is exactly 1 away from its neighbour.
890 is not an esthetic number. Nine and zero differ by 9.
These examples are nominally in base 10 but the concept extends easily to numbers in other bases. Traditionally, single digit numbers are included in esthetic numbers; zero may or may not be. For our purposes, for this task, do not include zero (0) as an esthetic number. Do not include numbers with leading zeros.
Esthetic numbers are also sometimes referred to as stepping numbers.
Task
Write a routine (function, procedure, whatever) to find esthetic numbers in a given base.
Use that routine to find esthetic numbers in bases 2 through 16 and display, here on this page, the esthectic numbers from index (base × 4) through index (base × 6), inclusive. (E.G. for base 2: 8th through 12th, for base 6: 24th through 36th, etc.)
Find and display, here on this page, the base 10 esthetic numbers with a magnitude between 1000 and 9999.
Stretch: Find and display, here on this page, the base 10 esthetic numbers with a magnitude between 1.0e8 and 1.3e8.
Related task
numbers with equal rises and falls
See also
OEIS A033075 - Positive numbers n such that all pairs of consecutive decimal digits differ by 1
Numbers Aplenty - Esthetic numbers
Geeks for Geeks - Stepping numbers
| #C.2B.2B | C++ | #include <functional>
#include <iostream>
#include <sstream>
#include <vector>
std::string to(int n, int b) {
static auto BASE = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
std::stringstream ss;
while (n > 0) {
auto rem = n % b;
n = n / b;
ss << BASE[rem];
}
auto fwd = ss.str();
return std::string(fwd.rbegin(), fwd.rend());
}
uint64_t uabs(uint64_t a, uint64_t b) {
if (a < b) {
return b - a;
}
return a - b;
}
bool isEsthetic(uint64_t n, uint64_t b) {
if (n == 0) {
return false;
}
auto i = n % b;
n /= b;
while (n > 0) {
auto j = n % b;
if (uabs(i, j) != 1) {
return false;
}
n /= b;
i = j;
}
return true;
}
void listEsths(uint64_t n, uint64_t n2, uint64_t m, uint64_t m2, int perLine, bool all) {
std::vector<uint64_t> esths;
const auto dfs = [&esths](uint64_t n, uint64_t m, uint64_t i) {
auto dfs_impl = [&esths](uint64_t n, uint64_t m, uint64_t i, auto &dfs_ref) {
if (i >= n && i <= m) {
esths.push_back(i);
}
if (i == 0 || i > m) {
return;
}
auto d = i % 10;
auto i1 = i * 10 + d - 1;
auto i2 = i1 + 2;
if (d == 0) {
dfs_ref(n, m, i2, dfs_ref);
} else if (d == 9) {
dfs_ref(n, m, i1, dfs_ref);
} else {
dfs_ref(n, m, i1, dfs_ref);
dfs_ref(n, m, i2, dfs_ref);
}
};
dfs_impl(n, m, i, dfs_impl);
};
for (int i = 0; i < 10; i++) {
dfs(n2, m2, i);
}
auto le = esths.size();
printf("Base 10: %d esthetic numbers between %llu and %llu:\n", le, n, m);
if (all) {
for (size_t c = 0; c < esths.size(); c++) {
auto esth = esths[c];
printf("%llu ", esth);
if ((c + 1) % perLine == 0) {
printf("\n");
}
}
printf("\n");
} else {
for (int c = 0; c < perLine; c++) {
auto esth = esths[c];
printf("%llu ", esth);
}
printf("\n............\n");
for (size_t i = le - perLine; i < le; i++) {
auto esth = esths[i];
printf("%llu ", esth);
}
printf("\n");
}
printf("\n");
}
int main() {
for (int b = 2; b <= 16; b++) {
printf("Base %d: %dth to %dth esthetic numbers:\n", b, 4 * b, 6 * b);
for (int n = 1, c = 0; c < 6 * b; n++) {
if (isEsthetic(n, b)) {
c++;
if (c >= 4 * b) {
std::cout << to(n, b) << ' ';
}
}
}
printf("\n");
}
printf("\n");
// the following all use the obvious range limitations for the numbers in question
listEsths(1000, 1010, 9999, 9898, 16, true);
listEsths((uint64_t)1e8, 101'010'101, 13 * (uint64_t)1e7, 123'456'789, 9, true);
listEsths((uint64_t)1e11, 101'010'101'010, 13 * (uint64_t)1e10, 123'456'789'898, 7, false);
listEsths((uint64_t)1e14, 101'010'101'010'101, 13 * (uint64_t)1e13, 123'456'789'898'989, 5, false);
listEsths((uint64_t)1e17, 101'010'101'010'101'010, 13 * (uint64_t)1e16, 123'456'789'898'989'898, 4, false);
return 0;
} |
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
| #MANOOL | MANOOL |
{ let rec
{ Fact = -- compile-time constant binding
{ proc { N } as -- precondition: N.IsI48[] & (N >= 0)
: if N == 0 then 1 else
N * Fact[N - 1]
}
}
in -- use Fact here or just make the whole expression to evaluate to it:
Fact
}
|
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.
| #68000_Assembly | 68000 Assembly | BTST D0,#1
BNE isOdd
;else, is even. |
http://rosettacode.org/wiki/Euler_method | Euler method | Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value. It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page.
The ODE has to be provided in the following form:
d
y
(
t
)
d
t
=
f
(
t
,
y
(
t
)
)
{\displaystyle {\frac {dy(t)}{dt}}=f(t,y(t))}
with an initial value
y
(
t
0
)
=
y
0
{\displaystyle y(t_{0})=y_{0}}
To get a numeric solution, we replace the derivative on the LHS with a finite difference approximation:
d
y
(
t
)
d
t
≈
y
(
t
+
h
)
−
y
(
t
)
h
{\displaystyle {\frac {dy(t)}{dt}}\approx {\frac {y(t+h)-y(t)}{h}}}
then solve for
y
(
t
+
h
)
{\displaystyle y(t+h)}
:
y
(
t
+
h
)
≈
y
(
t
)
+
h
d
y
(
t
)
d
t
{\displaystyle y(t+h)\approx y(t)+h\,{\frac {dy(t)}{dt}}}
which is the same as
y
(
t
+
h
)
≈
y
(
t
)
+
h
f
(
t
,
y
(
t
)
)
{\displaystyle y(t+h)\approx y(t)+h\,f(t,y(t))}
The iterative solution rule is then:
y
n
+
1
=
y
n
+
h
f
(
t
n
,
y
n
)
{\displaystyle y_{n+1}=y_{n}+h\,f(t_{n},y_{n})}
where
h
{\displaystyle h}
is the step size, the most relevant parameter for accuracy of the solution. A smaller step size increases accuracy but also the computation cost, so it has always has to be hand-picked according to the problem at hand.
Example: Newton's Cooling Law
Newton's cooling law describes how an object of initial temperature
T
(
t
0
)
=
T
0
{\displaystyle T(t_{0})=T_{0}}
cools down in an environment of temperature
T
R
{\displaystyle T_{R}}
:
d
T
(
t
)
d
t
=
−
k
Δ
T
{\displaystyle {\frac {dT(t)}{dt}}=-k\,\Delta T}
or
d
T
(
t
)
d
t
=
−
k
(
T
(
t
)
−
T
R
)
{\displaystyle {\frac {dT(t)}{dt}}=-k\,(T(t)-T_{R})}
It says that the cooling rate
d
T
(
t
)
d
t
{\displaystyle {\frac {dT(t)}{dt}}}
of the object is proportional to the current temperature difference
Δ
T
=
(
T
(
t
)
−
T
R
)
{\displaystyle \Delta T=(T(t)-T_{R})}
to the surrounding environment.
The analytical solution, which we will compare to the numerical approximation, is
T
(
t
)
=
T
R
+
(
T
0
−
T
R
)
e
−
k
t
{\displaystyle T(t)=T_{R}+(T_{0}-T_{R})\;e^{-kt}}
Task
Implement a routine of Euler's method and then to use it to solve the given example of Newton's cooling law with it for three different step sizes of:
2 s
5 s and
10 s
and to compare with the analytical solution.
Initial values
initial temperature
T
0
{\displaystyle T_{0}}
shall be 100 °C
room temperature
T
R
{\displaystyle T_{R}}
shall be 20 °C
cooling constant
k
{\displaystyle k}
shall be 0.07
time interval to calculate shall be from 0 s ──► 100 s
A reference solution (Common Lisp) can be seen below. We see that bigger step sizes lead to reduced approximation accuracy.
| #Delphi | Delphi | defmodule Euler do
def method(_, _, t, b, _) when t>b, do: :ok
def method(f, y, t, b, h) do
:io.format "~7.3f ~7.3f~n", [t,y]
method(f, y + h * f.(t,y), t + h, b, h)
end
end
f = fn _time, temp -> -0.07 * (temp - 20) end
Enum.each([10, 5, 2], fn step ->
IO.puts "\nStep = #{step}"
Euler.method(f, 100.0, 0.0, 100.0, step)
end) |
http://rosettacode.org/wiki/Euler_method | Euler method | Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value. It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page.
The ODE has to be provided in the following form:
d
y
(
t
)
d
t
=
f
(
t
,
y
(
t
)
)
{\displaystyle {\frac {dy(t)}{dt}}=f(t,y(t))}
with an initial value
y
(
t
0
)
=
y
0
{\displaystyle y(t_{0})=y_{0}}
To get a numeric solution, we replace the derivative on the LHS with a finite difference approximation:
d
y
(
t
)
d
t
≈
y
(
t
+
h
)
−
y
(
t
)
h
{\displaystyle {\frac {dy(t)}{dt}}\approx {\frac {y(t+h)-y(t)}{h}}}
then solve for
y
(
t
+
h
)
{\displaystyle y(t+h)}
:
y
(
t
+
h
)
≈
y
(
t
)
+
h
d
y
(
t
)
d
t
{\displaystyle y(t+h)\approx y(t)+h\,{\frac {dy(t)}{dt}}}
which is the same as
y
(
t
+
h
)
≈
y
(
t
)
+
h
f
(
t
,
y
(
t
)
)
{\displaystyle y(t+h)\approx y(t)+h\,f(t,y(t))}
The iterative solution rule is then:
y
n
+
1
=
y
n
+
h
f
(
t
n
,
y
n
)
{\displaystyle y_{n+1}=y_{n}+h\,f(t_{n},y_{n})}
where
h
{\displaystyle h}
is the step size, the most relevant parameter for accuracy of the solution. A smaller step size increases accuracy but also the computation cost, so it has always has to be hand-picked according to the problem at hand.
Example: Newton's Cooling Law
Newton's cooling law describes how an object of initial temperature
T
(
t
0
)
=
T
0
{\displaystyle T(t_{0})=T_{0}}
cools down in an environment of temperature
T
R
{\displaystyle T_{R}}
:
d
T
(
t
)
d
t
=
−
k
Δ
T
{\displaystyle {\frac {dT(t)}{dt}}=-k\,\Delta T}
or
d
T
(
t
)
d
t
=
−
k
(
T
(
t
)
−
T
R
)
{\displaystyle {\frac {dT(t)}{dt}}=-k\,(T(t)-T_{R})}
It says that the cooling rate
d
T
(
t
)
d
t
{\displaystyle {\frac {dT(t)}{dt}}}
of the object is proportional to the current temperature difference
Δ
T
=
(
T
(
t
)
−
T
R
)
{\displaystyle \Delta T=(T(t)-T_{R})}
to the surrounding environment.
The analytical solution, which we will compare to the numerical approximation, is
T
(
t
)
=
T
R
+
(
T
0
−
T
R
)
e
−
k
t
{\displaystyle T(t)=T_{R}+(T_{0}-T_{R})\;e^{-kt}}
Task
Implement a routine of Euler's method and then to use it to solve the given example of Newton's cooling law with it for three different step sizes of:
2 s
5 s and
10 s
and to compare with the analytical solution.
Initial values
initial temperature
T
0
{\displaystyle T_{0}}
shall be 100 °C
room temperature
T
R
{\displaystyle T_{R}}
shall be 20 °C
cooling constant
k
{\displaystyle k}
shall be 0.07
time interval to calculate shall be from 0 s ──► 100 s
A reference solution (Common Lisp) can be seen below. We see that bigger step sizes lead to reduced approximation accuracy.
| #Elixir | Elixir | defmodule Euler do
def method(_, _, t, b, _) when t>b, do: :ok
def method(f, y, t, b, h) do
:io.format "~7.3f ~7.3f~n", [t,y]
method(f, y + h * f.(t,y), t + h, b, h)
end
end
f = fn _time, temp -> -0.07 * (temp - 20) end
Enum.each([10, 5, 2], fn step ->
IO.puts "\nStep = #{step}"
Euler.method(f, 100.0, 0.0, 100.0, step)
end) |
http://rosettacode.org/wiki/Evaluate_binomial_coefficients | Evaluate binomial coefficients | This programming task, is to calculate ANY binomial coefficient.
However, it has to be able to output
(
5
3
)
{\displaystyle {\binom {5}{3}}}
, which is 10.
This formula is recommended:
(
n
k
)
=
n
!
(
n
−
k
)
!
k
!
=
n
(
n
−
1
)
(
n
−
2
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
(
k
−
2
)
…
1
{\displaystyle {\binom {n}{k}}={\frac {n!}{(n-k)!k!}}={\frac {n(n-1)(n-2)\ldots (n-k+1)}{k(k-1)(k-2)\ldots 1}}}
See Also:
Combinations and permutations
Pascal's triangle
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #ALGOL_68 | ALGOL 68 | PROC factorial = (INT n)INT:
(
INT result;
result := 1;
FOR i TO n DO
result *:= i
OD;
result
);
PROC choose = (INT n, INT k)INT:
(
INT result;
# Note: code can be optimised here as k < n #
result := factorial(n) OVER (factorial(k) * factorial(n - k));
result
);
test:(
print((choose(5, 3), new line))
) |
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
Fn = Fn+2 - Fn+1, if n<0
support for negative n in the solution is optional.
Related tasks
Fibonacci n-step number sequences
Leonardo numbers
References
Wikipedia, Fibonacci number
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #UnixPipes | UnixPipes | echo 1 |tee last fib ; tail -f fib | while read x
do
cat last | tee -a fib | xargs -n 1 expr $x + |tee last
done |
http://rosettacode.org/wiki/Esthetic_numbers | Esthetic numbers | An esthetic number is a positive integer where every adjacent digit differs from its neighbour by 1.
E.G.
12 is an esthetic number. One and two differ by 1.
5654 is an esthetic number. Each digit is exactly 1 away from its neighbour.
890 is not an esthetic number. Nine and zero differ by 9.
These examples are nominally in base 10 but the concept extends easily to numbers in other bases. Traditionally, single digit numbers are included in esthetic numbers; zero may or may not be. For our purposes, for this task, do not include zero (0) as an esthetic number. Do not include numbers with leading zeros.
Esthetic numbers are also sometimes referred to as stepping numbers.
Task
Write a routine (function, procedure, whatever) to find esthetic numbers in a given base.
Use that routine to find esthetic numbers in bases 2 through 16 and display, here on this page, the esthectic numbers from index (base × 4) through index (base × 6), inclusive. (E.G. for base 2: 8th through 12th, for base 6: 24th through 36th, etc.)
Find and display, here on this page, the base 10 esthetic numbers with a magnitude between 1000 and 9999.
Stretch: Find and display, here on this page, the base 10 esthetic numbers with a magnitude between 1.0e8 and 1.3e8.
Related task
numbers with equal rises and falls
See also
OEIS A033075 - Positive numbers n such that all pairs of consecutive decimal digits differ by 1
Numbers Aplenty - Esthetic numbers
Geeks for Geeks - Stepping numbers
| #D | D | import std.conv;
import std.stdio;
ulong uabs(ulong a, ulong b) {
if (a > b) {
return a - b;
}
return b - a;
}
bool isEsthetic(ulong n, ulong b) {
if (n == 0) {
return false;
}
auto i = n % b;
n /= b;
while (n > 0) {
auto j = n % b;
if (uabs(i, j) != 1) {
return false;
}
n /= b;
i = j;
}
return true;
}
ulong[] esths;
void dfs(ulong n, ulong m, ulong i) {
if (i >= n && i <= m) {
esths ~= i;
}
if (i == 0 || i > m) {
return;
}
auto d = i % 10;
auto i1 = i * 10 + d - 1;
auto i2 = i1 + 2;
if (d == 0) {
dfs(n, m, i2);
} else if (d == 9) {
dfs(n, m, i1);
} else {
dfs(n, m, i1);
dfs(n, m, i2);
}
}
void listEsths(ulong n, ulong n2, ulong m, long m2, int perLine, bool all) {
esths.length = 0;
for (auto i = 0; i < 10; i++) {
dfs(n2, m2, i);
}
auto le = esths.length;
writefln("Base 10: %s esthetic numbers between %s and %s:", le, n, m);
if (all) {
foreach (c, esth; esths) {
write(esth, ' ');
if ((c + 1) % perLine == 0) {
writeln;
}
}
writeln;
} else {
for (auto i = 0; i < perLine; i++) {
write(esths[i], ' ');
}
writeln("\n............");
for (auto i = le - perLine; i < le; i++) {
write(esths[i], ' ');
}
writeln;
}
writeln;
}
void main() {
for (auto b = 2; b <= 16; b++) {
writefln("Base %d: %dth to %dth esthetic numbers:", b, 4 * b, 6 * b);
for (auto n = 1, c = 0; c < 6 * b; n++) {
if (isEsthetic(n, b)) {
c++;
if (c >= 4 * b) {
write(to!string(n, b), ' ');
}
}
}
writeln;
}
writeln;
// the following all use the obvious range limitations for the numbers in question
listEsths(1000, 1010, 9999, 9898, 16, true);
listEsths(cast(ulong) 1e8, 101_010_101, 13*cast(ulong) 1e7, 123_456_789, 9, true);
listEsths(cast(ulong) 1e11, 101_010_101_010, 13*cast(ulong) 1e10, 123_456_789_898, 7, false);
listEsths(cast(ulong) 1e14, 101_010_101_010_101, 13*cast(ulong) 1e13, 123_456_789_898_989, 5, false);
listEsths(cast(ulong) 1e17, 101_010_101_010_101_010, 13*cast(ulong) 1e16, 123_456_789_898_989_898, 4, false);
} |
http://rosettacode.org/wiki/Euler%27s_sum_of_powers_conjecture | Euler's sum of powers conjecture | There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin.
Euler's (disproved) sum of powers conjecture
At least k positive kth powers are required to sum to a kth power,
except for the trivial case of one kth power: yk = yk
In 1966, Leon J. Lander and Thomas R. Parkin used a brute-force search on a CDC 6600 computer restricting numbers to those less than 250.
Task
Write a program to search for an integer solution for:
x05 + x15 + x25 + x35 == y5
Where all xi's and y are distinct integers between 0 and 250 (exclusive).
Show an answer here.
Related tasks
Pythagorean quadruples.
Pythagorean triples.
| #11l | 11l | F eulers_sum_of_powers()
V max_n = 250
V pow_5 = (0 .< max_n).map(n -> Int64(n) ^ 5)
V pow5_to_n = Dict(0 .< max_n, n -> (Int64(n) ^ 5, n))
L(x0) 1 .< max_n
L(x1) 1 .< x0
L(x2) 1 .< x1
L(x3) 1 .< x2
V pow_5_sum = pow_5[x0] + pow_5[x1] + pow_5[x2] + pow_5[x3]
I pow_5_sum C pow5_to_n
V y = pow5_to_n[pow_5_sum]
R (x0, x1, x2, x3, y)
V r = eulers_sum_of_powers()
print(‘#.^5 + #.^5 + #.^5 + #.^5 = #.^5’.format(r[0], r[1], r[2], r[3], r[4])) |
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
| #Maple | Maple |
> 5!;
120
|
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.
| #8080_Assembly | 8080 Assembly | CMDLIN: equ 80h ; Location of CP/M command line argument
puts: equ 9h ; Syscall to print a string
;;; Check if number given on command line is even or odd
org 100h
lxi h,CMDLIN ; Find length of argument
mov a,m
add l ; Look up last character (digit)
mov l,a
mov a,m ; Retrieve low digit
rar ; Rotate low bit into carry flag
mvi c,puts ; Prepare to print string
lxi d,odd ; If carry is set, then the number is odd
jc 5 ; So print 'odd'
lxi d,even ; Otherwise, the number is even
jmp 5 ; So print 'even'
even: db 'Even$' ; Strings
odd: db 'Odd$' |
http://rosettacode.org/wiki/Euler_method | Euler method | Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value. It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page.
The ODE has to be provided in the following form:
d
y
(
t
)
d
t
=
f
(
t
,
y
(
t
)
)
{\displaystyle {\frac {dy(t)}{dt}}=f(t,y(t))}
with an initial value
y
(
t
0
)
=
y
0
{\displaystyle y(t_{0})=y_{0}}
To get a numeric solution, we replace the derivative on the LHS with a finite difference approximation:
d
y
(
t
)
d
t
≈
y
(
t
+
h
)
−
y
(
t
)
h
{\displaystyle {\frac {dy(t)}{dt}}\approx {\frac {y(t+h)-y(t)}{h}}}
then solve for
y
(
t
+
h
)
{\displaystyle y(t+h)}
:
y
(
t
+
h
)
≈
y
(
t
)
+
h
d
y
(
t
)
d
t
{\displaystyle y(t+h)\approx y(t)+h\,{\frac {dy(t)}{dt}}}
which is the same as
y
(
t
+
h
)
≈
y
(
t
)
+
h
f
(
t
,
y
(
t
)
)
{\displaystyle y(t+h)\approx y(t)+h\,f(t,y(t))}
The iterative solution rule is then:
y
n
+
1
=
y
n
+
h
f
(
t
n
,
y
n
)
{\displaystyle y_{n+1}=y_{n}+h\,f(t_{n},y_{n})}
where
h
{\displaystyle h}
is the step size, the most relevant parameter for accuracy of the solution. A smaller step size increases accuracy but also the computation cost, so it has always has to be hand-picked according to the problem at hand.
Example: Newton's Cooling Law
Newton's cooling law describes how an object of initial temperature
T
(
t
0
)
=
T
0
{\displaystyle T(t_{0})=T_{0}}
cools down in an environment of temperature
T
R
{\displaystyle T_{R}}
:
d
T
(
t
)
d
t
=
−
k
Δ
T
{\displaystyle {\frac {dT(t)}{dt}}=-k\,\Delta T}
or
d
T
(
t
)
d
t
=
−
k
(
T
(
t
)
−
T
R
)
{\displaystyle {\frac {dT(t)}{dt}}=-k\,(T(t)-T_{R})}
It says that the cooling rate
d
T
(
t
)
d
t
{\displaystyle {\frac {dT(t)}{dt}}}
of the object is proportional to the current temperature difference
Δ
T
=
(
T
(
t
)
−
T
R
)
{\displaystyle \Delta T=(T(t)-T_{R})}
to the surrounding environment.
The analytical solution, which we will compare to the numerical approximation, is
T
(
t
)
=
T
R
+
(
T
0
−
T
R
)
e
−
k
t
{\displaystyle T(t)=T_{R}+(T_{0}-T_{R})\;e^{-kt}}
Task
Implement a routine of Euler's method and then to use it to solve the given example of Newton's cooling law with it for three different step sizes of:
2 s
5 s and
10 s
and to compare with the analytical solution.
Initial values
initial temperature
T
0
{\displaystyle T_{0}}
shall be 100 °C
room temperature
T
R
{\displaystyle T_{R}}
shall be 20 °C
cooling constant
k
{\displaystyle k}
shall be 0.07
time interval to calculate shall be from 0 s ──► 100 s
A reference solution (Common Lisp) can be seen below. We see that bigger step sizes lead to reduced approximation accuracy.
| #Erlang | Erlang |
-module(euler).
-export([main/0, euler/5]).
cooling(_Time, Temperature) ->
(-0.07)*(Temperature-20).
euler(_, Y, T, _, End) when End == T ->
io:fwrite("\n"),
Y;
euler(Func, Y, T, Step, End) ->
if
T rem 10 == 0 ->
io:fwrite("~.3f ",[float(Y)]);
true ->
ok
end,
euler(Func, Y + Step * Func(T, Y), T + Step, Step, End).
analytic(T, End) when T == End ->
io:fwrite("\n"),
T;
analytic(T, End) ->
Y = (20 + 80 * math:exp(-0.07 * T)),
io:fwrite("~.3f ", [Y]),
analytic(T+10, End).
main() ->
io:fwrite("Analytic:\n"),
analytic(0, 100),
io:fwrite("Step 2:\n"),
euler(fun cooling/2, 100, 0, 2, 100),
io:fwrite("Step 5:\n"),
euler(fun cooling/2, 100, 0, 5, 100),
io:fwrite("Step 10:\n"),
euler(fun cooling/2, 100, 0, 10, 100),
ok.
|
http://rosettacode.org/wiki/Evaluate_binomial_coefficients | Evaluate binomial coefficients | This programming task, is to calculate ANY binomial coefficient.
However, it has to be able to output
(
5
3
)
{\displaystyle {\binom {5}{3}}}
, which is 10.
This formula is recommended:
(
n
k
)
=
n
!
(
n
−
k
)
!
k
!
=
n
(
n
−
1
)
(
n
−
2
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
(
k
−
2
)
…
1
{\displaystyle {\binom {n}{k}}={\frac {n!}{(n-k)!k!}}={\frac {n(n-1)(n-2)\ldots (n-k+1)}{k(k-1)(k-2)\ldots 1}}}
See Also:
Combinations and permutations
Pascal's triangle
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #ALGOL_W | ALGOL W | begin
% calculates n!/k! %
integer procedure factorialOverFactorial( integer value n, k ) ;
if k > n then 0
else if k = n then 1
else % k < n % begin
integer f;
f := 1;
for i := k + 1 until n do f := f * i;
f
end factorialOverFactorial ;
% calculates n! %
integer procedure factorial( integer value n ) ;
begin
integer f;
f := 1;
for i := 2 until n do f := f * i;
f
end factorial ;
% calculates the binomial coefficient of (n k) %
% uses the factorialOverFactorial procedure for a slight optimisation %
integer procedure binomialCoefficient( integer value n, k ) ;
if ( n - k ) > k
then factorialOverFactorial( n, n - k ) div factorial( k )
else factorialOverFactorial( n, k ) div factorial( n - k );
% display the binomial coefficient of (5 3) %
write( binomialCoefficient( 5, 3 ) )
end. |
http://rosettacode.org/wiki/Evaluate_binomial_coefficients | Evaluate binomial coefficients | This programming task, is to calculate ANY binomial coefficient.
However, it has to be able to output
(
5
3
)
{\displaystyle {\binom {5}{3}}}
, which is 10.
This formula is recommended:
(
n
k
)
=
n
!
(
n
−
k
)
!
k
!
=
n
(
n
−
1
)
(
n
−
2
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
(
k
−
2
)
…
1
{\displaystyle {\binom {n}{k}}={\frac {n!}{(n-k)!k!}}={\frac {n(n-1)(n-2)\ldots (n-k+1)}{k(k-1)(k-2)\ldots 1}}}
See Also:
Combinations and permutations
Pascal's triangle
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #APL | APL | 3!5
10 |
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
Fn = Fn+2 - Fn+1, if n<0
support for negative n in the solution is optional.
Related tasks
Fibonacci n-step number sequences
Leonardo numbers
References
Wikipedia, Fibonacci number
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #Ursa | Ursa | def fibIter (int n)
if (< n 2)
return n
end if
decl int fib fibPrev num
set fib (set fibPrev 1)
for (set num 2) (< num n) (inc num)
set fib (+ fib fibPrev)
set fibPrev (- fib fibPrev)
end for
return fib
end |
http://rosettacode.org/wiki/Equal_prime_and_composite_sums | Equal prime and composite sums | Suppose we have a sequence of prime sums, where each term Pn is the sum of the first n primes.
P = (2), (2 + 3), (2 + 3 + 5), (2 + 3 + 5 + 7), (2 + 3 + 5 + 7 + 11), ...
P = 2, 5, 10, 17, 28, etc.
Further; suppose we have a sequence of composite sums, where each term Cm is the sum of the first m composites.
C = (4), (4 + 6), (4 + 6 + 8), (4 + 6 + 8 + 9), (4 + 6 + 8 + 9 + 10), ...
C = 4, 10, 18, 27, 37, etc.
Notice that the third term of P; P3 (10) is equal to the second term of C; C2 (10);
Task
Find and display the indices (n, m) and value of at least the first 6 terms of the sequence of numbers that are both the sum of the first n primes and the first m composites.
See also
OEIS:A007504 - Sum of the first n primes
OEIS:A053767 - Sum of first n composite numbers
OEIS:A294174 - Numbers that can be expressed both as the sum of first primes and as the sum of first composites
| #C.2B.2B | C++ | #include <primesieve.hpp>
#include <chrono>
#include <iomanip>
#include <iostream>
#include <locale>
class composite_iterator {
public:
composite_iterator();
uint64_t next_composite();
private:
uint64_t composite;
uint64_t prime;
primesieve::iterator pi;
};
composite_iterator::composite_iterator() {
composite = prime = pi.next_prime();
for (; composite == prime; ++composite)
prime = pi.next_prime();
}
uint64_t composite_iterator::next_composite() {
uint64_t result = composite;
while (++composite == prime)
prime = pi.next_prime();
return result;
}
int main() {
std::cout.imbue(std::locale(""));
auto start = std::chrono::high_resolution_clock::now();
composite_iterator ci;
primesieve::iterator pi;
uint64_t prime_sum = pi.next_prime();
uint64_t composite_sum = ci.next_composite();
uint64_t prime_index = 1, composite_index = 1;
std::cout << "Sum | Prime Index | Composite Index\n";
std::cout << "------------------------------------------------------\n";
for (int count = 0; count < 11;) {
if (prime_sum == composite_sum) {
std::cout << std::right << std::setw(21) << prime_sum << " | "
<< std::setw(12) << prime_index << " | " << std::setw(15)
<< composite_index << '\n';
composite_sum += ci.next_composite();
prime_sum += pi.next_prime();
++prime_index;
++composite_index;
++count;
} else if (prime_sum < composite_sum) {
prime_sum += pi.next_prime();
++prime_index;
} else {
composite_sum += ci.next_composite();
++composite_index;
}
}
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> duration(end - start);
std::cout << "\nElapsed time: " << duration.count() << " seconds\n";
} |
http://rosettacode.org/wiki/Esthetic_numbers | Esthetic numbers | An esthetic number is a positive integer where every adjacent digit differs from its neighbour by 1.
E.G.
12 is an esthetic number. One and two differ by 1.
5654 is an esthetic number. Each digit is exactly 1 away from its neighbour.
890 is not an esthetic number. Nine and zero differ by 9.
These examples are nominally in base 10 but the concept extends easily to numbers in other bases. Traditionally, single digit numbers are included in esthetic numbers; zero may or may not be. For our purposes, for this task, do not include zero (0) as an esthetic number. Do not include numbers with leading zeros.
Esthetic numbers are also sometimes referred to as stepping numbers.
Task
Write a routine (function, procedure, whatever) to find esthetic numbers in a given base.
Use that routine to find esthetic numbers in bases 2 through 16 and display, here on this page, the esthectic numbers from index (base × 4) through index (base × 6), inclusive. (E.G. for base 2: 8th through 12th, for base 6: 24th through 36th, etc.)
Find and display, here on this page, the base 10 esthetic numbers with a magnitude between 1000 and 9999.
Stretch: Find and display, here on this page, the base 10 esthetic numbers with a magnitude between 1.0e8 and 1.3e8.
Related task
numbers with equal rises and falls
See also
OEIS A033075 - Positive numbers n such that all pairs of consecutive decimal digits differ by 1
Numbers Aplenty - Esthetic numbers
Geeks for Geeks - Stepping numbers
| #F.23 | F# |
// Generate Esthetic Numbers. Nigel Galloway: March 21st., 2020
let rec fN Σ n g = match g with h::t -> match List.head h with
0 -> fN ((1::h)::Σ) n t
|g when g=n-1 -> fN ((g-1::h)::Σ) n t
|g -> fN ((g-1::h)::(g+1::h)::Σ) n t
|_ -> Σ
let Esthetic n = let Esthetic, g = fN [] n, [1..n-1] |> List.map(fun n->[n])
Seq.unfold(fun n->Some(n,Esthetic(List.rev n)))(g) |> Seq.concat
let EtoS n = let g = "0123456789abcdef".ToCharArray()
n |> List.map(fun n->g.[n]) |> List.rev |> Array.ofList |> System.String
|
http://rosettacode.org/wiki/Euler%27s_sum_of_powers_conjecture | Euler's sum of powers conjecture | There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin.
Euler's (disproved) sum of powers conjecture
At least k positive kth powers are required to sum to a kth power,
except for the trivial case of one kth power: yk = yk
In 1966, Leon J. Lander and Thomas R. Parkin used a brute-force search on a CDC 6600 computer restricting numbers to those less than 250.
Task
Write a program to search for an integer solution for:
x05 + x15 + x25 + x35 == y5
Where all xi's and y are distinct integers between 0 and 250 (exclusive).
Show an answer here.
Related tasks
Pythagorean quadruples.
Pythagorean triples.
| #360_Assembly | 360 Assembly | EULERCO CSECT
USING EULERCO,R13
B 80(R15)
DC 17F'0'
DC CL8'EULERCO'
STM R14,R12,12(R13)
ST R13,4(R15)
ST R15,8(R13)
LR R13,R15
ZAP X1,=P'1'
LOOPX1 ZAP PT,MAXN do x1=1 to maxn-4
SP PT,=P'4'
CP X1,PT
BH ELOOPX1
ZAP PT,X1
AP PT,=P'1'
ZAP X2,PT
LOOPX2 ZAP PT,MAXN do x2=x1+1 to maxn-3
SP PT,=P'3'
CP X2,PT
BH ELOOPX2
ZAP PT,X2
AP PT,=P'1'
ZAP X3,PT
LOOPX3 ZAP PT,MAXN do x3=x2+1 to maxn-2
SP PT,=P'2'
CP X3,PT
BH ELOOPX3
ZAP PT,X3
AP PT,=P'1'
ZAP X4,PT
LOOPX4 ZAP PT,MAXN do x4=x3+1 to maxn-1
SP PT,=P'1'
CP X4,PT
BH ELOOPX4
ZAP PT,X4
AP PT,=P'1'
ZAP X5,PT x5=x4+1
ZAP SUMX,=P'0' sumx=0
ZAP PT,X1 x1
BAL R14,POWER5
AP SUMX,PT
ZAP PT,X2 x2
BAL R14,POWER5
AP SUMX,PT
ZAP PT,X3 x3
BAL R14,POWER5
AP SUMX,PT
ZAP PT,X4 x4
BAL R14,POWER5
AP SUMX,PT sumx=x1**5+x2**5+x3**5+x4**5
ZAP PT,X5 x5
BAL R14,POWER5
ZAP VALX,PT valx=x5**5
LOOPX5 CP X5,MAXN while x5<=maxn & valx<=sumx
BH ELOOPX5
CP VALX,SUMX
BH ELOOPX5
CP VALX,SUMX if valx=sumx
BNE NOTEQUAL
MVI BUF,C' '
MVC BUF+1(79),BUF clear buffer
MVC WC,MASK
ED WC,X1 x1
MVC BUF+0(8),WC+8
MVC WC,MASK
ED WC,X2 x2
MVC BUF+8(8),WC+8
MVC WC,MASK
ED WC,X3 x3
MVC BUF+16(8),WC+8
MVC WC,MASK
ED WC,X4 x4
MVC BUF+24(8),WC+8
MVC WC,MASK
ED WC,X5 x5
MVC BUF+32(8),WC+8
XPRNT BUF,80 output x1,x2,x3,x4,x5
B ELOOPX1
NOTEQUAL ZAP PT,X5
AP PT,=P'1'
ZAP X5,PT x5=x5+1
ZAP PT,X5
BAL R14,POWER5
ZAP VALX,PT valx=x5**5
B LOOPX5
ELOOPX5 AP X4,=P'1'
B LOOPX4
ELOOPX4 AP X3,=P'1'
B LOOPX3
ELOOPX3 AP X2,=P'1'
B LOOPX2
ELOOPX2 AP X1,=P'1'
B LOOPX1
ELOOPX1 L R13,4(0,R13)
LM R14,R12,12(R13)
XR R15,R15
BR R14
POWER5 ZAP PQ,PT ^1
MP PQ,PT ^2
MP PQ,PT ^3
MP PQ,PT ^4
MP PQ,PT ^5
ZAP PT,PQ
BR R14
MAXN DC PL8'249'
X1 DS PL8
X2 DS PL8
X3 DS PL8
X4 DS PL8
X5 DS PL8
SUMX DS PL8
VALX DS PL8
PT DS PL8
PQ DS PL8
WC DS CL17
MASK DC X'40',13X'20',X'212060' CL17
BUF DS CL80
YREGS
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
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | factorial[n_Integer] := n*factorial[n-1]
factorial[0] = 1 |
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.
| #8086_Assembly | 8086 Assembly | test ax,1
jne isOdd
;else, is even |
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.
| #8th | 8th | : odd? \ n -- boolean
dup 1 n:band 1 n:= ;
: even? \ n -- boolean
odd? not ; |
http://rosettacode.org/wiki/Euler_method | Euler method | Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value. It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page.
The ODE has to be provided in the following form:
d
y
(
t
)
d
t
=
f
(
t
,
y
(
t
)
)
{\displaystyle {\frac {dy(t)}{dt}}=f(t,y(t))}
with an initial value
y
(
t
0
)
=
y
0
{\displaystyle y(t_{0})=y_{0}}
To get a numeric solution, we replace the derivative on the LHS with a finite difference approximation:
d
y
(
t
)
d
t
≈
y
(
t
+
h
)
−
y
(
t
)
h
{\displaystyle {\frac {dy(t)}{dt}}\approx {\frac {y(t+h)-y(t)}{h}}}
then solve for
y
(
t
+
h
)
{\displaystyle y(t+h)}
:
y
(
t
+
h
)
≈
y
(
t
)
+
h
d
y
(
t
)
d
t
{\displaystyle y(t+h)\approx y(t)+h\,{\frac {dy(t)}{dt}}}
which is the same as
y
(
t
+
h
)
≈
y
(
t
)
+
h
f
(
t
,
y
(
t
)
)
{\displaystyle y(t+h)\approx y(t)+h\,f(t,y(t))}
The iterative solution rule is then:
y
n
+
1
=
y
n
+
h
f
(
t
n
,
y
n
)
{\displaystyle y_{n+1}=y_{n}+h\,f(t_{n},y_{n})}
where
h
{\displaystyle h}
is the step size, the most relevant parameter for accuracy of the solution. A smaller step size increases accuracy but also the computation cost, so it has always has to be hand-picked according to the problem at hand.
Example: Newton's Cooling Law
Newton's cooling law describes how an object of initial temperature
T
(
t
0
)
=
T
0
{\displaystyle T(t_{0})=T_{0}}
cools down in an environment of temperature
T
R
{\displaystyle T_{R}}
:
d
T
(
t
)
d
t
=
−
k
Δ
T
{\displaystyle {\frac {dT(t)}{dt}}=-k\,\Delta T}
or
d
T
(
t
)
d
t
=
−
k
(
T
(
t
)
−
T
R
)
{\displaystyle {\frac {dT(t)}{dt}}=-k\,(T(t)-T_{R})}
It says that the cooling rate
d
T
(
t
)
d
t
{\displaystyle {\frac {dT(t)}{dt}}}
of the object is proportional to the current temperature difference
Δ
T
=
(
T
(
t
)
−
T
R
)
{\displaystyle \Delta T=(T(t)-T_{R})}
to the surrounding environment.
The analytical solution, which we will compare to the numerical approximation, is
T
(
t
)
=
T
R
+
(
T
0
−
T
R
)
e
−
k
t
{\displaystyle T(t)=T_{R}+(T_{0}-T_{R})\;e^{-kt}}
Task
Implement a routine of Euler's method and then to use it to solve the given example of Newton's cooling law with it for three different step sizes of:
2 s
5 s and
10 s
and to compare with the analytical solution.
Initial values
initial temperature
T
0
{\displaystyle T_{0}}
shall be 100 °C
room temperature
T
R
{\displaystyle T_{R}}
shall be 20 °C
cooling constant
k
{\displaystyle k}
shall be 0.07
time interval to calculate shall be from 0 s ──► 100 s
A reference solution (Common Lisp) can be seen below. We see that bigger step sizes lead to reduced approximation accuracy.
| #Euler_Math_Toolbox | Euler Math Toolbox |
>function dgleuler (f,x,y0) ...
$ y=zeros(size(x)); y[1]=y0;
$ for i=2 to cols(y);
$ y[i]=y[i-1]+f(x[i-1],y[i-1])*(x[i]-x[i-1]);
$ end;
$ return y;
$endfunction
>function f(x,y) := -k*(y-TR)
>k=0.07; TR=20; TS=100;
>x=0:1:100; dgleuler("f",x,TS)[-1]
20.0564137335
>x=0:2:100; dgleuler("f",x,TS)[-1]
20.0424631834
>TR+(TS-TR)*exp(-k*TS)
20.0729505572
>x=0:5:100; plot2d(x,dgleuler("f",x,TS)); ...
> plot2d(x,TR+(TS-TR)*exp(-k*x),>add,color=red);
>ode("f",x,TS)[-1] // Euler default solver LSODA
20.0729505568
>adaptiverunge("f",x,TS)[-1] // Adaptive Runge Method
20.0729505572
|
http://rosettacode.org/wiki/Euler_method | Euler method | Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value. It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page.
The ODE has to be provided in the following form:
d
y
(
t
)
d
t
=
f
(
t
,
y
(
t
)
)
{\displaystyle {\frac {dy(t)}{dt}}=f(t,y(t))}
with an initial value
y
(
t
0
)
=
y
0
{\displaystyle y(t_{0})=y_{0}}
To get a numeric solution, we replace the derivative on the LHS with a finite difference approximation:
d
y
(
t
)
d
t
≈
y
(
t
+
h
)
−
y
(
t
)
h
{\displaystyle {\frac {dy(t)}{dt}}\approx {\frac {y(t+h)-y(t)}{h}}}
then solve for
y
(
t
+
h
)
{\displaystyle y(t+h)}
:
y
(
t
+
h
)
≈
y
(
t
)
+
h
d
y
(
t
)
d
t
{\displaystyle y(t+h)\approx y(t)+h\,{\frac {dy(t)}{dt}}}
which is the same as
y
(
t
+
h
)
≈
y
(
t
)
+
h
f
(
t
,
y
(
t
)
)
{\displaystyle y(t+h)\approx y(t)+h\,f(t,y(t))}
The iterative solution rule is then:
y
n
+
1
=
y
n
+
h
f
(
t
n
,
y
n
)
{\displaystyle y_{n+1}=y_{n}+h\,f(t_{n},y_{n})}
where
h
{\displaystyle h}
is the step size, the most relevant parameter for accuracy of the solution. A smaller step size increases accuracy but also the computation cost, so it has always has to be hand-picked according to the problem at hand.
Example: Newton's Cooling Law
Newton's cooling law describes how an object of initial temperature
T
(
t
0
)
=
T
0
{\displaystyle T(t_{0})=T_{0}}
cools down in an environment of temperature
T
R
{\displaystyle T_{R}}
:
d
T
(
t
)
d
t
=
−
k
Δ
T
{\displaystyle {\frac {dT(t)}{dt}}=-k\,\Delta T}
or
d
T
(
t
)
d
t
=
−
k
(
T
(
t
)
−
T
R
)
{\displaystyle {\frac {dT(t)}{dt}}=-k\,(T(t)-T_{R})}
It says that the cooling rate
d
T
(
t
)
d
t
{\displaystyle {\frac {dT(t)}{dt}}}
of the object is proportional to the current temperature difference
Δ
T
=
(
T
(
t
)
−
T
R
)
{\displaystyle \Delta T=(T(t)-T_{R})}
to the surrounding environment.
The analytical solution, which we will compare to the numerical approximation, is
T
(
t
)
=
T
R
+
(
T
0
−
T
R
)
e
−
k
t
{\displaystyle T(t)=T_{R}+(T_{0}-T_{R})\;e^{-kt}}
Task
Implement a routine of Euler's method and then to use it to solve the given example of Newton's cooling law with it for three different step sizes of:
2 s
5 s and
10 s
and to compare with the analytical solution.
Initial values
initial temperature
T
0
{\displaystyle T_{0}}
shall be 100 °C
room temperature
T
R
{\displaystyle T_{R}}
shall be 20 °C
cooling constant
k
{\displaystyle k}
shall be 0.07
time interval to calculate shall be from 0 s ──► 100 s
A reference solution (Common Lisp) can be seen below. We see that bigger step sizes lead to reduced approximation accuracy.
| #F.23 | F# | let euler f (h : float) t0 y0 =
(t0, y0)
|> Seq.unfold (fun (t, y) -> Some((t,y), ((t + h), (y + h * (f t y)))))
let newtonCoolíng _ y = -0.07 * (y - 20.0)
[<EntryPoint>]
let main argv =
let f = newtonCoolíng
let a = 0.0
let y0 = 100.0
let b = 100.0
let h = 10.0
(euler newtonCoolíng h a y0)
|> Seq.takeWhile (fun (t,_) -> t <= b)
|> Seq.iter (printfn "%A")
0 |
http://rosettacode.org/wiki/Evaluate_binomial_coefficients | Evaluate binomial coefficients | This programming task, is to calculate ANY binomial coefficient.
However, it has to be able to output
(
5
3
)
{\displaystyle {\binom {5}{3}}}
, which is 10.
This formula is recommended:
(
n
k
)
=
n
!
(
n
−
k
)
!
k
!
=
n
(
n
−
1
)
(
n
−
2
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
(
k
−
2
)
…
1
{\displaystyle {\binom {n}{k}}={\frac {n!}{(n-k)!k!}}={\frac {n(n-1)(n-2)\ldots (n-k+1)}{k(k-1)(k-2)\ldots 1}}}
See Also:
Combinations and permutations
Pascal's triangle
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #AppleScript | AppleScript | set n to 5
set k to 3
on calculateFactorial(val)
set partial_factorial to 1 as integer
repeat with i from 1 to val
set factorial to i * partial_factorial
set partial_factorial to factorial
end repeat
return factorial
end calculateFactorial
set n_factorial to calculateFactorial(n)
set k_factorial to calculateFactorial(k)
set n_minus_k_factorial to calculateFactorial(n - k)
return n_factorial / (n_minus_k_factorial) * 1 / (k_factorial) as integer
|
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
Fn = Fn+2 - Fn+1, if n<0
support for negative n in the solution is optional.
Related tasks
Fibonacci n-step number sequences
Leonardo numbers
References
Wikipedia, Fibonacci number
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #Ursala | Ursala | #import std
#import nat
iterative_fib = ~&/(0,1); ~&r->ll ^|\predecessor ^/~&r sum
recursive_fib = {0,1}^?<a/~&a sum^|W/~& predecessor^~/~& predecessor
analytical_fib =
%np+ -+
mp..round; ..mp2str; sep`+; ^CNC/~&hh take^\~&htt %np@t,
(mp..div^|\~& mp..sub+ ~~ @rlX mp..pow_ui)^lrlPGrrPX/~& -+
^\~& ^(~&,mp..sub/1.E0)+ mp..div\2.E0+ mp..add/1.E0,
mp..sqrt+ ..grow/5.E0+-+- |
http://rosettacode.org/wiki/Equal_prime_and_composite_sums | Equal prime and composite sums | Suppose we have a sequence of prime sums, where each term Pn is the sum of the first n primes.
P = (2), (2 + 3), (2 + 3 + 5), (2 + 3 + 5 + 7), (2 + 3 + 5 + 7 + 11), ...
P = 2, 5, 10, 17, 28, etc.
Further; suppose we have a sequence of composite sums, where each term Cm is the sum of the first m composites.
C = (4), (4 + 6), (4 + 6 + 8), (4 + 6 + 8 + 9), (4 + 6 + 8 + 9 + 10), ...
C = 4, 10, 18, 27, 37, etc.
Notice that the third term of P; P3 (10) is equal to the second term of C; C2 (10);
Task
Find and display the indices (n, m) and value of at least the first 6 terms of the sequence of numbers that are both the sum of the first n primes and the first m composites.
See also
OEIS:A007504 - Sum of the first n primes
OEIS:A053767 - Sum of first n composite numbers
OEIS:A294174 - Numbers that can be expressed both as the sum of first primes and as the sum of first composites
| #F.23 | F# |
// Equal prime and composite sums. Nigel Galloway: March 3rd., 2022
let fN(g:seq<int64>)=let g=(g|>Seq.scan(fun(_,n,i) g->(g,n+g,i+1))(0,0L,0)|>Seq.skip 1).GetEnumerator() in (fun()->g.MoveNext()|>ignore; g.Current)
let fG n g=let rec fG a b=seq{match a,b with ((_,p,_),(_,c,_)) when p<c->yield! fG(n()) b |((_,p,_),(_,c,_)) when p>c->yield! fG a (g()) |_->yield(a,b); yield! fG(n())(g())} in fG(n())(g())
fG(fN(primes64()))(fN(primes64()|>Seq.pairwise|>Seq.collect(fun(n,g)->[1L+n..g-1L])))|>Seq.take 11|>Seq.iter(fun((n,i,g),(e,_,l))->printfn $"Primes up to %d{n} at position %d{g} and composites up to %d{e} at position %d{l} sum to %d{i}.")
|
http://rosettacode.org/wiki/Equal_prime_and_composite_sums | Equal prime and composite sums | Suppose we have a sequence of prime sums, where each term Pn is the sum of the first n primes.
P = (2), (2 + 3), (2 + 3 + 5), (2 + 3 + 5 + 7), (2 + 3 + 5 + 7 + 11), ...
P = 2, 5, 10, 17, 28, etc.
Further; suppose we have a sequence of composite sums, where each term Cm is the sum of the first m composites.
C = (4), (4 + 6), (4 + 6 + 8), (4 + 6 + 8 + 9), (4 + 6 + 8 + 9 + 10), ...
C = 4, 10, 18, 27, 37, etc.
Notice that the third term of P; P3 (10) is equal to the second term of C; C2 (10);
Task
Find and display the indices (n, m) and value of at least the first 6 terms of the sequence of numbers that are both the sum of the first n primes and the first m composites.
See also
OEIS:A007504 - Sum of the first n primes
OEIS:A053767 - Sum of first n composite numbers
OEIS:A294174 - Numbers that can be expressed both as the sum of first primes and as the sum of first composites
| #FreeBASIC | FreeBASIC | #include "isprime.bas"
Dim As Integer i = 0
Dim As Integer IndN = 1, IndM = 1
Dim As Integer NumP = 2, NumC = 4
Dim As Integer SumP = 2, SumC = 4
Print " sum prime sum composite sum"
Do
If SumC > SumP Then
Do
NumP += 1
Loop Until isPrime(NumP)
SumP += NumP
IndN += 1
End If
If SumP > SumC Then
Do
NumC += 1
Loop Until Not isPrime(NumC)
SumC += NumC
IndM += 1
End If
If SumP = SumC Then
Print Using "##,###,###,###,### - ##,###,### - ##,###,###"; SumP; IndN; IndM
i += 1
If i >= 9 Then Exit Do
Do
NumC += 1
Loop Until Not isPrime(NumC)
SumC += NumC
IndM += 1
End If
Loop |
http://rosettacode.org/wiki/Esthetic_numbers | Esthetic numbers | An esthetic number is a positive integer where every adjacent digit differs from its neighbour by 1.
E.G.
12 is an esthetic number. One and two differ by 1.
5654 is an esthetic number. Each digit is exactly 1 away from its neighbour.
890 is not an esthetic number. Nine and zero differ by 9.
These examples are nominally in base 10 but the concept extends easily to numbers in other bases. Traditionally, single digit numbers are included in esthetic numbers; zero may or may not be. For our purposes, for this task, do not include zero (0) as an esthetic number. Do not include numbers with leading zeros.
Esthetic numbers are also sometimes referred to as stepping numbers.
Task
Write a routine (function, procedure, whatever) to find esthetic numbers in a given base.
Use that routine to find esthetic numbers in bases 2 through 16 and display, here on this page, the esthectic numbers from index (base × 4) through index (base × 6), inclusive. (E.G. for base 2: 8th through 12th, for base 6: 24th through 36th, etc.)
Find and display, here on this page, the base 10 esthetic numbers with a magnitude between 1000 and 9999.
Stretch: Find and display, here on this page, the base 10 esthetic numbers with a magnitude between 1.0e8 and 1.3e8.
Related task
numbers with equal rises and falls
See also
OEIS A033075 - Positive numbers n such that all pairs of consecutive decimal digits differ by 1
Numbers Aplenty - Esthetic numbers
Geeks for Geeks - Stepping numbers
| #Factor | Factor | USING: combinators deques dlists formatting grouping io kernel
locals make math math.order math.parser math.ranges
math.text.english prettyprint sequences sorting strings ;
:: bfs ( from to num base -- )
DL{ } clone :> q
base 1 - :> ld
num q push-front
[ q deque-empty? ]
[
q pop-back :> step-num
step-num from to between? [ step-num , ] when
step-num zero? step-num to > or
[
step-num base mod :> last-digit
step-num base * last-digit 1 - + :> a
step-num base * last-digit 1 + + :> b
last-digit
{
{ 0 [ b q push-front ] }
{ ld [ a q push-front ] }
[ drop a q push-front b q push-front ]
} case
] unless
] until ;
:: esthetics ( from to base -- seq )
[ base <iota> [| num | from to num base bfs ] each ]
{ } make natural-sort ;
: .seq ( seq width -- )
group [ [ dup string? [ write ] [ pprint ] if bl ] each nl ]
each nl ;
:: show ( base -- )
base [ 4 * ] [ 6 * ] bi :> ( from to )
from to [ dup ordinal-suffix ] bi@ base
"%d%s through %d%s esthetic numbers in base %d\n" printf
from to 1 + 0 5000 ! enough for base 16
base esthetics subseq [ base >base ] map 17 .seq ;
2 16 [a,b] [ show ] each
"Base 10 numbers between 1,000 and 9,999:" print
1,000 9,999 10 esthetics 16 .seq
"Base 10 numbers between 100,000,000 and 130,000,000:" print
100,000,000 130,000,000 10 esthetics 9 .seq
"Count of base 10 esthetic numbers between zero and one quadrillion:"
print 0 1e15 10 esthetics length . |
http://rosettacode.org/wiki/Euler%27s_sum_of_powers_conjecture | Euler's sum of powers conjecture | There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin.
Euler's (disproved) sum of powers conjecture
At least k positive kth powers are required to sum to a kth power,
except for the trivial case of one kth power: yk = yk
In 1966, Leon J. Lander and Thomas R. Parkin used a brute-force search on a CDC 6600 computer restricting numbers to those less than 250.
Task
Write a program to search for an integer solution for:
x05 + x15 + x25 + x35 == y5
Where all xi's and y are distinct integers between 0 and 250 (exclusive).
Show an answer here.
Related tasks
Pythagorean quadruples.
Pythagorean triples.
| #6502_Assembly | 6502 Assembly | ; Prove Euler's sum of powers conjecture false by finding
; positive a,b,c,d,e such that a⁵+b⁵+c⁵+d⁵=e⁵.
; we're only looking for the first counterexample, which occurs with all
; integers less than this value
max_value = $fa ; decimal 250
; this header turns our code into a LOADable and RUNnable BASIC program
.include "basic_header.s"
; this contains the first 256 integers to the power of 5 broken up into
; 5 tables of one-byte values (power5byte0 with the LSBs through
; power5byte4 with the MSBs)
.include "power5table.s"
; this defines subroutines and macros for printing messages to
; the console, including `puts` for printing out a NUL-terminated string,
; puthex to display a one-byte value in hexadecimal, and putdec through
; putdec5 to display an N-byte value in decimal
.include "output.s"
; label strings for the result output
.feature string_escapes
success: .asciiz "\r\rFOUND EXAMPLE:\r\r"
between: .asciiz "^5 + "
penult: .asciiz "^5 = "
eqend: .asciiz "^5\r\r(SUM IS "
; the BASIC loader program prints the elapsed time at the end, so we include a
; label for that, too
tilabel: .asciiz ")\r\rTIME:"
; ZP locations to store the integers to try
x0 = $f7
x1 = x0 + 1
x2 = x0 + 2
x3 = x0 + 3
; we use binary search to find integer roots; current bounds go here
low = x0 + 4
hi = x0 + 5
; sum of powers of current candidate integers
sum: .res 5
; when we find a sum with an integer 5th root, we put it here
x4: .res 1
main: ; loop for x0 from 1 to max_value
ldx #01
stx x0
loop0: ; loop for x1 from x0+1 to max_value
ldx x0
inx
stx x1
loop1: ; loop for x2 from x1+1 to max_value
ldx x1
inx
stx x2
loop2: ; loop for x3 from x2+1 to max_value
ldx x2
inx
stx x3
loop3: ; add up the fifth powers of the four numbers
; initialize to 0
lda #00
sta sum
sta sum+1
sta sum+2
sta sum+3
sta sum+4
; we use indexed addressing, taking advantage of the fact that the xn's
; are consecutive, so x0,1 = x1, etc.
ldy #0
addloop:
ldx x0,y
lda sum
clc
adc power5byte0,x
sta sum
lda sum+1
adc power5byte1,x
sta sum+1
lda sum+2
adc power5byte2,x
sta sum+2
lda sum+3
adc power5byte3,x
sta sum+3
lda sum+4
adc power5byte4,x
sta sum+4
iny
cpy #4
bcc addloop
; now sum := x₀⁵+x₁⁵+x₂⁵+x₃⁵
; set initial bounds for binary search
ldx x3
inx
stx low
ldx #max_value
dex
stx hi
binsearch:
; compute midpoint
lda low
cmp hi
beq notdone
bcs done_search
notdone:
ldx #0
clc
adc hi
; now a + carry bit = low+hi; rotating right will get the midpoint
ror
; compare square of midpoint to sum
tax
lda sum+4
cmp power5byte4,x
bne notyet
lda sum+3
cmp power5byte3,x
bne notyet
lda sum+2
cmp power5byte2,x
bne notyet
lda sum+1
cmp power5byte1,x
bne notyet
lda sum
cmp power5byte0,x
beq found
notyet:
bcc sum_lt_guess
inx
stx low
bne endbin
beq endbin
sum_lt_guess:
dex
stx hi
endbin:
bne binsearch
beq binsearch
done_search:
inc x3
lda x3
cmp #max_value
bcs end_loop3
jmp loop3
end_loop3:
inc x2
lda x2
cmp #max_value
bcs end_loop2
jmp loop2
end_loop2:
inc x1
lda x1
cmp #max_value
bcs end_loop1
jmp loop1
end_loop1:
inc x0
lda x0
cmp #max_value
bcs end_loop0
jmp loop0
end_loop0:
; should never get here, means we didn't find an example.
brk
found: stx x4
puts success
putdec x0
ldy #1
ploop: puts between
putdec {x0,y}
iny
cpy #4
bcc ploop
puts penult
putdec {x0,y}
puts eqend
putdec5 sum
puts tilabel
rts |
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
| #MATLAB | MATLAB | answer = factorial(N) |
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.
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B and android arm 64 bits*/
/* program oddEven64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/*********************************/
/* Initialized data */
/*********************************/
.data
sMessResultOdd: .asciz " @ is odd (impair) \n"
sMessResultEven: .asciz " @ is even (pair) \n"
szCarriageReturn: .asciz "\n"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: //entry of program
mov x0,#5
bl testOddEven
mov x0,#12
bl testOddEven
mov x0,#2021
bl testOddEven
100: //standard end of the program
mov x0, #0 //return code
mov x8, #EXIT //request to exit program
svc #0 //perform the system call
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrsMessResultOdd: .quad sMessResultOdd
qAdrsMessResultEven: .quad sMessResultEven
qAdrsZoneConv: .quad sZoneConv
/***************************************************/
/* test if number is odd or even */
/***************************************************/
// x0 contains à number
testOddEven:
stp x1,lr,[sp,-16]! // save registres
tst x0,#1 //test bit 0 to one
beq 1f //if result are all zéro, go to even
ldr x1,qAdrsZoneConv //else display odd message
bl conversion10 //call decimal conversion
ldr x0,qAdrsMessResultOdd
ldr x1,qAdrsZoneConv //insert value conversion in message
bl strInsertAtCharInc
bl affichageMess
b 100f
1:
ldr x1,qAdrsZoneConv
bl conversion10 //call decimal conversion
ldr x0,qAdrsMessResultEven
ldr x1,qAdrsZoneConv //insert conversion in message
bl strInsertAtCharInc
bl affichageMess
100:
ldp x1,lr,[sp],16 // restaur des 2 registres
ret
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
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.
| #ABAP | ABAP |
cl_demo_output=>display(
VALUE string_table(
FOR i = -5 WHILE i < 6 (
COND string(
LET r = i MOD 2 IN
WHEN r = 0 THEN |{ i } is even|
ELSE |{ i } is odd|
)
)
)
).
|
http://rosettacode.org/wiki/Euler_method | Euler method | Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value. It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page.
The ODE has to be provided in the following form:
d
y
(
t
)
d
t
=
f
(
t
,
y
(
t
)
)
{\displaystyle {\frac {dy(t)}{dt}}=f(t,y(t))}
with an initial value
y
(
t
0
)
=
y
0
{\displaystyle y(t_{0})=y_{0}}
To get a numeric solution, we replace the derivative on the LHS with a finite difference approximation:
d
y
(
t
)
d
t
≈
y
(
t
+
h
)
−
y
(
t
)
h
{\displaystyle {\frac {dy(t)}{dt}}\approx {\frac {y(t+h)-y(t)}{h}}}
then solve for
y
(
t
+
h
)
{\displaystyle y(t+h)}
:
y
(
t
+
h
)
≈
y
(
t
)
+
h
d
y
(
t
)
d
t
{\displaystyle y(t+h)\approx y(t)+h\,{\frac {dy(t)}{dt}}}
which is the same as
y
(
t
+
h
)
≈
y
(
t
)
+
h
f
(
t
,
y
(
t
)
)
{\displaystyle y(t+h)\approx y(t)+h\,f(t,y(t))}
The iterative solution rule is then:
y
n
+
1
=
y
n
+
h
f
(
t
n
,
y
n
)
{\displaystyle y_{n+1}=y_{n}+h\,f(t_{n},y_{n})}
where
h
{\displaystyle h}
is the step size, the most relevant parameter for accuracy of the solution. A smaller step size increases accuracy but also the computation cost, so it has always has to be hand-picked according to the problem at hand.
Example: Newton's Cooling Law
Newton's cooling law describes how an object of initial temperature
T
(
t
0
)
=
T
0
{\displaystyle T(t_{0})=T_{0}}
cools down in an environment of temperature
T
R
{\displaystyle T_{R}}
:
d
T
(
t
)
d
t
=
−
k
Δ
T
{\displaystyle {\frac {dT(t)}{dt}}=-k\,\Delta T}
or
d
T
(
t
)
d
t
=
−
k
(
T
(
t
)
−
T
R
)
{\displaystyle {\frac {dT(t)}{dt}}=-k\,(T(t)-T_{R})}
It says that the cooling rate
d
T
(
t
)
d
t
{\displaystyle {\frac {dT(t)}{dt}}}
of the object is proportional to the current temperature difference
Δ
T
=
(
T
(
t
)
−
T
R
)
{\displaystyle \Delta T=(T(t)-T_{R})}
to the surrounding environment.
The analytical solution, which we will compare to the numerical approximation, is
T
(
t
)
=
T
R
+
(
T
0
−
T
R
)
e
−
k
t
{\displaystyle T(t)=T_{R}+(T_{0}-T_{R})\;e^{-kt}}
Task
Implement a routine of Euler's method and then to use it to solve the given example of Newton's cooling law with it for three different step sizes of:
2 s
5 s and
10 s
and to compare with the analytical solution.
Initial values
initial temperature
T
0
{\displaystyle T_{0}}
shall be 100 °C
room temperature
T
R
{\displaystyle T_{R}}
shall be 20 °C
cooling constant
k
{\displaystyle k}
shall be 0.07
time interval to calculate shall be from 0 s ──► 100 s
A reference solution (Common Lisp) can be seen below. We see that bigger step sizes lead to reduced approximation accuracy.
| #Factor | Factor | USING: formatting fry io kernel locals math math.ranges
sequences ;
IN: rosetta-code.euler-method
:: euler ( quot y! a b h -- )
a b h <range> [
:> t
t y "%7.3f %7.3f\n" printf
t y quot call h * y + y!
] each ; inline
: cooling ( t y -- x ) nip 20 - -0.07 * ;
: euler-method-demo ( -- )
2 5 10 [ '[ [ cooling ] 100 0 100 _ euler ] call nl ] tri@ ;
MAIN: euler-method-demo |
http://rosettacode.org/wiki/Euler_method | Euler method | Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value. It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page.
The ODE has to be provided in the following form:
d
y
(
t
)
d
t
=
f
(
t
,
y
(
t
)
)
{\displaystyle {\frac {dy(t)}{dt}}=f(t,y(t))}
with an initial value
y
(
t
0
)
=
y
0
{\displaystyle y(t_{0})=y_{0}}
To get a numeric solution, we replace the derivative on the LHS with a finite difference approximation:
d
y
(
t
)
d
t
≈
y
(
t
+
h
)
−
y
(
t
)
h
{\displaystyle {\frac {dy(t)}{dt}}\approx {\frac {y(t+h)-y(t)}{h}}}
then solve for
y
(
t
+
h
)
{\displaystyle y(t+h)}
:
y
(
t
+
h
)
≈
y
(
t
)
+
h
d
y
(
t
)
d
t
{\displaystyle y(t+h)\approx y(t)+h\,{\frac {dy(t)}{dt}}}
which is the same as
y
(
t
+
h
)
≈
y
(
t
)
+
h
f
(
t
,
y
(
t
)
)
{\displaystyle y(t+h)\approx y(t)+h\,f(t,y(t))}
The iterative solution rule is then:
y
n
+
1
=
y
n
+
h
f
(
t
n
,
y
n
)
{\displaystyle y_{n+1}=y_{n}+h\,f(t_{n},y_{n})}
where
h
{\displaystyle h}
is the step size, the most relevant parameter for accuracy of the solution. A smaller step size increases accuracy but also the computation cost, so it has always has to be hand-picked according to the problem at hand.
Example: Newton's Cooling Law
Newton's cooling law describes how an object of initial temperature
T
(
t
0
)
=
T
0
{\displaystyle T(t_{0})=T_{0}}
cools down in an environment of temperature
T
R
{\displaystyle T_{R}}
:
d
T
(
t
)
d
t
=
−
k
Δ
T
{\displaystyle {\frac {dT(t)}{dt}}=-k\,\Delta T}
or
d
T
(
t
)
d
t
=
−
k
(
T
(
t
)
−
T
R
)
{\displaystyle {\frac {dT(t)}{dt}}=-k\,(T(t)-T_{R})}
It says that the cooling rate
d
T
(
t
)
d
t
{\displaystyle {\frac {dT(t)}{dt}}}
of the object is proportional to the current temperature difference
Δ
T
=
(
T
(
t
)
−
T
R
)
{\displaystyle \Delta T=(T(t)-T_{R})}
to the surrounding environment.
The analytical solution, which we will compare to the numerical approximation, is
T
(
t
)
=
T
R
+
(
T
0
−
T
R
)
e
−
k
t
{\displaystyle T(t)=T_{R}+(T_{0}-T_{R})\;e^{-kt}}
Task
Implement a routine of Euler's method and then to use it to solve the given example of Newton's cooling law with it for three different step sizes of:
2 s
5 s and
10 s
and to compare with the analytical solution.
Initial values
initial temperature
T
0
{\displaystyle T_{0}}
shall be 100 °C
room temperature
T
R
{\displaystyle T_{R}}
shall be 20 °C
cooling constant
k
{\displaystyle k}
shall be 0.07
time interval to calculate shall be from 0 s ──► 100 s
A reference solution (Common Lisp) can be seen below. We see that bigger step sizes lead to reduced approximation accuracy.
| #Forth | Forth | : newton-cooling-law ( f: temp -- f: temp' )
20e f- -0.07e f* ;
: euler ( f: y0 xt step end -- )
1+ 0 do
cr i . fdup f.
fdup over execute
dup s>f f* f+
dup +loop
2drop fdrop ;
100e ' newton-cooling-law 2 100 euler cr
100e ' newton-cooling-law 5 100 euler cr
100e ' newton-cooling-law 10 100 euler cr |
http://rosettacode.org/wiki/Evaluate_binomial_coefficients | Evaluate binomial coefficients | This programming task, is to calculate ANY binomial coefficient.
However, it has to be able to output
(
5
3
)
{\displaystyle {\binom {5}{3}}}
, which is 10.
This formula is recommended:
(
n
k
)
=
n
!
(
n
−
k
)
!
k
!
=
n
(
n
−
1
)
(
n
−
2
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
(
k
−
2
)
…
1
{\displaystyle {\binom {n}{k}}={\frac {n!}{(n-k)!k!}}={\frac {n(n-1)(n-2)\ldots (n-k+1)}{k(k-1)(k-2)\ldots 1}}}
See Also:
Combinations and permutations
Pascal's triangle
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #Arturo | Arturo | factorial: function [n]-> product 1..n
binomial: function [x,y]-> (factorial x) / (factorial y) * factorial x-y
print binomial 5 3 |
http://rosettacode.org/wiki/Evaluate_binomial_coefficients | Evaluate binomial coefficients | This programming task, is to calculate ANY binomial coefficient.
However, it has to be able to output
(
5
3
)
{\displaystyle {\binom {5}{3}}}
, which is 10.
This formula is recommended:
(
n
k
)
=
n
!
(
n
−
k
)
!
k
!
=
n
(
n
−
1
)
(
n
−
2
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
(
k
−
2
)
…
1
{\displaystyle {\binom {n}{k}}={\frac {n!}{(n-k)!k!}}={\frac {n(n-1)(n-2)\ldots (n-k+1)}{k(k-1)(k-2)\ldots 1}}}
See Also:
Combinations and permutations
Pascal's triangle
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #AutoHotkey | AutoHotkey | MsgBox, % Round(BinomialCoefficient(5, 3))
;---------------------------------------------------------------------------
BinomialCoefficient(n, k) {
;---------------------------------------------------------------------------
r := 1
Loop, % k < n - k ? k : n - k {
r *= n - A_Index + 1
r /= A_Index
}
Return, r
} |
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
Fn = Fn+2 - Fn+1, if n<0
support for negative n in the solution is optional.
Related tasks
Fibonacci n-step number sequences
Leonardo numbers
References
Wikipedia, Fibonacci number
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #V | V | [fib
[small?] []
[pred dup pred]
[+]
binrec]. |
http://rosettacode.org/wiki/Equal_prime_and_composite_sums | Equal prime and composite sums | Suppose we have a sequence of prime sums, where each term Pn is the sum of the first n primes.
P = (2), (2 + 3), (2 + 3 + 5), (2 + 3 + 5 + 7), (2 + 3 + 5 + 7 + 11), ...
P = 2, 5, 10, 17, 28, etc.
Further; suppose we have a sequence of composite sums, where each term Cm is the sum of the first m composites.
C = (4), (4 + 6), (4 + 6 + 8), (4 + 6 + 8 + 9), (4 + 6 + 8 + 9 + 10), ...
C = 4, 10, 18, 27, 37, etc.
Notice that the third term of P; P3 (10) is equal to the second term of C; C2 (10);
Task
Find and display the indices (n, m) and value of at least the first 6 terms of the sequence of numbers that are both the sum of the first n primes and the first m composites.
See also
OEIS:A007504 - Sum of the first n primes
OEIS:A053767 - Sum of first n composite numbers
OEIS:A294174 - Numbers that can be expressed both as the sum of first primes and as the sum of first composites
| #Go | Go | package main
import (
"fmt"
"log"
"rcu"
"sort"
)
func ord(n int) string {
if n < 0 {
log.Fatal("Argument must be a non-negative integer.")
}
m := n % 100
if m >= 4 && m <= 20 {
return fmt.Sprintf("%sth", rcu.Commatize(n))
}
m %= 10
suffix := "th"
if m == 1 {
suffix = "st"
} else if m == 2 {
suffix = "nd"
} else if m == 3 {
suffix = "rd"
}
return fmt.Sprintf("%s%s", rcu.Commatize(n), suffix)
}
func main() {
limit := int(4 * 1e8)
c := rcu.PrimeSieve(limit-1, true)
var compSums []int
var primeSums []int
csum := 0
psum := 0
for i := 2; i < limit; i++ {
if c[i] {
csum += i
compSums = append(compSums, csum)
} else {
psum += i
primeSums = append(primeSums, psum)
}
}
for i := 0; i < len(primeSums); i++ {
ix := sort.SearchInts(compSums, primeSums[i])
if ix < len(compSums) && compSums[ix] == primeSums[i] {
cps := rcu.Commatize(primeSums[i])
fmt.Printf("%21s - %12s prime sum, %12s composite sum\n", cps, ord(i+1), ord(ix+1))
}
}
} |
http://rosettacode.org/wiki/Equal_prime_and_composite_sums | Equal prime and composite sums | Suppose we have a sequence of prime sums, where each term Pn is the sum of the first n primes.
P = (2), (2 + 3), (2 + 3 + 5), (2 + 3 + 5 + 7), (2 + 3 + 5 + 7 + 11), ...
P = 2, 5, 10, 17, 28, etc.
Further; suppose we have a sequence of composite sums, where each term Cm is the sum of the first m composites.
C = (4), (4 + 6), (4 + 6 + 8), (4 + 6 + 8 + 9), (4 + 6 + 8 + 9 + 10), ...
C = 4, 10, 18, 27, 37, etc.
Notice that the third term of P; P3 (10) is equal to the second term of C; C2 (10);
Task
Find and display the indices (n, m) and value of at least the first 6 terms of the sequence of numbers that are both the sum of the first n primes and the first m composites.
See also
OEIS:A007504 - Sum of the first n primes
OEIS:A053767 - Sum of first n composite numbers
OEIS:A294174 - Numbers that can be expressed both as the sum of first primes and as the sum of first composites
| #J | J | Pn=: +/\ pn=: p: i.1e6 NB. first million primes pn and their running sum Pn
Cn=: +/\(4+i.{:pn)-.pn NB. running sum of composites starting at 4 and excluding those primes
both=: Pn(e.#[)Cn NB. numbers in both sequences
both,.(Pn i.both),.Cn i.both NB. values, Pn index m, Cn index n
10 2 1
1988 32 50
14697 79 146
83292 174 360
1503397 659 1581
18859052 2142 5698
93952013 4555 12820
89171409882 118784 403340 |
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
| #11l | 11l | F halve(x)
R x I/ 2
F double(x)
R x * 2
F even(x)
R !(x % 2)
F ethiopian(=multiplier, =multiplicand)
V result = 0
L multiplier >= 1
I !even(multiplier)
result += multiplicand
multiplier = halve(multiplier)
multiplicand = double(multiplicand)
R result
print(ethiopian(17, 34)) |
http://rosettacode.org/wiki/Esthetic_numbers | Esthetic numbers | An esthetic number is a positive integer where every adjacent digit differs from its neighbour by 1.
E.G.
12 is an esthetic number. One and two differ by 1.
5654 is an esthetic number. Each digit is exactly 1 away from its neighbour.
890 is not an esthetic number. Nine and zero differ by 9.
These examples are nominally in base 10 but the concept extends easily to numbers in other bases. Traditionally, single digit numbers are included in esthetic numbers; zero may or may not be. For our purposes, for this task, do not include zero (0) as an esthetic number. Do not include numbers with leading zeros.
Esthetic numbers are also sometimes referred to as stepping numbers.
Task
Write a routine (function, procedure, whatever) to find esthetic numbers in a given base.
Use that routine to find esthetic numbers in bases 2 through 16 and display, here on this page, the esthectic numbers from index (base × 4) through index (base × 6), inclusive. (E.G. for base 2: 8th through 12th, for base 6: 24th through 36th, etc.)
Find and display, here on this page, the base 10 esthetic numbers with a magnitude between 1000 and 9999.
Stretch: Find and display, here on this page, the base 10 esthetic numbers with a magnitude between 1.0e8 and 1.3e8.
Related task
numbers with equal rises and falls
See also
OEIS A033075 - Positive numbers n such that all pairs of consecutive decimal digits differ by 1
Numbers Aplenty - Esthetic numbers
Geeks for Geeks - Stepping numbers
| #Forth | Forth | \ Returns the next esthetic number in the given base after n, where n is an
\ esthetic number in that base or one less than a power of base.
: next_esthetic_number { n base -- n }
n 1+ base < if n 1+ exit then
n base / dup base mod
dup n base mod 1+ = if dup 1+ base < if 2drop n 2 + exit then then
drop base recurse
dup base mod
dup 0= if 1+ else 1- then
swap base * + ;
: print_esthetic_numbers { min max per_line -- }
." Esthetic numbers in base 10 between " min 1 .r ." and " max 1 .r ." :" cr
0
min 1- 10 next_esthetic_number
begin
dup max <=
while
dup 4 .r
swap 1+ dup per_line mod 0= if cr else space then swap
10 next_esthetic_number
repeat
drop
cr ." count: " . cr ;
: main
17 2 do
i 4 * i 6 * { min max }
." Esthetic numbers in base " i 1 .r ." from index " min 1 .r ." through index " max 1 .r ." :" cr
0
max 1+ 1 do
j next_esthetic_number
i min >= if dup ['] . j base-execute then
loop
drop
cr cr
loop
1000 9999 16 print_esthetic_numbers cr
100000000 130000000 8 print_esthetic_numbers ;
main
bye |
http://rosettacode.org/wiki/Euler%27s_sum_of_powers_conjecture | Euler's sum of powers conjecture | There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin.
Euler's (disproved) sum of powers conjecture
At least k positive kth powers are required to sum to a kth power,
except for the trivial case of one kth power: yk = yk
In 1966, Leon J. Lander and Thomas R. Parkin used a brute-force search on a CDC 6600 computer restricting numbers to those less than 250.
Task
Write a program to search for an integer solution for:
x05 + x15 + x25 + x35 == y5
Where all xi's and y are distinct integers between 0 and 250 (exclusive).
Show an answer here.
Related tasks
Pythagorean quadruples.
Pythagorean triples.
| #Ada | Ada | with Ada.Text_IO;
procedure Sum_Of_Powers is
type Base is range 0 .. 250; -- A, B, C, D and Y are in that range
type Num is range 0 .. 4*(250**5); -- (A**5 + ... + D**5) is in that range
subtype Fit is Num range 0 .. 250**5; -- Y**5 is in that range
Modulus: constant Num := 254;
type Modular is mod Modulus;
type Result_Type is array(1..5) of Base; -- this will hold A,B,C,D and Y
type Y_Type is array(Modular) of Base;
type Y_Sum_Type is array(Modular) of Fit;
Y_Sum: Y_Sum_Type := (others => 0);
Y: Y_Type := (others => 0);
-- for I in 0 .. 250, we set Y_Sum(I**5 mod Modulus) := I**5
-- and Y(I**5 mod Modulus) := I
-- Modulus has been chosen to avoid collisions on (I**5 mod Modulus)
-- later we will compute Sum_ABCD := A**5 + B**5 + C**5 + D**5
-- and check if Y_Sum(Sum_ABCD mod modulus) = Sum_ABCD
function Compute_Coefficients return Result_Type is
Sum_A: Fit;
Sum_AB, Sum_ABC, Sum_ABCD: Num;
Short: Modular;
begin
for A in Base(0) .. 246 loop
Sum_A := Num(A) ** 5;
for B in A .. 247 loop
Sum_AB := Sum_A + (Num(B) ** 5);
for C in Base'Max(B,1) .. 248 loop -- if A=B=0 then skip C=0
Sum_ABC := Sum_AB + (Num(C) ** 5);
for D in C .. 249 loop
Sum_ABCD := Sum_ABC + (Num(D) ** 5);
Short := Modular(Sum_ABCD mod Modulus);
if Y_Sum(Short) = Sum_ABCD then
return A & B & C & D & Y(Short);
end if;
end loop;
end loop;
end loop;
end loop;
return 0 & 0 & 0 & 0 & 0;
end Compute_Coefficients;
Tmp: Fit;
ABCD_Y: Result_Type;
begin -- main program
-- initialize Y_Sum and Y
for I in Base(0) .. 250 loop
Tmp := Num(I)**5;
if Y_Sum(Modular(Tmp mod Modulus)) /= 0 then
raise Program_Error with "Collision: Change Modulus and recompile!";
else
Y_Sum(Modular(Tmp mod Modulus)) := Tmp;
Y(Modular(Tmp mod Modulus)) := I;
end if;
end loop;
-- search for a solution (A, B, C, D, Y)
ABCD_Y := Compute_Coefficients;
-- output result
for Number of ABCD_Y loop
Ada.Text_IO.Put(Base'Image(Number));
end loop;
Ada.Text_IO.New_Line;
end Sum_Of_Powers; |
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
| #Maude | Maude |
fmod FACTORIAL is
protecting INT .
op undefined : -> Int .
op _! : Int -> Int .
var n : Int .
eq 0 ! = 1 .
eq n ! = if n < 0 then undefined else n * (sd(n, 1) !) fi .
endfm
red 11 ! .
|
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.
| #Action.21 | Action! | PROC OddByAnd(INT v)
IF (v&1)=0 THEN
Print(" even")
ELSE
Print(" odd ")
FI
RETURN
PROC OddByMod(INT v)
;MOD doesn't work properly for negative numbers in Action!
IF v<0 THEN
v=-v
FI
IF v MOD 2=0 THEN
Print(" even")
ELSE
Print(" odd ")
FI
RETURN
PROC OddByDiv(INT v)
INT d
d=(v/2)*2
IF v=d THEN
Print(" even")
ELSE
Print(" odd ")
FI
RETURN
PROC Main()
INT i
FOR i=-4 TO 4
DO
PrintF("%I is",i)
OddByAnd(i)
OddByMod(i)
OddByDiv(i)
PutE()
OD
RETURN |
http://rosettacode.org/wiki/Euler_method | Euler method | Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value. It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page.
The ODE has to be provided in the following form:
d
y
(
t
)
d
t
=
f
(
t
,
y
(
t
)
)
{\displaystyle {\frac {dy(t)}{dt}}=f(t,y(t))}
with an initial value
y
(
t
0
)
=
y
0
{\displaystyle y(t_{0})=y_{0}}
To get a numeric solution, we replace the derivative on the LHS with a finite difference approximation:
d
y
(
t
)
d
t
≈
y
(
t
+
h
)
−
y
(
t
)
h
{\displaystyle {\frac {dy(t)}{dt}}\approx {\frac {y(t+h)-y(t)}{h}}}
then solve for
y
(
t
+
h
)
{\displaystyle y(t+h)}
:
y
(
t
+
h
)
≈
y
(
t
)
+
h
d
y
(
t
)
d
t
{\displaystyle y(t+h)\approx y(t)+h\,{\frac {dy(t)}{dt}}}
which is the same as
y
(
t
+
h
)
≈
y
(
t
)
+
h
f
(
t
,
y
(
t
)
)
{\displaystyle y(t+h)\approx y(t)+h\,f(t,y(t))}
The iterative solution rule is then:
y
n
+
1
=
y
n
+
h
f
(
t
n
,
y
n
)
{\displaystyle y_{n+1}=y_{n}+h\,f(t_{n},y_{n})}
where
h
{\displaystyle h}
is the step size, the most relevant parameter for accuracy of the solution. A smaller step size increases accuracy but also the computation cost, so it has always has to be hand-picked according to the problem at hand.
Example: Newton's Cooling Law
Newton's cooling law describes how an object of initial temperature
T
(
t
0
)
=
T
0
{\displaystyle T(t_{0})=T_{0}}
cools down in an environment of temperature
T
R
{\displaystyle T_{R}}
:
d
T
(
t
)
d
t
=
−
k
Δ
T
{\displaystyle {\frac {dT(t)}{dt}}=-k\,\Delta T}
or
d
T
(
t
)
d
t
=
−
k
(
T
(
t
)
−
T
R
)
{\displaystyle {\frac {dT(t)}{dt}}=-k\,(T(t)-T_{R})}
It says that the cooling rate
d
T
(
t
)
d
t
{\displaystyle {\frac {dT(t)}{dt}}}
of the object is proportional to the current temperature difference
Δ
T
=
(
T
(
t
)
−
T
R
)
{\displaystyle \Delta T=(T(t)-T_{R})}
to the surrounding environment.
The analytical solution, which we will compare to the numerical approximation, is
T
(
t
)
=
T
R
+
(
T
0
−
T
R
)
e
−
k
t
{\displaystyle T(t)=T_{R}+(T_{0}-T_{R})\;e^{-kt}}
Task
Implement a routine of Euler's method and then to use it to solve the given example of Newton's cooling law with it for three different step sizes of:
2 s
5 s and
10 s
and to compare with the analytical solution.
Initial values
initial temperature
T
0
{\displaystyle T_{0}}
shall be 100 °C
room temperature
T
R
{\displaystyle T_{R}}
shall be 20 °C
cooling constant
k
{\displaystyle k}
shall be 0.07
time interval to calculate shall be from 0 s ──► 100 s
A reference solution (Common Lisp) can be seen below. We see that bigger step sizes lead to reduced approximation accuracy.
| #Fortran | Fortran | program euler_method
use iso_fortran_env, only: real64
implicit none
abstract interface
! a derivative dy/dt as function of y and t
function derivative(y, t)
use iso_fortran_env, only: real64
real(real64) :: derivative
real(real64), intent(in) :: t, y
end function
end interface
real(real64), parameter :: T_0 = 100, T_room = 20, k = 0.07, a = 0, b = 100, &
h(3) = [2.0, 5.0, 10.0]
integer :: i
! loop over all step sizes
do i = 1, 3
call euler(newton_cooling, T_0, a, b, h(i))
end do
contains
! Approximates y(t) in y'(t) = f(y, t) with y(a) = y0 and t = a..b and the
! step size h.
subroutine euler(f, y0, a, b, h)
procedure(derivative) :: f
real(real64), intent(in) :: y0, a, b, h
real(real64) :: t, y
if (a > b) return
if (h <= 0) stop "negative step size"
print '("# h = ", F0.3)', h
y = y0
t = a
do
print *, t, y
t = t + h
if (t > b) return
y = y + h * f(y, t)
end do
end subroutine
! Example: Newton's cooling law, f(T, _) = -k*(T - T_room)
function newton_cooling(T, unused) result(dTdt)
real(real64) :: dTdt
real(real64), intent(in) :: T, unused
dTdt = -k * (T - T_room)
end function
end program |
http://rosettacode.org/wiki/Evaluate_binomial_coefficients | Evaluate binomial coefficients | This programming task, is to calculate ANY binomial coefficient.
However, it has to be able to output
(
5
3
)
{\displaystyle {\binom {5}{3}}}
, which is 10.
This formula is recommended:
(
n
k
)
=
n
!
(
n
−
k
)
!
k
!
=
n
(
n
−
1
)
(
n
−
2
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
(
k
−
2
)
…
1
{\displaystyle {\binom {n}{k}}={\frac {n!}{(n-k)!k!}}={\frac {n(n-1)(n-2)\ldots (n-k+1)}{k(k-1)(k-2)\ldots 1}}}
See Also:
Combinations and permutations
Pascal's triangle
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #AWK | AWK |
# syntax: GAWK -f EVALUATE_BINOMIAL_COEFFICIENTS.AWK
BEGIN {
main(5,3)
main(100,2)
main(33,17)
exit(0)
}
function main(n,k, i,r) {
r = 1
for (i=1; i<k+1; i++) {
r *= (n - i + 1) / i
}
printf("%d %d = %d\n",n,k,r)
}
|
http://rosettacode.org/wiki/Evaluate_binomial_coefficients | Evaluate binomial coefficients | This programming task, is to calculate ANY binomial coefficient.
However, it has to be able to output
(
5
3
)
{\displaystyle {\binom {5}{3}}}
, which is 10.
This formula is recommended:
(
n
k
)
=
n
!
(
n
−
k
)
!
k
!
=
n
(
n
−
1
)
(
n
−
2
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
(
k
−
2
)
…
1
{\displaystyle {\binom {n}{k}}={\frac {n!}{(n-k)!k!}}={\frac {n(n-1)(n-2)\ldots (n-k+1)}{k(k-1)(k-2)\ldots 1}}}
See Also:
Combinations and permutations
Pascal's triangle
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #Batch_File | Batch File | @echo off & setlocal
if "%~2"=="" ( echo Usage: %~nx0 n k && goto :EOF )
call :binom binom %~1 %~2
1>&2 set /P "=%~1 choose %~2 = "<NUL
echo %binom%
goto :EOF
:binom <var_to_set> <N> <K>
setlocal
set /a coeff=1, nk=%~2 - %~3 + 1
for /L %%I in (%nk%, 1, %~2) do set /a coeff *= %%I
for /L %%I in (1, 1, %~3) do set /a coeff /= %%I
endlocal && set "%~1=%coeff%"
goto :EOF |
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
Fn = Fn+2 - Fn+1, if n<0
support for negative n in the solution is optional.
Related tasks
Fibonacci n-step number sequences
Leonardo numbers
References
Wikipedia, Fibonacci number
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #Vala | Vala |
int fibRec(int n){
if (n < 2)
return n;
else
return fibRec(n - 1) + fibRec(n - 2);
}
|
http://rosettacode.org/wiki/Equal_prime_and_composite_sums | Equal prime and composite sums | Suppose we have a sequence of prime sums, where each term Pn is the sum of the first n primes.
P = (2), (2 + 3), (2 + 3 + 5), (2 + 3 + 5 + 7), (2 + 3 + 5 + 7 + 11), ...
P = 2, 5, 10, 17, 28, etc.
Further; suppose we have a sequence of composite sums, where each term Cm is the sum of the first m composites.
C = (4), (4 + 6), (4 + 6 + 8), (4 + 6 + 8 + 9), (4 + 6 + 8 + 9 + 10), ...
C = 4, 10, 18, 27, 37, etc.
Notice that the third term of P; P3 (10) is equal to the second term of C; C2 (10);
Task
Find and display the indices (n, m) and value of at least the first 6 terms of the sequence of numbers that are both the sum of the first n primes and the first m composites.
See also
OEIS:A007504 - Sum of the first n primes
OEIS:A053767 - Sum of first n composite numbers
OEIS:A294174 - Numbers that can be expressed both as the sum of first primes and as the sum of first composites
| #jq | jq | def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] +.;
def task($sievesize):
{compSums:[],
primeSums:[],
csum:0,
psum:0 }
| reduce range(2; $sievesize) as $i (.;
if $i|is_prime
then .psum += $i
| .primeSums += [.psum]
else .csum += $i
| .compSums += [ .csum ]
end)
| range(0; .primeSums|length) as $i
| .primeSums[$i] as $ps
| (.compSums | index( $ps )) as $ix
| select($ix >= 0)
| "\($ps|lpad(21)) - \($i+1|lpad(21)) prime sum, \($ix+1|lpad(12)) composite sum"
;
task(1E5) |
http://rosettacode.org/wiki/Equal_prime_and_composite_sums | Equal prime and composite sums | Suppose we have a sequence of prime sums, where each term Pn is the sum of the first n primes.
P = (2), (2 + 3), (2 + 3 + 5), (2 + 3 + 5 + 7), (2 + 3 + 5 + 7 + 11), ...
P = 2, 5, 10, 17, 28, etc.
Further; suppose we have a sequence of composite sums, where each term Cm is the sum of the first m composites.
C = (4), (4 + 6), (4 + 6 + 8), (4 + 6 + 8 + 9), (4 + 6 + 8 + 9 + 10), ...
C = 4, 10, 18, 27, 37, etc.
Notice that the third term of P; P3 (10) is equal to the second term of C; C2 (10);
Task
Find and display the indices (n, m) and value of at least the first 6 terms of the sequence of numbers that are both the sum of the first n primes and the first m composites.
See also
OEIS:A007504 - Sum of the first n primes
OEIS:A053767 - Sum of first n composite numbers
OEIS:A294174 - Numbers that can be expressed both as the sum of first primes and as the sum of first composites
| #Julia | Julia | using Primes
function getsequencematches(N, masksize = 1_000_000_000)
pmask = primesmask(masksize)
found, psum, csum, pindex, cindex, pcount, ccount = 0, 2, 4, 2, 4, 1, 1
incrementpsum() = (pindex += 1; if pmask[pindex] psum += pindex; pcount += 1 end)
incrementcsum() = (cindex += 1; if !pmask[cindex] csum += cindex; ccount += 1 end)
while found < N
while psum < csum
pindex >= masksize && return
incrementpsum()
end
if psum == csum
println("Primes up to $pindex at position $pcount and composites up to $cindex at position $ccount sum to $psum.")
found += 1
while psum == csum
incrementpsum()
incrementcsum()
end
end
while csum < psum
incrementcsum()
end
end
end
@time getsequencematches(11)
|
http://rosettacode.org/wiki/Equal_prime_and_composite_sums | Equal prime and composite sums | Suppose we have a sequence of prime sums, where each term Pn is the sum of the first n primes.
P = (2), (2 + 3), (2 + 3 + 5), (2 + 3 + 5 + 7), (2 + 3 + 5 + 7 + 11), ...
P = 2, 5, 10, 17, 28, etc.
Further; suppose we have a sequence of composite sums, where each term Cm is the sum of the first m composites.
C = (4), (4 + 6), (4 + 6 + 8), (4 + 6 + 8 + 9), (4 + 6 + 8 + 9 + 10), ...
C = 4, 10, 18, 27, 37, etc.
Notice that the third term of P; P3 (10) is equal to the second term of C; C2 (10);
Task
Find and display the indices (n, m) and value of at least the first 6 terms of the sequence of numbers that are both the sum of the first n primes and the first m composites.
See also
OEIS:A007504 - Sum of the first n primes
OEIS:A053767 - Sum of first n composite numbers
OEIS:A294174 - Numbers that can be expressed both as the sum of first primes and as the sum of first composites
| #Perl | Perl | use strict;
use warnings;
use feature <say state>;
use ntheory <is_prime next_prime>;
sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r }
sub suffix { my($d) = $_[0] =~ /(.)$/; $d == 1 ? 'st' : $d == 2 ? 'nd' : $d == 3 ? 'rd' : 'th' }
sub prime_sum {
state $s = state $p = 2; state $i = 1;
if ($i < (my $n = shift) ) { do { $s += $p = next_prime($p) } until ++$i == $n }
$s
}
sub composite_sum {
state $s = state $c = 4; state $i = 1;
if ($i < (my $n = shift) ) { do { 1 until ! is_prime(++$c); $s += $c } until ++$i == $n }
$s
}
my $ci++;
for my $pi (1 .. 5_012_372) {
next if prime_sum($pi) < composite_sum($ci);
printf( "%20s - %11s prime sum, %12s composite sum\n",
comma(prime_sum $pi), comma($pi).suffix($pi), comma($ci).suffix($ci))
and next if prime_sum($pi) == composite_sum($ci);
$ci++;
redo
} |
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
| #8080_Assembly | 8080 Assembly | org 100h
jmp demo
;;; HL = BC * DE
;;; BC is left column, DE is right column
emul: lxi h,0 ; HL will be the accumulator
ztest: mov a,b ; Check if the left column is zero.
ora c ; If so, stop.
rz
halve: mov a,b ; Halve BC by rotating it right.
rar ; We know the carry is zero here because of the ORA.
mov b,a ; So rotate the top half first,
mov a,c ; Then the bottom half
rar ; This leaves the old low bit in the carry flag,
mov c,a ; so this also lets us do the even/odd test in one go.
even: jnc $+4 ; If no carry, the number is even, so skip (strikethrough)
dad d ; But if odd, add the number in the right column
double: xchg ; Doubling DE is a bit easier since you can add
dad h ; HL to itself in one go, and XCHG swaps DE and HL
xchg
jmp ztest ; We want to do the whole thing again until BC is zero
;;; Demo code, print 17 * 34
demo: lxi b,17 ; Load 17 into BC (left column)
lxi d,34 ; Load 34 into DE (right column)
call emul ; Do the multiplication
print: lxi b,-10 ; Decimal output routine (not very interesting here,
lxi d,pbuf ; but without it you can't see the result)
push d
digit: lxi d,-1
dloop: inx d
dad b
jc dloop
mvi a,58
add l
pop h
dcx h
mov m,a
push h
xchg
mov a,h
ora l
jnz digit
pop d
mvi c,9
jmp 5
db '*****'
pbuf: db '$' |
http://rosettacode.org/wiki/Esthetic_numbers | Esthetic numbers | An esthetic number is a positive integer where every adjacent digit differs from its neighbour by 1.
E.G.
12 is an esthetic number. One and two differ by 1.
5654 is an esthetic number. Each digit is exactly 1 away from its neighbour.
890 is not an esthetic number. Nine and zero differ by 9.
These examples are nominally in base 10 but the concept extends easily to numbers in other bases. Traditionally, single digit numbers are included in esthetic numbers; zero may or may not be. For our purposes, for this task, do not include zero (0) as an esthetic number. Do not include numbers with leading zeros.
Esthetic numbers are also sometimes referred to as stepping numbers.
Task
Write a routine (function, procedure, whatever) to find esthetic numbers in a given base.
Use that routine to find esthetic numbers in bases 2 through 16 and display, here on this page, the esthectic numbers from index (base × 4) through index (base × 6), inclusive. (E.G. for base 2: 8th through 12th, for base 6: 24th through 36th, etc.)
Find and display, here on this page, the base 10 esthetic numbers with a magnitude between 1000 and 9999.
Stretch: Find and display, here on this page, the base 10 esthetic numbers with a magnitude between 1.0e8 and 1.3e8.
Related task
numbers with equal rises and falls
See also
OEIS A033075 - Positive numbers n such that all pairs of consecutive decimal digits differ by 1
Numbers Aplenty - Esthetic numbers
Geeks for Geeks - Stepping numbers
| #FreeBASIC | FreeBASIC |
dim shared as string*16 digits = "0123456789ABCDEF"
function get_digit( n as uinteger ) as string
return mid(digits, n+1, 1)
end function
function find_digit( s as string ) as integer
for i as uinteger = 1 to len(digits)
if s = mid(digits, i, 1) then return i
next i
return -999
end function
sub make_base( byval n as uinteger, bse as uinteger, byref ret as string )
if n = 0 then ret = "0" else ret = ""
dim as uinteger m
while n > 0
m = n mod bse
ret = mid(digits, m+1, 1) + ret
n = (n - m)/bse
wend
end sub
function is_esthetic( number as string ) as boolean
if number = "0" then return false
if len(number) = 1 then return true
dim as integer curr = find_digit( left(number,1) ), last, i
for i = 2 to len(number)
last = curr
curr = find_digit( mid(number, i, 1) )
if abs( last - curr ) <> 1 then return false
next i
return true
end function
dim as uinteger b, c
dim as ulongint i
dim as string number
for b = 2 to 16
print "BASE ";b
i = 0 : c = 0
while c <= 6*b
i += 1
make_base i, b, number
if is_esthetic( number ) then
c += 1
if c >= 4*b then print number;" ";
end if
wend
print
next b
print "BASE TEN"
for i = 1000 to 9999
make_base i, 10, number
if is_esthetic(number) then print number;" ";
next i
print
print "STRETCH GOAL"
for i = 100000000 to 130000000
make_base i, 10, number
if is_esthetic(number) then print number;" ";
next i |
http://rosettacode.org/wiki/Euler%27s_sum_of_powers_conjecture | Euler's sum of powers conjecture | There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin.
Euler's (disproved) sum of powers conjecture
At least k positive kth powers are required to sum to a kth power,
except for the trivial case of one kth power: yk = yk
In 1966, Leon J. Lander and Thomas R. Parkin used a brute-force search on a CDC 6600 computer restricting numbers to those less than 250.
Task
Write a program to search for an integer solution for:
x05 + x15 + x25 + x35 == y5
Where all xi's and y are distinct integers between 0 and 250 (exclusive).
Show an answer here.
Related tasks
Pythagorean quadruples.
Pythagorean triples.
| #ALGOL_68 | ALGOL 68 | # max number will be the highest integer we will consider #
INT max number = 250;
# Construct a table of the fifth powers of 1 : max number #
[ max number ]LONG INT fifth;
FOR i TO max number DO
LONG INT i2 = i * i;
fifth[ i ] := i2 * i2 * i
OD;
# find the first a, b, c, d, e such that a^5 + b^5 + c^5 + d^5 = e^5 #
# as the fifth powers are in order, we can use a binary search to determine #
# whether the value is in the table #
BOOL found := FALSE;
FOR a TO max number WHILE NOT found DO
FOR b FROM a TO max number WHILE NOT found DO
FOR c FROM b TO max number WHILE NOT found DO
FOR d FROM c TO max number WHILE NOT found DO
LONG INT sum = fifth[a] + fifth[b] + fifth[c] + fifth[d];
INT low := d;
INT high := max number;
WHILE low < high
AND NOT found
DO
INT e := ( low + high ) OVER 2;
IF fifth[ e ] = sum
THEN
# the value at e is a fifth power #
found := TRUE;
print( ( ( whole( a, 0 ) + "^5 + " + whole( b, 0 ) + "^5 + "
+ whole( c, 0 ) + "^5 + " + whole( d, 0 ) + "^5 = "
+ whole( e, 0 ) + "^5"
)
, newline
)
)
ELIF sum < fifth[ e ]
THEN high := e - 1
ELSE low := e + 1
FI
OD
OD
OD
OD
OD |
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
| #Maxima | Maxima | n! |
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.
| #Ada | Ada | -- Ada has bitwise operators in package Interfaces,
-- but they work with Interfaces.Unsigned_*** types only.
-- Use rem or mod for Integer types, and let the compiler
-- optimize it.
declare
N : Integer := 5;
begin
if N rem 2 = 0 then
Put_Line ("Even number");
elseif N rem 2 /= 0 then
Put_Line ("Odd number");
else
Put_Line ("Something went really wrong!");
end if;
end; |
http://rosettacode.org/wiki/Euler_method | Euler method | Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value. It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page.
The ODE has to be provided in the following form:
d
y
(
t
)
d
t
=
f
(
t
,
y
(
t
)
)
{\displaystyle {\frac {dy(t)}{dt}}=f(t,y(t))}
with an initial value
y
(
t
0
)
=
y
0
{\displaystyle y(t_{0})=y_{0}}
To get a numeric solution, we replace the derivative on the LHS with a finite difference approximation:
d
y
(
t
)
d
t
≈
y
(
t
+
h
)
−
y
(
t
)
h
{\displaystyle {\frac {dy(t)}{dt}}\approx {\frac {y(t+h)-y(t)}{h}}}
then solve for
y
(
t
+
h
)
{\displaystyle y(t+h)}
:
y
(
t
+
h
)
≈
y
(
t
)
+
h
d
y
(
t
)
d
t
{\displaystyle y(t+h)\approx y(t)+h\,{\frac {dy(t)}{dt}}}
which is the same as
y
(
t
+
h
)
≈
y
(
t
)
+
h
f
(
t
,
y
(
t
)
)
{\displaystyle y(t+h)\approx y(t)+h\,f(t,y(t))}
The iterative solution rule is then:
y
n
+
1
=
y
n
+
h
f
(
t
n
,
y
n
)
{\displaystyle y_{n+1}=y_{n}+h\,f(t_{n},y_{n})}
where
h
{\displaystyle h}
is the step size, the most relevant parameter for accuracy of the solution. A smaller step size increases accuracy but also the computation cost, so it has always has to be hand-picked according to the problem at hand.
Example: Newton's Cooling Law
Newton's cooling law describes how an object of initial temperature
T
(
t
0
)
=
T
0
{\displaystyle T(t_{0})=T_{0}}
cools down in an environment of temperature
T
R
{\displaystyle T_{R}}
:
d
T
(
t
)
d
t
=
−
k
Δ
T
{\displaystyle {\frac {dT(t)}{dt}}=-k\,\Delta T}
or
d
T
(
t
)
d
t
=
−
k
(
T
(
t
)
−
T
R
)
{\displaystyle {\frac {dT(t)}{dt}}=-k\,(T(t)-T_{R})}
It says that the cooling rate
d
T
(
t
)
d
t
{\displaystyle {\frac {dT(t)}{dt}}}
of the object is proportional to the current temperature difference
Δ
T
=
(
T
(
t
)
−
T
R
)
{\displaystyle \Delta T=(T(t)-T_{R})}
to the surrounding environment.
The analytical solution, which we will compare to the numerical approximation, is
T
(
t
)
=
T
R
+
(
T
0
−
T
R
)
e
−
k
t
{\displaystyle T(t)=T_{R}+(T_{0}-T_{R})\;e^{-kt}}
Task
Implement a routine of Euler's method and then to use it to solve the given example of Newton's cooling law with it for three different step sizes of:
2 s
5 s and
10 s
and to compare with the analytical solution.
Initial values
initial temperature
T
0
{\displaystyle T_{0}}
shall be 100 °C
room temperature
T
R
{\displaystyle T_{R}}
shall be 20 °C
cooling constant
k
{\displaystyle k}
shall be 0.07
time interval to calculate shall be from 0 s ──► 100 s
A reference solution (Common Lisp) can be seen below. We see that bigger step sizes lead to reduced approximation accuracy.
| #Futhark | Futhark |
let analytic(t0: f64) (time: f64): f64 =
20.0 + (t0 - 20.0) * f64.exp(-0.07*time)
let cooling(_time: f64) (temperature: f64): f64 =
-0.07 * (temperature-20.0)
let main(t0: f64) (a: f64) (b: f64) (h: f64): []f64 =
let steps = i32.f64 ((b-a)/h)
let temps = replicate steps 0.0
let (_,temps) = loop (t,temps)=(t0,temps) for i < steps do
let x = a + f64.i32 i * h
let temps[i] = f64.abs(t-analytic t0 x)
in (t + h * cooling x t,
temps)
in temps
|
http://rosettacode.org/wiki/Euler_method | Euler method | Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value. It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page.
The ODE has to be provided in the following form:
d
y
(
t
)
d
t
=
f
(
t
,
y
(
t
)
)
{\displaystyle {\frac {dy(t)}{dt}}=f(t,y(t))}
with an initial value
y
(
t
0
)
=
y
0
{\displaystyle y(t_{0})=y_{0}}
To get a numeric solution, we replace the derivative on the LHS with a finite difference approximation:
d
y
(
t
)
d
t
≈
y
(
t
+
h
)
−
y
(
t
)
h
{\displaystyle {\frac {dy(t)}{dt}}\approx {\frac {y(t+h)-y(t)}{h}}}
then solve for
y
(
t
+
h
)
{\displaystyle y(t+h)}
:
y
(
t
+
h
)
≈
y
(
t
)
+
h
d
y
(
t
)
d
t
{\displaystyle y(t+h)\approx y(t)+h\,{\frac {dy(t)}{dt}}}
which is the same as
y
(
t
+
h
)
≈
y
(
t
)
+
h
f
(
t
,
y
(
t
)
)
{\displaystyle y(t+h)\approx y(t)+h\,f(t,y(t))}
The iterative solution rule is then:
y
n
+
1
=
y
n
+
h
f
(
t
n
,
y
n
)
{\displaystyle y_{n+1}=y_{n}+h\,f(t_{n},y_{n})}
where
h
{\displaystyle h}
is the step size, the most relevant parameter for accuracy of the solution. A smaller step size increases accuracy but also the computation cost, so it has always has to be hand-picked according to the problem at hand.
Example: Newton's Cooling Law
Newton's cooling law describes how an object of initial temperature
T
(
t
0
)
=
T
0
{\displaystyle T(t_{0})=T_{0}}
cools down in an environment of temperature
T
R
{\displaystyle T_{R}}
:
d
T
(
t
)
d
t
=
−
k
Δ
T
{\displaystyle {\frac {dT(t)}{dt}}=-k\,\Delta T}
or
d
T
(
t
)
d
t
=
−
k
(
T
(
t
)
−
T
R
)
{\displaystyle {\frac {dT(t)}{dt}}=-k\,(T(t)-T_{R})}
It says that the cooling rate
d
T
(
t
)
d
t
{\displaystyle {\frac {dT(t)}{dt}}}
of the object is proportional to the current temperature difference
Δ
T
=
(
T
(
t
)
−
T
R
)
{\displaystyle \Delta T=(T(t)-T_{R})}
to the surrounding environment.
The analytical solution, which we will compare to the numerical approximation, is
T
(
t
)
=
T
R
+
(
T
0
−
T
R
)
e
−
k
t
{\displaystyle T(t)=T_{R}+(T_{0}-T_{R})\;e^{-kt}}
Task
Implement a routine of Euler's method and then to use it to solve the given example of Newton's cooling law with it for three different step sizes of:
2 s
5 s and
10 s
and to compare with the analytical solution.
Initial values
initial temperature
T
0
{\displaystyle T_{0}}
shall be 100 °C
room temperature
T
R
{\displaystyle T_{R}}
shall be 20 °C
cooling constant
k
{\displaystyle k}
shall be 0.07
time interval to calculate shall be from 0 s ──► 100 s
A reference solution (Common Lisp) can be seen below. We see that bigger step sizes lead to reduced approximation accuracy.
| #Go | Go | package main
import (
"fmt"
"math"
)
// fdy is a type for function f used in Euler's method.
type fdy func(float64, float64) float64
// eulerStep computes a single new value using Euler's method.
// Note that step size h is a parameter, so a variable step size
// could be used.
func eulerStep(f fdy, x, y, h float64) float64 {
return y + h*f(x, y)
}
// Definition of cooling rate. Note that this has general utility and
// is not specific to use in Euler's method.
// newCoolingRate returns a function that computes cooling rate
// for a given cooling rate constant k.
func newCoolingRate(k float64) func(float64) float64 {
return func(deltaTemp float64) float64 {
return -k * deltaTemp
}
}
// newTempFunc returns a function that computes the analytical solution
// of cooling rate integrated over time.
func newTempFunc(k, ambientTemp, initialTemp float64) func(float64) float64 {
return func(time float64) float64 {
return ambientTemp + (initialTemp-ambientTemp)*math.Exp(-k*time)
}
}
// newCoolingRateDy returns a function of the kind needed for Euler's method.
// That is, a function representing dy(x, y(x)).
//
// Parameters to newCoolingRateDy are cooling constant k and ambient
// temperature.
func newCoolingRateDy(k, ambientTemp float64) fdy {
crf := newCoolingRate(k)
// note that result is dependent only on the object temperature.
// there are no additional dependencies on time, so the x parameter
// provided by eulerStep is unused.
return func(_, objectTemp float64) float64 {
return crf(objectTemp - ambientTemp)
}
}
func main() {
k := .07
tempRoom := 20.
tempObject := 100.
fcr := newCoolingRateDy(k, tempRoom)
analytic := newTempFunc(k, tempRoom, tempObject)
for _, deltaTime := range []float64{2, 5, 10} {
fmt.Printf("Step size = %.1f\n", deltaTime)
fmt.Println(" Time Euler's Analytic")
temp := tempObject
for time := 0.; time <= 100; time += deltaTime {
fmt.Printf("%5.1f %7.3f %7.3f\n", time, temp, analytic(time))
temp = eulerStep(fcr, time, temp, deltaTime)
}
fmt.Println()
}
} |
http://rosettacode.org/wiki/Evaluate_binomial_coefficients | Evaluate binomial coefficients | This programming task, is to calculate ANY binomial coefficient.
However, it has to be able to output
(
5
3
)
{\displaystyle {\binom {5}{3}}}
, which is 10.
This formula is recommended:
(
n
k
)
=
n
!
(
n
−
k
)
!
k
!
=
n
(
n
−
1
)
(
n
−
2
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
(
k
−
2
)
…
1
{\displaystyle {\binom {n}{k}}={\frac {n!}{(n-k)!k!}}={\frac {n(n-1)(n-2)\ldots (n-k+1)}{k(k-1)(k-2)\ldots 1}}}
See Also:
Combinations and permutations
Pascal's triangle
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #BCPL | BCPL |
GET "libhdr"
LET choose(n, k) =
~(0 <= k <= n) -> 0,
2*k > n -> binomial(n, n - k),
binomial(n, k)
AND binomial(n, k) =
k = 0 -> 1,
binomial(n, k - 1) * (n - k + 1) / k
LET start() = VALOF {
LET n, k = ?, ?
LET argv = VEC 20
LET sz = ?
sz := rdargs("n/a/n/p,k/a/n/p", argv, 20)
UNLESS sz ~= 0 RESULTIS 1
n := !argv!0
k := !argv!1
writef("%d choose %d = %d *n", n, k, choose(n, k))
RESULTIS 0
}
|
http://rosettacode.org/wiki/Evaluate_binomial_coefficients | Evaluate binomial coefficients | This programming task, is to calculate ANY binomial coefficient.
However, it has to be able to output
(
5
3
)
{\displaystyle {\binom {5}{3}}}
, which is 10.
This formula is recommended:
(
n
k
)
=
n
!
(
n
−
k
)
!
k
!
=
n
(
n
−
1
)
(
n
−
2
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
(
k
−
2
)
…
1
{\displaystyle {\binom {n}{k}}={\frac {n!}{(n-k)!k!}}={\frac {n(n-1)(n-2)\ldots (n-k+1)}{k(k-1)(k-2)\ldots 1}}}
See Also:
Combinations and permutations
Pascal's triangle
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #BBC_BASIC | BBC BASIC | @%=&1010
PRINT "Binomial (5,3) = "; FNbinomial(5, 3)
PRINT "Binomial (100,2) = "; FNbinomial(100, 2)
PRINT "Binomial (33,17) = "; FNbinomial(33, 17)
END
DEF FNbinomial(N%, K%)
LOCAL R%, D%
R% = 1 : D% = N% - K%
IF D% > K% THEN K% = D% : D% = N% - K%
WHILE N% > K%
R% *= N%
N% -= 1
WHILE D% > 1 AND (R% MOD D%) = 0
R% /= D%
D% -= 1
ENDWHILE
ENDWHILE
= R%
|
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
Fn = Fn+2 - Fn+1, if n<0
support for negative n in the solution is optional.
Related tasks
Fibonacci n-step number sequences
Leonardo numbers
References
Wikipedia, Fibonacci number
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #VAX_Assembly | VAX Assembly | 0000 0000 1 .entry main,0
7E 7CFD 0002 2 clro -(sp) ;result buffer
5E DD 0005 3 pushl sp ;pointer to buffer
10 DD 0007 4 pushl #16 ;descriptor: len of buffer
5B 5E D0 0009 5 movl sp, r11 ;-> descriptor
000C 6
7E 01 7D 000C 7 movq #1, -(sp) ;init 0,1
000F 8 loop:
7E 6E 04 AE C1 000F 9 addl3 4(sp), (sp), -(sp) ;next element on stack
17 1D 0014 10 bvs ret ;vs - overflow set, exit
0016 11
5B DD 0016 12 pushl r11 ;-> descriptor by ref
04 AE DF 0018 13 pushal 4(sp) ;-> fib on stack by ref
00000000'GF 02 FB 001B 14 calls #2, g^ots$cvt_l_ti ;convert integer to string
5B DD 0022 15 pushl r11 ;
00000000'GF 01 FB 0024 16 calls #1, g^lib$put_output ;show result
E2 11 002B 17 brb loop
002D 18 ret:
04 002D 19 ret
002E 20 .end main
$ run fib
...
14930352
24157817
39088169
63245986
102334155
165580141
267914296
433494437
701408733
1134903170
1836311903
$
|
http://rosettacode.org/wiki/Equal_prime_and_composite_sums | Equal prime and composite sums | Suppose we have a sequence of prime sums, where each term Pn is the sum of the first n primes.
P = (2), (2 + 3), (2 + 3 + 5), (2 + 3 + 5 + 7), (2 + 3 + 5 + 7 + 11), ...
P = 2, 5, 10, 17, 28, etc.
Further; suppose we have a sequence of composite sums, where each term Cm is the sum of the first m composites.
C = (4), (4 + 6), (4 + 6 + 8), (4 + 6 + 8 + 9), (4 + 6 + 8 + 9 + 10), ...
C = 4, 10, 18, 27, 37, etc.
Notice that the third term of P; P3 (10) is equal to the second term of C; C2 (10);
Task
Find and display the indices (n, m) and value of at least the first 6 terms of the sequence of numbers that are both the sum of the first n primes and the first m composites.
See also
OEIS:A007504 - Sum of the first n primes
OEIS:A053767 - Sum of first n composite numbers
OEIS:A294174 - Numbers that can be expressed both as the sum of first primes and as the sum of first composites
| #Phix | Phix | with javascript_semantics
atom t0 = time()
atom ps = 2, -- current prime sum
cs = 4 -- current composite sum
integer psn = 1, npi = 1, -- (see below)
csn = 1, nci = 3, nc = 4, ncp = 5,
found = 0
constant limit = iff(platform()=JS?10:11)
while found<limit do
integer c = compare(ps,cs) -- {-1,0,+1}
if c=0 then
printf(1,"%,21d - %,10d%s prime sum, %,10d%s composite sum (%s)\n",
{ps, psn, ord(psn), csn, ord(csn), elapsed(time()-t0)})
found += 1
end if
if c<=0 then
psn += 1 -- prime sum number
npi += 1 -- next prime index
ps += get_prime(npi)
end if
if c>=0 then
csn += 1 -- composite sum number
nc += 1 -- next composite?
if nc=ncp then -- "", erm no
nci += 1 -- next prime index
ncp = get_prime(nci)
nc += 1 -- next composite (even!)
end if
cs += nc
end if
end while
|
http://rosettacode.org/wiki/Equal_prime_and_composite_sums | Equal prime and composite sums | Suppose we have a sequence of prime sums, where each term Pn is the sum of the first n primes.
P = (2), (2 + 3), (2 + 3 + 5), (2 + 3 + 5 + 7), (2 + 3 + 5 + 7 + 11), ...
P = 2, 5, 10, 17, 28, etc.
Further; suppose we have a sequence of composite sums, where each term Cm is the sum of the first m composites.
C = (4), (4 + 6), (4 + 6 + 8), (4 + 6 + 8 + 9), (4 + 6 + 8 + 9 + 10), ...
C = 4, 10, 18, 27, 37, etc.
Notice that the third term of P; P3 (10) is equal to the second term of C; C2 (10);
Task
Find and display the indices (n, m) and value of at least the first 6 terms of the sequence of numbers that are both the sum of the first n primes and the first m composites.
See also
OEIS:A007504 - Sum of the first n primes
OEIS:A053767 - Sum of first n composite numbers
OEIS:A294174 - Numbers that can be expressed both as the sum of first primes and as the sum of first composites
| #Raku | Raku | use Lingua::EN::Numbers:ver<2.8.2+>;
my $prime-sum = [\+] (2..*).grep: *.is-prime;
my $composite-sum = [\+] (2..*).grep: !*.is-prime;
my $c-index = 0;
for ^∞ -> $p-index {
next if $prime-sum[$p-index] < $composite-sum[$c-index];
printf( "%20s - %11s prime sum, %12s composite sum %5.2f seconds\n",
$prime-sum[$p-index].&comma, ordinal-digit($p-index + 1, :u, :c),
ordinal-digit($c-index + 1, :u, :c), now - INIT now )
and next if $prime-sum[$p-index] == $composite-sum[$c-index];
++$c-index;
redo;
}; |
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
| #ACL2 | ACL2 | (include-book "arithmetic-3/top" :dir :system)
(defun halve (x)
(floor x 2))
(defun double (x)
(* x 2))
(defun is-even (x)
(evenp x))
(defun multiply (x y)
(if (zp (1- x))
y
(+ (if (is-even x)
0
y)
(multiply (halve x) (double y))))) |
http://rosettacode.org/wiki/Esthetic_numbers | Esthetic numbers | An esthetic number is a positive integer where every adjacent digit differs from its neighbour by 1.
E.G.
12 is an esthetic number. One and two differ by 1.
5654 is an esthetic number. Each digit is exactly 1 away from its neighbour.
890 is not an esthetic number. Nine and zero differ by 9.
These examples are nominally in base 10 but the concept extends easily to numbers in other bases. Traditionally, single digit numbers are included in esthetic numbers; zero may or may not be. For our purposes, for this task, do not include zero (0) as an esthetic number. Do not include numbers with leading zeros.
Esthetic numbers are also sometimes referred to as stepping numbers.
Task
Write a routine (function, procedure, whatever) to find esthetic numbers in a given base.
Use that routine to find esthetic numbers in bases 2 through 16 and display, here on this page, the esthectic numbers from index (base × 4) through index (base × 6), inclusive. (E.G. for base 2: 8th through 12th, for base 6: 24th through 36th, etc.)
Find and display, here on this page, the base 10 esthetic numbers with a magnitude between 1000 and 9999.
Stretch: Find and display, here on this page, the base 10 esthetic numbers with a magnitude between 1.0e8 and 1.3e8.
Related task
numbers with equal rises and falls
See also
OEIS A033075 - Positive numbers n such that all pairs of consecutive decimal digits differ by 1
Numbers Aplenty - Esthetic numbers
Geeks for Geeks - Stepping numbers
| #Go | Go | package main
import (
"fmt"
"strconv"
)
func uabs(a, b uint64) uint64 {
if a > b {
return a - b
}
return b - a
}
func isEsthetic(n, b uint64) bool {
if n == 0 {
return false
}
i := n % b
n /= b
for n > 0 {
j := n % b
if uabs(i, j) != 1 {
return false
}
n /= b
i = j
}
return true
}
var esths []uint64
func dfs(n, m, i uint64) {
if i >= n && i <= m {
esths = append(esths, i)
}
if i == 0 || i > m {
return
}
d := i % 10
i1 := i*10 + d - 1
i2 := i1 + 2
if d == 0 {
dfs(n, m, i2)
} else if d == 9 {
dfs(n, m, i1)
} else {
dfs(n, m, i1)
dfs(n, m, i2)
}
}
func listEsths(n, n2, m, m2 uint64, perLine int, all bool) {
esths = esths[:0]
for i := uint64(0); i < 10; i++ {
dfs(n2, m2, i)
}
le := len(esths)
fmt.Printf("Base 10: %s esthetic numbers between %s and %s:\n",
commatize(uint64(le)), commatize(n), commatize(m))
if all {
for c, esth := range esths {
fmt.Printf("%d ", esth)
if (c+1)%perLine == 0 {
fmt.Println()
}
}
} else {
for i := 0; i < perLine; i++ {
fmt.Printf("%d ", esths[i])
}
fmt.Println("\n............\n")
for i := le - perLine; i < le; i++ {
fmt.Printf("%d ", esths[i])
}
}
fmt.Println("\n")
}
func commatize(n uint64) string {
s := fmt.Sprintf("%d", n)
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
return s
}
func main() {
for b := uint64(2); b <= 16; b++ {
fmt.Printf("Base %d: %dth to %dth esthetic numbers:\n", b, 4*b, 6*b)
for n, c := uint64(1), uint64(0); c < 6*b; n++ {
if isEsthetic(n, b) {
c++
if c >= 4*b {
fmt.Printf("%s ", strconv.FormatUint(n, int(b)))
}
}
}
fmt.Println("\n")
}
// the following all use the obvious range limitations for the numbers in question
listEsths(1000, 1010, 9999, 9898, 16, true)
listEsths(1e8, 101_010_101, 13*1e7, 123_456_789, 9, true)
listEsths(1e11, 101_010_101_010, 13*1e10, 123_456_789_898, 7, false)
listEsths(1e14, 101_010_101_010_101, 13*1e13, 123_456_789_898_989, 5, false)
listEsths(1e17, 101_010_101_010_101_010, 13*1e16, 123_456_789_898_989_898, 4, false)
} |
http://rosettacode.org/wiki/Euler%27s_sum_of_powers_conjecture | Euler's sum of powers conjecture | There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin.
Euler's (disproved) sum of powers conjecture
At least k positive kth powers are required to sum to a kth power,
except for the trivial case of one kth power: yk = yk
In 1966, Leon J. Lander and Thomas R. Parkin used a brute-force search on a CDC 6600 computer restricting numbers to those less than 250.
Task
Write a program to search for an integer solution for:
x05 + x15 + x25 + x35 == y5
Where all xi's and y are distinct integers between 0 and 250 (exclusive).
Show an answer here.
Related tasks
Pythagorean quadruples.
Pythagorean triples.
| #ALGOL_W | ALGOL W | begin
% find a, b, c, d, e such that a^5 + b^5 + c^5 + d^5 = e^5 %
% where 1 <= a <= b <= c <= d <= e <= 250 %
% we solve this using the equivalent equation a^5 + b^5 + c^5 = e^5 - d^5 %
% 250^5 is 976 562 500 000 - too large for a 32 bit number so we will use pairs of %
% integers and constrain their values to be in 0..1 000 000 %
% Note only positive numbers are needed %
integer MAX_NUMBER, MAX_V;
MAX_NUMBER := 250;
MAX_V := 1000000;
begin
% quick sorts the fifth power differences table %
procedure quickSort5 ( integer value lb, ub ) ;
if ub > lb then begin
% more than one element, so must sort %
integer left, right, pivot, pivotLo, pivotHi;
left := lb;
right := ub;
% choosing the middle element of the array as the pivot %
pivot := left + ( ( ( right + 1 ) - left ) div 2 );
pivotLo := loD( pivot );
pivotHi := hiD( pivot );
while begin
while left <= ub
and begin integer cmp;
cmp := hiD( left ) - pivotHi;
if cmp = 0 then cmp := loD( left ) - pivotLo;
cmp < 0
end
do left := left + 1;
while right >= lb
and begin integer cmp;
cmp := hiD( right ) - pivotHi;
if cmp = 0 then cmp := loD( right ) - pivotLo;
cmp > 0
end
do right := right - 1;
left <= right
end do begin
integer swapLo, swapHi, swapD, swapE;
swapLo := loD( left );
swapHi := hiD( left );
swapD := Dd( left );
swapE := De( left );
loD( left ) := loD( right );
hiD( left ) := hiD( right );
Dd( left ) := Dd( right );
De( left ) := De( right );
loD( right ) := swapLo;
hiD( right ) := swapHi;
Dd( right ) := swapD;
De( right ) := swapE;
left := left + 1;
right := right - 1
end while_left_le_right ;
quickSort5( lb, right );
quickSort5( left, ub )
end quickSort5 ;
% table of fifth powers %
integer array lo5, hi5 ( 1 :: MAX_NUMBER );
% table if differences between fifth powers %
integer array loD, hiD, De, Dd ( 1 :: MAX_NUMBER * MAX_NUMBER );
integer dUsed, dPos;
% compute fifth powers %
for i := 1 until MAX_NUMBER do begin
lo5( i ) := i * i; hi5( i ) := 0;
for p := 3 until 5 do begin
integer carry;
lo5( i ) := lo5( i ) * i;
carry := lo5( i ) div MAX_V;
lo5( i ) := lo5( i ) rem MAX_V;
hi5( i ) := hi5( i ) * i;
hi5( i ) := hi5( i ) + carry
end for_p
end for_i ;
% compute the differences between fifth powers e^5 - d^5, 1 <= d < e <= MAX_NUMBER %
dUsed := 0;
for e := 2 until MAX_NUMBER do begin
for d := 1 until e - 1 do begin
dUsed := dUsed + 1;
De( dUsed ) := e;
Dd( dUsed ) := d;
loD( dUsed ) := lo5( e ) - lo5( d );
hiD( dUsed ) := hi5( e ) - hi5( d );
if loD( dUsed ) < 0 then begin
loD( dUsed ) := loD( dUsed ) + MAX_V;
hiD( dUsed ) := hiD( dUsed ) - 1
end if_need_to_borrow
end for_d
end for_e;
% sort the fifth power differences %
quickSort5( 1, dUsed );
% attempt to find a^5 + b^5 + c^5 = e^5 - d^5 %
for a := 1 until MAX_NUMBER do begin
integer loA, hiA;
loA := lo5( a ); hiA := hi5( a );
for b := a until MAX_NUMBER do begin
integer loB, hiB;
loB := lo5( b ); hiB := hi5( b );
for c := b until MAX_NUMBER do begin
integer low, high, loSum, hiSum;
loSum := loA + loB + lo5( c );
hiSum := ( loSum div MAX_V ) + hiA + hiB + hi5( c );
loSum := loSum rem MAX_V;
% look for hiSum,loSum in hiD,loD %
low := 1;
high := dUsed;
while low < high do begin
integer mid, cmp;
mid := ( low + high ) div 2;
cmp := hiD( mid ) - hiSum;
if cmp = 0 then cmp := loD( mid ) - loSum;
if cmp = 0 then begin
% the value at mid is the difference of two fifth powers %
write( i_w := 1, s_w := 0
, a, "^5 + ", b, "^5 + ", c, "^5 + "
, Dd( mid ), "^5 = ", De( mid ), "^5"
);
go to found
end
else if cmp > 0 then high := mid - 1
else low := mid + 1
end while_low_lt_high
end for_c
end for_b
end for_a ;
found :
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
| #MAXScript | MAXScript | fn factorial n =
(
if n == 0 then return 1
local fac = 1
for i in 1 to n do
(
fac *= i
)
fac
) |
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.
| #Agda | Agda | even : ℕ → Bool
odd : ℕ → Bool
even zero = true
even (suc n) = odd n
odd zero = false
odd (suc n) = even n |
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.
| #Aime | Aime | if (x & 1) {
# x is odd
} else {
# x is even
} |
http://rosettacode.org/wiki/Euler_method | Euler method | Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value. It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page.
The ODE has to be provided in the following form:
d
y
(
t
)
d
t
=
f
(
t
,
y
(
t
)
)
{\displaystyle {\frac {dy(t)}{dt}}=f(t,y(t))}
with an initial value
y
(
t
0
)
=
y
0
{\displaystyle y(t_{0})=y_{0}}
To get a numeric solution, we replace the derivative on the LHS with a finite difference approximation:
d
y
(
t
)
d
t
≈
y
(
t
+
h
)
−
y
(
t
)
h
{\displaystyle {\frac {dy(t)}{dt}}\approx {\frac {y(t+h)-y(t)}{h}}}
then solve for
y
(
t
+
h
)
{\displaystyle y(t+h)}
:
y
(
t
+
h
)
≈
y
(
t
)
+
h
d
y
(
t
)
d
t
{\displaystyle y(t+h)\approx y(t)+h\,{\frac {dy(t)}{dt}}}
which is the same as
y
(
t
+
h
)
≈
y
(
t
)
+
h
f
(
t
,
y
(
t
)
)
{\displaystyle y(t+h)\approx y(t)+h\,f(t,y(t))}
The iterative solution rule is then:
y
n
+
1
=
y
n
+
h
f
(
t
n
,
y
n
)
{\displaystyle y_{n+1}=y_{n}+h\,f(t_{n},y_{n})}
where
h
{\displaystyle h}
is the step size, the most relevant parameter for accuracy of the solution. A smaller step size increases accuracy but also the computation cost, so it has always has to be hand-picked according to the problem at hand.
Example: Newton's Cooling Law
Newton's cooling law describes how an object of initial temperature
T
(
t
0
)
=
T
0
{\displaystyle T(t_{0})=T_{0}}
cools down in an environment of temperature
T
R
{\displaystyle T_{R}}
:
d
T
(
t
)
d
t
=
−
k
Δ
T
{\displaystyle {\frac {dT(t)}{dt}}=-k\,\Delta T}
or
d
T
(
t
)
d
t
=
−
k
(
T
(
t
)
−
T
R
)
{\displaystyle {\frac {dT(t)}{dt}}=-k\,(T(t)-T_{R})}
It says that the cooling rate
d
T
(
t
)
d
t
{\displaystyle {\frac {dT(t)}{dt}}}
of the object is proportional to the current temperature difference
Δ
T
=
(
T
(
t
)
−
T
R
)
{\displaystyle \Delta T=(T(t)-T_{R})}
to the surrounding environment.
The analytical solution, which we will compare to the numerical approximation, is
T
(
t
)
=
T
R
+
(
T
0
−
T
R
)
e
−
k
t
{\displaystyle T(t)=T_{R}+(T_{0}-T_{R})\;e^{-kt}}
Task
Implement a routine of Euler's method and then to use it to solve the given example of Newton's cooling law with it for three different step sizes of:
2 s
5 s and
10 s
and to compare with the analytical solution.
Initial values
initial temperature
T
0
{\displaystyle T_{0}}
shall be 100 °C
room temperature
T
R
{\displaystyle T_{R}}
shall be 20 °C
cooling constant
k
{\displaystyle k}
shall be 0.07
time interval to calculate shall be from 0 s ──► 100 s
A reference solution (Common Lisp) can be seen below. We see that bigger step sizes lead to reduced approximation accuracy.
| #Groovy | Groovy | def eulerStep = { xn, yn, h, dydx ->
(yn + h * dydx(xn, yn)) as BigDecimal
}
Map eulerMapping = { x0, y0, h, dydx, stopCond = { xx, yy, hh, xx0 -> abs(xx - xx0) > (hh * 100) }.rcurry(h, x0) ->
Map yMap = [:]
yMap[x0] = y0 as BigDecimal
def x = x0
while (!stopCond(x, yMap[x])) {
yMap[x + h] = eulerStep(x, yMap[x], h, dydx)
x += h
}
yMap
}
assert eulerMapping.maximumNumberOfParameters == 5 |
http://rosettacode.org/wiki/Evaluate_binomial_coefficients | Evaluate binomial coefficients | This programming task, is to calculate ANY binomial coefficient.
However, it has to be able to output
(
5
3
)
{\displaystyle {\binom {5}{3}}}
, which is 10.
This formula is recommended:
(
n
k
)
=
n
!
(
n
−
k
)
!
k
!
=
n
(
n
−
1
)
(
n
−
2
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
(
k
−
2
)
…
1
{\displaystyle {\binom {n}{k}}={\frac {n!}{(n-k)!k!}}={\frac {n(n-1)(n-2)\ldots (n-k+1)}{k(k-1)(k-2)\ldots 1}}}
See Also:
Combinations and permutations
Pascal's triangle
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #Bracmat | Bracmat | (binomial=
n k coef
. !arg:(?n,?k)
& (!n+-1*!k:<!k:?k|)
& 1:?coef
& whl
' ( !k:>0
& !coef*!n*!k^-1:?coef
& !k+-1:?k
& !n+-1:?n
)
& !coef
);
binomial$(5,3)
10
|
http://rosettacode.org/wiki/Evaluate_binomial_coefficients | Evaluate binomial coefficients | This programming task, is to calculate ANY binomial coefficient.
However, it has to be able to output
(
5
3
)
{\displaystyle {\binom {5}{3}}}
, which is 10.
This formula is recommended:
(
n
k
)
=
n
!
(
n
−
k
)
!
k
!
=
n
(
n
−
1
)
(
n
−
2
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
(
k
−
2
)
…
1
{\displaystyle {\binom {n}{k}}={\frac {n!}{(n-k)!k!}}={\frac {n(n-1)(n-2)\ldots (n-k+1)}{k(k-1)(k-2)\ldots 1}}}
See Also:
Combinations and permutations
Pascal's triangle
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #Burlesque | Burlesque |
blsq ) 5 3nr
10
|
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
Fn = Fn+2 - Fn+1, if n<0
support for negative n in the solution is optional.
Related tasks
Fibonacci n-step number sequences
Leonardo numbers
References
Wikipedia, Fibonacci number
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #VBA | VBA | Public Function Fib(ByVal n As Integer) As Variant
Dim fib0 As Variant, fib1 As Variant, sum As Variant
Dim i As Integer
fib0 = 0
fib1 = 1
For i = 1 To n
sum = fib0 + fib1
fib0 = fib1
fib1 = sum
Next i
Fib = fib0
End Function |
http://rosettacode.org/wiki/Equal_prime_and_composite_sums | Equal prime and composite sums | Suppose we have a sequence of prime sums, where each term Pn is the sum of the first n primes.
P = (2), (2 + 3), (2 + 3 + 5), (2 + 3 + 5 + 7), (2 + 3 + 5 + 7 + 11), ...
P = 2, 5, 10, 17, 28, etc.
Further; suppose we have a sequence of composite sums, where each term Cm is the sum of the first m composites.
C = (4), (4 + 6), (4 + 6 + 8), (4 + 6 + 8 + 9), (4 + 6 + 8 + 9 + 10), ...
C = 4, 10, 18, 27, 37, etc.
Notice that the third term of P; P3 (10) is equal to the second term of C; C2 (10);
Task
Find and display the indices (n, m) and value of at least the first 6 terms of the sequence of numbers that are both the sum of the first n primes and the first m composites.
See also
OEIS:A007504 - Sum of the first n primes
OEIS:A053767 - Sum of first n composite numbers
OEIS:A294174 - Numbers that can be expressed both as the sum of first primes and as the sum of first composites
| #Sidef | Sidef | func f(n) {
var (
p = 2, sp = p,
c = 4, sc = c,
)
var res = []
while (res.len < n) {
if (sc == sp) {
res << [sp, c.composite_count, p.prime_count]
sc += c.next_composite!
}
while (sp < sc) {
sp += p.next_prime!
}
while (sc < sp) {
sc += c.next_composite!
}
}
return res
}
f(8).each_2d {|n, ci, pi|
printf("%12s = %-9s = %s\n", n, "P(#{pi})", "C(#{ci})")
} |
http://rosettacode.org/wiki/Equal_prime_and_composite_sums | Equal prime and composite sums | Suppose we have a sequence of prime sums, where each term Pn is the sum of the first n primes.
P = (2), (2 + 3), (2 + 3 + 5), (2 + 3 + 5 + 7), (2 + 3 + 5 + 7 + 11), ...
P = 2, 5, 10, 17, 28, etc.
Further; suppose we have a sequence of composite sums, where each term Cm is the sum of the first m composites.
C = (4), (4 + 6), (4 + 6 + 8), (4 + 6 + 8 + 9), (4 + 6 + 8 + 9 + 10), ...
C = 4, 10, 18, 27, 37, etc.
Notice that the third term of P; P3 (10) is equal to the second term of C; C2 (10);
Task
Find and display the indices (n, m) and value of at least the first 6 terms of the sequence of numbers that are both the sum of the first n primes and the first m composites.
See also
OEIS:A007504 - Sum of the first n primes
OEIS:A053767 - Sum of first n composite numbers
OEIS:A294174 - Numbers that can be expressed both as the sum of first primes and as the sum of first composites
| #Wren | Wren | import "./math" for Int
import "./sort" for Find
import "/fmt" for Fmt
var limit = 4 * 1e8
var c = Int.primeSieve(limit - 1, false)
var compSums = []
var primeSums = []
var csum = 0
var psum = 0
for (i in 2...limit) {
if (c[i]) {
csum = csum + i
compSums.add(csum)
} else {
psum = psum + i
primeSums.add(psum)
}
}
for (i in 0...primeSums.count) {
var ix
if ((ix = Find.first(compSums, primeSums[i])) >= 0) {
Fmt.print("$,21d - $,12r prime sum, $,12r composite sum", primeSums[i], i+1, ix+1)
}
} |
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
| #Action.21 | Action! | INT FUNC EthopianMult(INT a,b)
INT res
PrintF("Ethopian multiplication %I by %I:%E",a,b)
res=0
WHILE a>=1
DO
IF a MOD 2=0 THEN
PrintF("%I %I strike%E",a,b)
ELSE
PrintF("%I %I keep%E",a,b)
res==+b
FI
a==/2
b==*2
OD
RETURN (res)
PROC Main()
INT res
res=EthopianMult(17,34)
PrintF("Result is %I",res)
RETURN |
http://rosettacode.org/wiki/Equilibrium_index | Equilibrium index | An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices.
For example, in a sequence
A
{\displaystyle A}
:
A
0
=
−
7
{\displaystyle A_{0}=-7}
A
1
=
1
{\displaystyle A_{1}=1}
A
2
=
5
{\displaystyle A_{2}=5}
A
3
=
2
{\displaystyle A_{3}=2}
A
4
=
−
4
{\displaystyle A_{4}=-4}
A
5
=
3
{\displaystyle A_{5}=3}
A
6
=
0
{\displaystyle A_{6}=0}
3 is an equilibrium index, because:
A
0
+
A
1
+
A
2
=
A
4
+
A
5
+
A
6
{\displaystyle A_{0}+A_{1}+A_{2}=A_{4}+A_{5}+A_{6}}
6 is also an equilibrium index, because:
A
0
+
A
1
+
A
2
+
A
3
+
A
4
+
A
5
=
0
{\displaystyle A_{0}+A_{1}+A_{2}+A_{3}+A_{4}+A_{5}=0}
(sum of zero elements is zero)
7 is not an equilibrium index, because it is not a valid index of sequence
A
{\displaystyle A}
.
Task;
Write a function that, given a sequence, returns its equilibrium indices (if any).
Assume that the sequence may be very long.
| #11l | 11l | F eqindex(arr)
R (0 .< arr.len).filter(i -> sum(@arr[0.<i]) == sum(@arr[i+1..]))
print(eqindex([-7, 1, 5, 2, -4, 3, 0])) |
http://rosettacode.org/wiki/Environment_variables | Environment variables | Task
Show how to get one of your process's environment variables.
The available variables vary by system; some of the common ones available on Unix include:
PATH
HOME
USER
| #11l | 11l | print(os:getenv(‘HOME’)) |
http://rosettacode.org/wiki/Esthetic_numbers | Esthetic numbers | An esthetic number is a positive integer where every adjacent digit differs from its neighbour by 1.
E.G.
12 is an esthetic number. One and two differ by 1.
5654 is an esthetic number. Each digit is exactly 1 away from its neighbour.
890 is not an esthetic number. Nine and zero differ by 9.
These examples are nominally in base 10 but the concept extends easily to numbers in other bases. Traditionally, single digit numbers are included in esthetic numbers; zero may or may not be. For our purposes, for this task, do not include zero (0) as an esthetic number. Do not include numbers with leading zeros.
Esthetic numbers are also sometimes referred to as stepping numbers.
Task
Write a routine (function, procedure, whatever) to find esthetic numbers in a given base.
Use that routine to find esthetic numbers in bases 2 through 16 and display, here on this page, the esthectic numbers from index (base × 4) through index (base × 6), inclusive. (E.G. for base 2: 8th through 12th, for base 6: 24th through 36th, etc.)
Find and display, here on this page, the base 10 esthetic numbers with a magnitude between 1000 and 9999.
Stretch: Find and display, here on this page, the base 10 esthetic numbers with a magnitude between 1.0e8 and 1.3e8.
Related task
numbers with equal rises and falls
See also
OEIS A033075 - Positive numbers n such that all pairs of consecutive decimal digits differ by 1
Numbers Aplenty - Esthetic numbers
Geeks for Geeks - Stepping numbers
| #Haskell | Haskell | import Data.List (unfoldr, genericIndex)
import Control.Monad (replicateM, foldM, mzero)
-- a predicate for esthetic numbers
isEsthetic b = all ((== 1) . abs) . differences . toBase b
where
differences lst = zipWith (-) lst (tail lst)
-- Monadic solution, inefficient for small bases.
esthetics_m b =
do differences <- (\n -> replicateM n [-1, 1]) <$> [0..]
firstDigit <- [1..b-1]
differences >>= fromBase b <$> scanl (+) firstDigit
-- Much more efficient iterative solution (translation from Python).
-- Uses simple list as an ersatz queue.
esthetics b = tail $ fst <$> iterate step (undefined, q)
where
q = [(d, d) | d <- [1..b-1]]
step (_, queue) =
let (num, lsd) = head queue
new_lsds = [d | d <- [lsd-1, lsd+1], d < b, d >= 0]
in (num, tail queue ++ [(num*b + d, d) | d <- new_lsds])
-- representation of numbers as digits
fromBase b = foldM f 0
where f r d | d < 0 || d >= b = mzero
| otherwise = pure (r*b + d)
toBase b = reverse . unfoldr f
where
f 0 = Nothing
f n = let (q, r) = divMod n b in Just (r, q)
showInBase b = foldMap (pure . digit) . toBase b
where digit = genericIndex (['0'..'9'] <> ['a'..'z'])
|
http://rosettacode.org/wiki/Euler%27s_sum_of_powers_conjecture | Euler's sum of powers conjecture | There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin.
Euler's (disproved) sum of powers conjecture
At least k positive kth powers are required to sum to a kth power,
except for the trivial case of one kth power: yk = yk
In 1966, Leon J. Lander and Thomas R. Parkin used a brute-force search on a CDC 6600 computer restricting numbers to those less than 250.
Task
Write a program to search for an integer solution for:
x05 + x15 + x25 + x35 == y5
Where all xi's and y are distinct integers between 0 and 250 (exclusive).
Show an answer here.
Related tasks
Pythagorean quadruples.
Pythagorean triples.
| #Arturo | Arturo | eulerSumOfPowers: function [top][
p5: map 0..top => [& ^ 5]
loop 4..top 'a [
loop 3..a-1 'b [
loop 2..b-1 'c [
loop 1..c-1 'd [
s: (get p5 a) + (get p5 b) + (get p5 c) + (get p5 d)
if integer? index p5 s ->
return ~"|a|^5 + |b|^5 + |c|^5 + |d|^5 = |index p5 s|^5"
]
]
]
]
return "not found" ; shouldn't reach here
]
print eulerSumOfPowers 249 |
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
| #Mercury | Mercury | :- module factorial.
:- interface.
:- import_module integer.
:- func factorial(integer) = integer.
:- implementation.
:- pragma memo(factorial/1).
factorial(N) =
( N =< integer(0)
-> integer(1)
; factorial(N - integer(1)) * N
). |
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.
| #ALGOL_68 | ALGOL 68 | # Algol 68 has a standard operator: ODD which returns TRUE if its integer #
# operand is odd and FALSE if it is even #
# E.g.: #
INT n;
print( ( "Enter an integer: " ) );
read( ( n ) );
print( ( whole( n, 0 ), " is ", IF ODD n THEN "odd" ELSE "even" FI, newline ) )
|
http://rosettacode.org/wiki/Euler_method | Euler method | Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value. It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page.
The ODE has to be provided in the following form:
d
y
(
t
)
d
t
=
f
(
t
,
y
(
t
)
)
{\displaystyle {\frac {dy(t)}{dt}}=f(t,y(t))}
with an initial value
y
(
t
0
)
=
y
0
{\displaystyle y(t_{0})=y_{0}}
To get a numeric solution, we replace the derivative on the LHS with a finite difference approximation:
d
y
(
t
)
d
t
≈
y
(
t
+
h
)
−
y
(
t
)
h
{\displaystyle {\frac {dy(t)}{dt}}\approx {\frac {y(t+h)-y(t)}{h}}}
then solve for
y
(
t
+
h
)
{\displaystyle y(t+h)}
:
y
(
t
+
h
)
≈
y
(
t
)
+
h
d
y
(
t
)
d
t
{\displaystyle y(t+h)\approx y(t)+h\,{\frac {dy(t)}{dt}}}
which is the same as
y
(
t
+
h
)
≈
y
(
t
)
+
h
f
(
t
,
y
(
t
)
)
{\displaystyle y(t+h)\approx y(t)+h\,f(t,y(t))}
The iterative solution rule is then:
y
n
+
1
=
y
n
+
h
f
(
t
n
,
y
n
)
{\displaystyle y_{n+1}=y_{n}+h\,f(t_{n},y_{n})}
where
h
{\displaystyle h}
is the step size, the most relevant parameter for accuracy of the solution. A smaller step size increases accuracy but also the computation cost, so it has always has to be hand-picked according to the problem at hand.
Example: Newton's Cooling Law
Newton's cooling law describes how an object of initial temperature
T
(
t
0
)
=
T
0
{\displaystyle T(t_{0})=T_{0}}
cools down in an environment of temperature
T
R
{\displaystyle T_{R}}
:
d
T
(
t
)
d
t
=
−
k
Δ
T
{\displaystyle {\frac {dT(t)}{dt}}=-k\,\Delta T}
or
d
T
(
t
)
d
t
=
−
k
(
T
(
t
)
−
T
R
)
{\displaystyle {\frac {dT(t)}{dt}}=-k\,(T(t)-T_{R})}
It says that the cooling rate
d
T
(
t
)
d
t
{\displaystyle {\frac {dT(t)}{dt}}}
of the object is proportional to the current temperature difference
Δ
T
=
(
T
(
t
)
−
T
R
)
{\displaystyle \Delta T=(T(t)-T_{R})}
to the surrounding environment.
The analytical solution, which we will compare to the numerical approximation, is
T
(
t
)
=
T
R
+
(
T
0
−
T
R
)
e
−
k
t
{\displaystyle T(t)=T_{R}+(T_{0}-T_{R})\;e^{-kt}}
Task
Implement a routine of Euler's method and then to use it to solve the given example of Newton's cooling law with it for three different step sizes of:
2 s
5 s and
10 s
and to compare with the analytical solution.
Initial values
initial temperature
T
0
{\displaystyle T_{0}}
shall be 100 °C
room temperature
T
R
{\displaystyle T_{R}}
shall be 20 °C
cooling constant
k
{\displaystyle k}
shall be 0.07
time interval to calculate shall be from 0 s ──► 100 s
A reference solution (Common Lisp) can be seen below. We see that bigger step sizes lead to reduced approximation accuracy.
| #Haskell | Haskell | -- the solver
dsolveBy _ _ [] _ = error "empty solution interval"
dsolveBy method f mesh x0 = zip mesh results
where results = scanl (method f) x0 intervals
intervals = zip mesh (tail mesh) |
http://rosettacode.org/wiki/Euler_method | Euler method | Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value. It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page.
The ODE has to be provided in the following form:
d
y
(
t
)
d
t
=
f
(
t
,
y
(
t
)
)
{\displaystyle {\frac {dy(t)}{dt}}=f(t,y(t))}
with an initial value
y
(
t
0
)
=
y
0
{\displaystyle y(t_{0})=y_{0}}
To get a numeric solution, we replace the derivative on the LHS with a finite difference approximation:
d
y
(
t
)
d
t
≈
y
(
t
+
h
)
−
y
(
t
)
h
{\displaystyle {\frac {dy(t)}{dt}}\approx {\frac {y(t+h)-y(t)}{h}}}
then solve for
y
(
t
+
h
)
{\displaystyle y(t+h)}
:
y
(
t
+
h
)
≈
y
(
t
)
+
h
d
y
(
t
)
d
t
{\displaystyle y(t+h)\approx y(t)+h\,{\frac {dy(t)}{dt}}}
which is the same as
y
(
t
+
h
)
≈
y
(
t
)
+
h
f
(
t
,
y
(
t
)
)
{\displaystyle y(t+h)\approx y(t)+h\,f(t,y(t))}
The iterative solution rule is then:
y
n
+
1
=
y
n
+
h
f
(
t
n
,
y
n
)
{\displaystyle y_{n+1}=y_{n}+h\,f(t_{n},y_{n})}
where
h
{\displaystyle h}
is the step size, the most relevant parameter for accuracy of the solution. A smaller step size increases accuracy but also the computation cost, so it has always has to be hand-picked according to the problem at hand.
Example: Newton's Cooling Law
Newton's cooling law describes how an object of initial temperature
T
(
t
0
)
=
T
0
{\displaystyle T(t_{0})=T_{0}}
cools down in an environment of temperature
T
R
{\displaystyle T_{R}}
:
d
T
(
t
)
d
t
=
−
k
Δ
T
{\displaystyle {\frac {dT(t)}{dt}}=-k\,\Delta T}
or
d
T
(
t
)
d
t
=
−
k
(
T
(
t
)
−
T
R
)
{\displaystyle {\frac {dT(t)}{dt}}=-k\,(T(t)-T_{R})}
It says that the cooling rate
d
T
(
t
)
d
t
{\displaystyle {\frac {dT(t)}{dt}}}
of the object is proportional to the current temperature difference
Δ
T
=
(
T
(
t
)
−
T
R
)
{\displaystyle \Delta T=(T(t)-T_{R})}
to the surrounding environment.
The analytical solution, which we will compare to the numerical approximation, is
T
(
t
)
=
T
R
+
(
T
0
−
T
R
)
e
−
k
t
{\displaystyle T(t)=T_{R}+(T_{0}-T_{R})\;e^{-kt}}
Task
Implement a routine of Euler's method and then to use it to solve the given example of Newton's cooling law with it for three different step sizes of:
2 s
5 s and
10 s
and to compare with the analytical solution.
Initial values
initial temperature
T
0
{\displaystyle T_{0}}
shall be 100 °C
room temperature
T
R
{\displaystyle T_{R}}
shall be 20 °C
cooling constant
k
{\displaystyle k}
shall be 0.07
time interval to calculate shall be from 0 s ──► 100 s
A reference solution (Common Lisp) can be seen below. We see that bigger step sizes lead to reduced approximation accuracy.
| #Icon_and_Unicon | Icon and Unicon |
invocable "newton_cooling" # needed to use the 'proc' procedure
procedure euler (f, y0, a, b, h)
t := a
y := y0
until (t >= b) do {
write (right(t, 4) || " " || left(y, 7))
t +:= h
y +:= h * (proc(f) (t, y)) # 'proc' applies procedure named in f to (t, y)
}
write ("DONE")
end
procedure newton_cooling (time, T)
return -0.07 * (T - 20)
end
procedure main ()
# generate data for all three step sizes [2, 5, 10]
every (step_size := ![2,5,10]) do
euler ("newton_cooling", 100, 0, 100, step_size)
end
|
http://rosettacode.org/wiki/Evaluate_binomial_coefficients | Evaluate binomial coefficients | This programming task, is to calculate ANY binomial coefficient.
However, it has to be able to output
(
5
3
)
{\displaystyle {\binom {5}{3}}}
, which is 10.
This formula is recommended:
(
n
k
)
=
n
!
(
n
−
k
)
!
k
!
=
n
(
n
−
1
)
(
n
−
2
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
(
k
−
2
)
…
1
{\displaystyle {\binom {n}{k}}={\frac {n!}{(n-k)!k!}}={\frac {n(n-1)(n-2)\ldots (n-k+1)}{k(k-1)(k-2)\ldots 1}}}
See Also:
Combinations and permutations
Pascal's triangle
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #C | C | #include <stdio.h>
#include <limits.h>
/* We go to some effort to handle overflow situations */
static unsigned long gcd_ui(unsigned long x, unsigned long y) {
unsigned long t;
if (y < x) { t = x; x = y; y = t; }
while (y > 0) {
t = y; y = x % y; x = t; /* y1 <- x0 % y0 ; x1 <- y0 */
}
return x;
}
unsigned long binomial(unsigned long n, unsigned long k) {
unsigned long d, g, r = 1;
if (k == 0) return 1;
if (k == 1) return n;
if (k >= n) return (k == n);
if (k > n/2) k = n-k;
for (d = 1; d <= k; d++) {
if (r >= ULONG_MAX/n) { /* Possible overflow */
unsigned long nr, dr; /* reduced numerator / denominator */
g = gcd_ui(n, d); nr = n/g; dr = d/g;
g = gcd_ui(r, dr); r = r/g; dr = dr/g;
if (r >= ULONG_MAX/nr) return 0; /* Unavoidable overflow */
r *= nr;
r /= dr;
n--;
} else {
r *= n--;
r /= d;
}
}
return r;
}
int main() {
printf("%lu\n", binomial(5, 3));
printf("%lu\n", binomial(40, 19));
printf("%lu\n", binomial(67, 31));
return 0;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.