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/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
| #Klingphix | Klingphix | { recursive }
:factorial
dup 1 great (
[dup 1 - factorial *]
[drop 1]
) if
;
{ iterative }
:factorial2
1 swap [*] for
;
( 0 22 ) [
"Factorial(" print dup print ") = " print factorial2 print nl
] for
" " input |
http://rosettacode.org/wiki/Euler%27s_identity | Euler's identity |
This page uses content from Wikipedia. The original article was at Euler's_identity. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In mathematics, Euler's identity is the equality:
ei
π
{\displaystyle \pi }
+ 1 = 0
where
e is Euler's number, the base of natural logarithms,
i is the imaginary unit, which satisfies i2 = −1, and
π
{\displaystyle \pi }
is pi, the ratio of the circumference of a circle to its diameter.
Euler's identity is often cited as an example of deep mathematical beauty. Three of the basic arithmetic operations occur exactly once each: addition, multiplication, and exponentiation. The identity also links five fundamental mathematical constants:
The number 0.
The number 1.
The number
π
{\displaystyle \pi }
(
π
{\displaystyle \pi }
= 3.14159+),
The number e (e = 2.71828+), which occurs widely in mathematical analysis.
The number i, the imaginary unit of the complex numbers.
Task
Show in your language that Euler's identity is true. As much as possible and practical, mimic the Euler's identity equation.
Most languages are limited to IEEE 754 floating point calculations so will have some error in the calculation.
If that is the case, or there is some other limitation, show
that ei
π
{\displaystyle \pi }
+ 1 is approximately equal to zero and
show the amount of error in the calculation.
If your language is capable of symbolic calculations, show
that ei
π
{\displaystyle \pi }
+ 1 is exactly equal to zero for bonus kudos points.
| #F.23 | F# |
printfn "-1 + 1 = %d" (-1+1)
|
http://rosettacode.org/wiki/Euler%27s_identity | Euler's identity |
This page uses content from Wikipedia. The original article was at Euler's_identity. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In mathematics, Euler's identity is the equality:
ei
π
{\displaystyle \pi }
+ 1 = 0
where
e is Euler's number, the base of natural logarithms,
i is the imaginary unit, which satisfies i2 = −1, and
π
{\displaystyle \pi }
is pi, the ratio of the circumference of a circle to its diameter.
Euler's identity is often cited as an example of deep mathematical beauty. Three of the basic arithmetic operations occur exactly once each: addition, multiplication, and exponentiation. The identity also links five fundamental mathematical constants:
The number 0.
The number 1.
The number
π
{\displaystyle \pi }
(
π
{\displaystyle \pi }
= 3.14159+),
The number e (e = 2.71828+), which occurs widely in mathematical analysis.
The number i, the imaginary unit of the complex numbers.
Task
Show in your language that Euler's identity is true. As much as possible and practical, mimic the Euler's identity equation.
Most languages are limited to IEEE 754 floating point calculations so will have some error in the calculation.
If that is the case, or there is some other limitation, show
that ei
π
{\displaystyle \pi }
+ 1 is approximately equal to zero and
show the amount of error in the calculation.
If your language is capable of symbolic calculations, show
that ei
π
{\displaystyle \pi }
+ 1 is exactly equal to zero for bonus kudos points.
| #Factor | Factor | USING: math math.constants math.functions prettyprint ;
1 e pi C{ 0 1 } * ^ + . |
http://rosettacode.org/wiki/Euler%27s_identity | Euler's identity |
This page uses content from Wikipedia. The original article was at Euler's_identity. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In mathematics, Euler's identity is the equality:
ei
π
{\displaystyle \pi }
+ 1 = 0
where
e is Euler's number, the base of natural logarithms,
i is the imaginary unit, which satisfies i2 = −1, and
π
{\displaystyle \pi }
is pi, the ratio of the circumference of a circle to its diameter.
Euler's identity is often cited as an example of deep mathematical beauty. Three of the basic arithmetic operations occur exactly once each: addition, multiplication, and exponentiation. The identity also links five fundamental mathematical constants:
The number 0.
The number 1.
The number
π
{\displaystyle \pi }
(
π
{\displaystyle \pi }
= 3.14159+),
The number e (e = 2.71828+), which occurs widely in mathematical analysis.
The number i, the imaginary unit of the complex numbers.
Task
Show in your language that Euler's identity is true. As much as possible and practical, mimic the Euler's identity equation.
Most languages are limited to IEEE 754 floating point calculations so will have some error in the calculation.
If that is the case, or there is some other limitation, show
that ei
π
{\displaystyle \pi }
+ 1 is approximately equal to zero and
show the amount of error in the calculation.
If your language is capable of symbolic calculations, show
that ei
π
{\displaystyle \pi }
+ 1 is exactly equal to zero for bonus kudos points.
| #Forth | Forth |
." e^(i*π) + 1 = " pi fcos 1e0 f+ f. '+ emit space pi fsin fs. 'i emit cr
bye
|
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
| #SNOBOL4 | SNOBOL4 | define("fib(a)") :(fib_end)
fib fib = lt(a,2) a :s(return)
fib = fib(a - 1) + fib(a - 2) :(return)
fib_end
while a = trim(input) :f(end)
output = a " " fib(a) :(while)
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
| #Klong | Klong |
factRecursive::{:[x>1;x*.f(x-1);1]}
factIterative::{*/1+!x}
|
http://rosettacode.org/wiki/Euler%27s_identity | Euler's identity |
This page uses content from Wikipedia. The original article was at Euler's_identity. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In mathematics, Euler's identity is the equality:
ei
π
{\displaystyle \pi }
+ 1 = 0
where
e is Euler's number, the base of natural logarithms,
i is the imaginary unit, which satisfies i2 = −1, and
π
{\displaystyle \pi }
is pi, the ratio of the circumference of a circle to its diameter.
Euler's identity is often cited as an example of deep mathematical beauty. Three of the basic arithmetic operations occur exactly once each: addition, multiplication, and exponentiation. The identity also links five fundamental mathematical constants:
The number 0.
The number 1.
The number
π
{\displaystyle \pi }
(
π
{\displaystyle \pi }
= 3.14159+),
The number e (e = 2.71828+), which occurs widely in mathematical analysis.
The number i, the imaginary unit of the complex numbers.
Task
Show in your language that Euler's identity is true. As much as possible and practical, mimic the Euler's identity equation.
Most languages are limited to IEEE 754 floating point calculations so will have some error in the calculation.
If that is the case, or there is some other limitation, show
that ei
π
{\displaystyle \pi }
+ 1 is approximately equal to zero and
show the amount of error in the calculation.
If your language is capable of symbolic calculations, show
that ei
π
{\displaystyle \pi }
+ 1 is exactly equal to zero for bonus kudos points.
| #Fortran | Fortran |
program euler
use iso_fortran_env, only: output_unit, REAL64
implicit none
integer, parameter :: d=REAL64
real(kind=d), parameter :: e=exp(1._d), pi=4._d*atan(1._d)
complex(kind=d), parameter :: i=(0._d,1._d)
write(output_unit,*) e**(pi*i) + 1
end program euler
|
http://rosettacode.org/wiki/Euler%27s_identity | Euler's identity |
This page uses content from Wikipedia. The original article was at Euler's_identity. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In mathematics, Euler's identity is the equality:
ei
π
{\displaystyle \pi }
+ 1 = 0
where
e is Euler's number, the base of natural logarithms,
i is the imaginary unit, which satisfies i2 = −1, and
π
{\displaystyle \pi }
is pi, the ratio of the circumference of a circle to its diameter.
Euler's identity is often cited as an example of deep mathematical beauty. Three of the basic arithmetic operations occur exactly once each: addition, multiplication, and exponentiation. The identity also links five fundamental mathematical constants:
The number 0.
The number 1.
The number
π
{\displaystyle \pi }
(
π
{\displaystyle \pi }
= 3.14159+),
The number e (e = 2.71828+), which occurs widely in mathematical analysis.
The number i, the imaginary unit of the complex numbers.
Task
Show in your language that Euler's identity is true. As much as possible and practical, mimic the Euler's identity equation.
Most languages are limited to IEEE 754 floating point calculations so will have some error in the calculation.
If that is the case, or there is some other limitation, show
that ei
π
{\displaystyle \pi }
+ 1 is approximately equal to zero and
show the amount of error in the calculation.
If your language is capable of symbolic calculations, show
that ei
π
{\displaystyle \pi }
+ 1 is exactly equal to zero for bonus kudos points.
| #FreeBASIC | FreeBASIC | #define PI 3.141592653589793238462643383279502884197169399375105821
#define MAXITER 12
'---------------------------------------
' complex numbers and their arithmetic
'---------------------------------------
type complex
r as double
i as double
end type
function conj( a as complex ) as complex
dim as complex c
c.r = a.r
c.i = -a.i
return c
end function
operator + ( a as complex, b as complex ) as complex
dim as complex c
c.r = a.r + b.r
c.i = a.i + b.i
return c
end operator
operator - ( a as complex, b as complex ) as complex
dim as complex c
c.r = a.r - b.r
c.i = a.i - b.i
return c
end operator
operator * ( a as complex, b as complex ) as complex
dim as complex c
c.r = a.r*b.r - a.i*b.i
c.i = a.i*b.r + a.r*b.i
return c
end operator
operator / ( a as complex, b as complex ) as complex
dim as double bcb = (b*conj(b)).r
dim as complex acb = a*conj(b), c
c.r = acb.r/bcb
c.i = acb.i/bcb
return c
end operator
sub printc( a as complex )
if a.i>=0 then
print using "############.############### + ############.############### i"; a.r; a.i
else
print using "############.############### - ############.############### i"; a.r; -a.i
end if
end sub
function intc( n as integer ) as complex
dim as complex c
c.r = n
c.i = 0.0
return c
end function
function absc( a as complex ) as double
return sqr( (a*conj(a)).r )
end function
'-----------------------
' the algorithm
' Uses a rapidly converging continued
' fraction expansion for e^z and recursive
' expressions for its convergents
'-----------------------
dim as complex pii, pii2, curr, A2, A1, A0, B2, B1, B0
dim as complex ONE, TWO
dim as integer i, k = 2
pii.r = 0.0
pii.i = PI
pii2 = pii*pii
B0 = intc(2)
A0 = intc(2)
B1 = (intc(2) - pii)
A1 = B0*B1 + intc(2)*pii
printc( A0/B0)
print " Absolute error = ", absc(A0/B0)
printc( A1/B1)
print " Absolute error = ", absc(A1/B1)
for i = 1 to MAXITER
k = k + 4
A2 = intc(k)*A1 + pii2*A0
B2 = intc(k)*B1 + pii2*B0
curr = A2/B2
A0 = A1
A1 = A2
B0 = B1
B1 = B2
printc( curr )
print " Absolute error = ", absc(curr)
next i |
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
| #SNUSP | SNUSP | @!\+++++++++# /<<+>+>-\
fib\==>>+<<?!/>!\ ?/\
#<</?\!>/@>\?-<<</@>/@>/>+<-\
\-/ \ !\ !\ !\ ?/# |
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
| #KonsolScript | KonsolScript | function factorial(Number n):Number {
Var:Number ret;
if (n >= 0) {
ret = 1;
Var:Number i = 1;
for (i = 1; i <= n; i++) {
ret = ret * i;
}
} else {
ret = 0;
}
return ret;
} |
http://rosettacode.org/wiki/Euler%27s_identity | Euler's identity |
This page uses content from Wikipedia. The original article was at Euler's_identity. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In mathematics, Euler's identity is the equality:
ei
π
{\displaystyle \pi }
+ 1 = 0
where
e is Euler's number, the base of natural logarithms,
i is the imaginary unit, which satisfies i2 = −1, and
π
{\displaystyle \pi }
is pi, the ratio of the circumference of a circle to its diameter.
Euler's identity is often cited as an example of deep mathematical beauty. Three of the basic arithmetic operations occur exactly once each: addition, multiplication, and exponentiation. The identity also links five fundamental mathematical constants:
The number 0.
The number 1.
The number
π
{\displaystyle \pi }
(
π
{\displaystyle \pi }
= 3.14159+),
The number e (e = 2.71828+), which occurs widely in mathematical analysis.
The number i, the imaginary unit of the complex numbers.
Task
Show in your language that Euler's identity is true. As much as possible and practical, mimic the Euler's identity equation.
Most languages are limited to IEEE 754 floating point calculations so will have some error in the calculation.
If that is the case, or there is some other limitation, show
that ei
π
{\displaystyle \pi }
+ 1 is approximately equal to zero and
show the amount of error in the calculation.
If your language is capable of symbolic calculations, show
that ei
π
{\displaystyle \pi }
+ 1 is exactly equal to zero for bonus kudos points.
| #Go | Go | package main
import (
"fmt"
"math"
"math/cmplx"
)
func main() {
fmt.Println(cmplx.Exp(math.Pi * 1i) + 1.0)
} |
http://rosettacode.org/wiki/Euler%27s_identity | Euler's identity |
This page uses content from Wikipedia. The original article was at Euler's_identity. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In mathematics, Euler's identity is the equality:
ei
π
{\displaystyle \pi }
+ 1 = 0
where
e is Euler's number, the base of natural logarithms,
i is the imaginary unit, which satisfies i2 = −1, and
π
{\displaystyle \pi }
is pi, the ratio of the circumference of a circle to its diameter.
Euler's identity is often cited as an example of deep mathematical beauty. Three of the basic arithmetic operations occur exactly once each: addition, multiplication, and exponentiation. The identity also links five fundamental mathematical constants:
The number 0.
The number 1.
The number
π
{\displaystyle \pi }
(
π
{\displaystyle \pi }
= 3.14159+),
The number e (e = 2.71828+), which occurs widely in mathematical analysis.
The number i, the imaginary unit of the complex numbers.
Task
Show in your language that Euler's identity is true. As much as possible and practical, mimic the Euler's identity equation.
Most languages are limited to IEEE 754 floating point calculations so will have some error in the calculation.
If that is the case, or there is some other limitation, show
that ei
π
{\displaystyle \pi }
+ 1 is approximately equal to zero and
show the amount of error in the calculation.
If your language is capable of symbolic calculations, show
that ei
π
{\displaystyle \pi }
+ 1 is exactly equal to zero for bonus kudos points.
| #Groovy | Groovy | import static Complex.*
Number.metaClass.mixin ComplexCategory
def π = Math.PI
def e = Math.E
println "e ** (π * i) + 1 = " + (e ** (π * i) + 1)
println "| e ** (π * i) + 1 | = " + (e ** (π * i) + 1).ρ |
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
| #Softbridge_BASIC | Softbridge BASIC |
Function Fibonacci(n)
x = 0
y = 1
i = 0
n = ABS(n)
If n < 2 Then
Fibonacci = n
Else
Do Until (i = n)
sum = x+y
x=y
y=sum
i=i+1
Loop
Fibonacci = x
End If
End Function
|
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
| #Kotlin | Kotlin | fun facti(n: Int) = when {
n < 0 -> throw IllegalArgumentException("negative numbers not allowed")
else -> {
var ans = 1L
for (i in 2..n) ans *= i
ans
}
}
fun factr(n: Int): Long = when {
n < 0 -> throw IllegalArgumentException("negative numbers not allowed")
n < 2 -> 1L
else -> n * factr(n - 1)
}
fun main(args: Array<String>) {
val n = 20
println("$n! = " + facti(n))
println("$n! = " + factr(n))
} |
http://rosettacode.org/wiki/Euler%27s_identity | Euler's identity |
This page uses content from Wikipedia. The original article was at Euler's_identity. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In mathematics, Euler's identity is the equality:
ei
π
{\displaystyle \pi }
+ 1 = 0
where
e is Euler's number, the base of natural logarithms,
i is the imaginary unit, which satisfies i2 = −1, and
π
{\displaystyle \pi }
is pi, the ratio of the circumference of a circle to its diameter.
Euler's identity is often cited as an example of deep mathematical beauty. Three of the basic arithmetic operations occur exactly once each: addition, multiplication, and exponentiation. The identity also links five fundamental mathematical constants:
The number 0.
The number 1.
The number
π
{\displaystyle \pi }
(
π
{\displaystyle \pi }
= 3.14159+),
The number e (e = 2.71828+), which occurs widely in mathematical analysis.
The number i, the imaginary unit of the complex numbers.
Task
Show in your language that Euler's identity is true. As much as possible and practical, mimic the Euler's identity equation.
Most languages are limited to IEEE 754 floating point calculations so will have some error in the calculation.
If that is the case, or there is some other limitation, show
that ei
π
{\displaystyle \pi }
+ 1 is approximately equal to zero and
show the amount of error in the calculation.
If your language is capable of symbolic calculations, show
that ei
π
{\displaystyle \pi }
+ 1 is exactly equal to zero for bonus kudos points.
| #Haskell | Haskell | import Data.Complex
eulerIdentityZeroIsh :: Complex Double
eulerIdentityZeroIsh =
exp (0 :+ pi) + 1
main :: IO ()
main = print eulerIdentityZeroIsh |
http://rosettacode.org/wiki/Euler%27s_identity | Euler's identity |
This page uses content from Wikipedia. The original article was at Euler's_identity. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In mathematics, Euler's identity is the equality:
ei
π
{\displaystyle \pi }
+ 1 = 0
where
e is Euler's number, the base of natural logarithms,
i is the imaginary unit, which satisfies i2 = −1, and
π
{\displaystyle \pi }
is pi, the ratio of the circumference of a circle to its diameter.
Euler's identity is often cited as an example of deep mathematical beauty. Three of the basic arithmetic operations occur exactly once each: addition, multiplication, and exponentiation. The identity also links five fundamental mathematical constants:
The number 0.
The number 1.
The number
π
{\displaystyle \pi }
(
π
{\displaystyle \pi }
= 3.14159+),
The number e (e = 2.71828+), which occurs widely in mathematical analysis.
The number i, the imaginary unit of the complex numbers.
Task
Show in your language that Euler's identity is true. As much as possible and practical, mimic the Euler's identity equation.
Most languages are limited to IEEE 754 floating point calculations so will have some error in the calculation.
If that is the case, or there is some other limitation, show
that ei
π
{\displaystyle \pi }
+ 1 is approximately equal to zero and
show the amount of error in the calculation.
If your language is capable of symbolic calculations, show
that ei
π
{\displaystyle \pi }
+ 1 is exactly equal to zero for bonus kudos points.
| #J | J |
NB. Euler's number is the default base for power
NB. using j's expressive numeric notation:
1 + ^ 0j1p1
0j1.22465e_16
NB. Customize the comparison tolerance to 10 ^ (-15)
NB. to show that
_1 (=!.1e_15) ^ 0j1p1
1
TAU =: 2p1
NB. tauday.com pi is wrong
NB. with TAU as 2 pi,
NB. Euler's identity should have read
1 (=!.1e_15) ^ j. TAU
1
|
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
| #Spin | Spin | con
_clkmode = xtal1 + pll16x
_clkfreq = 80_000_000
obj
ser : "FullDuplexSerial.spin"
pub main | i
ser.start(31, 30, 0, 115200)
repeat i from 0 to 10
ser.dec(fib(i))
ser.tx(32)
waitcnt(_clkfreq + cnt)
ser.stop
cogstop(0)
pub fib(i) : b | a
b := a := 1
repeat i
a := b + (b := a) |
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
| #Lambdatalk | Lambdatalk |
{def fac
{lambda {:n}
{if {< :n 1}
then 1
else {long_mult :n {fac {- :n 1}}}}}}
{fac 6}
-> 720
{fac 100}
-> 93326215443944152681699238856266700490715968264381621468592963895217599993229
915608941463976156518286253697920827223758251185210916864000000000000000000000000
|
http://rosettacode.org/wiki/Euler%27s_identity | Euler's identity |
This page uses content from Wikipedia. The original article was at Euler's_identity. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In mathematics, Euler's identity is the equality:
ei
π
{\displaystyle \pi }
+ 1 = 0
where
e is Euler's number, the base of natural logarithms,
i is the imaginary unit, which satisfies i2 = −1, and
π
{\displaystyle \pi }
is pi, the ratio of the circumference of a circle to its diameter.
Euler's identity is often cited as an example of deep mathematical beauty. Three of the basic arithmetic operations occur exactly once each: addition, multiplication, and exponentiation. The identity also links five fundamental mathematical constants:
The number 0.
The number 1.
The number
π
{\displaystyle \pi }
(
π
{\displaystyle \pi }
= 3.14159+),
The number e (e = 2.71828+), which occurs widely in mathematical analysis.
The number i, the imaginary unit of the complex numbers.
Task
Show in your language that Euler's identity is true. As much as possible and practical, mimic the Euler's identity equation.
Most languages are limited to IEEE 754 floating point calculations so will have some error in the calculation.
If that is the case, or there is some other limitation, show
that ei
π
{\displaystyle \pi }
+ 1 is approximately equal to zero and
show the amount of error in the calculation.
If your language is capable of symbolic calculations, show
that ei
π
{\displaystyle \pi }
+ 1 is exactly equal to zero for bonus kudos points.
| #Java | Java |
public class EulerIdentity {
public static void main(String[] args) {
System.out.println("e ^ (i*Pi) + 1 = " + (new Complex(0, Math.PI).exp()).add(new Complex(1, 0)));
}
public static class Complex {
private double x, y;
public Complex(double re, double im) {
x = re;
y = im;
}
public Complex exp() {
double exp = Math.exp(x);
return new Complex(exp * Math.cos(y), exp * Math.sin(y));
}
public Complex add(Complex a) {
return new Complex(x + a.x, y + a.y);
}
@Override
public String toString() {
return x + " + " + y + "i";
}
}
}
|
http://rosettacode.org/wiki/Euler%27s_identity | Euler's identity |
This page uses content from Wikipedia. The original article was at Euler's_identity. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In mathematics, Euler's identity is the equality:
ei
π
{\displaystyle \pi }
+ 1 = 0
where
e is Euler's number, the base of natural logarithms,
i is the imaginary unit, which satisfies i2 = −1, and
π
{\displaystyle \pi }
is pi, the ratio of the circumference of a circle to its diameter.
Euler's identity is often cited as an example of deep mathematical beauty. Three of the basic arithmetic operations occur exactly once each: addition, multiplication, and exponentiation. The identity also links five fundamental mathematical constants:
The number 0.
The number 1.
The number
π
{\displaystyle \pi }
(
π
{\displaystyle \pi }
= 3.14159+),
The number e (e = 2.71828+), which occurs widely in mathematical analysis.
The number i, the imaginary unit of the complex numbers.
Task
Show in your language that Euler's identity is true. As much as possible and practical, mimic the Euler's identity equation.
Most languages are limited to IEEE 754 floating point calculations so will have some error in the calculation.
If that is the case, or there is some other limitation, show
that ei
π
{\displaystyle \pi }
+ 1 is approximately equal to zero and
show the amount of error in the calculation.
If your language is capable of symbolic calculations, show
that ei
π
{\displaystyle \pi }
+ 1 is exactly equal to zero for bonus kudos points.
| #jq | jq | def multiply(x; y):
if (x|type) == "number" then
if (y|type) == "number" then [ x*y, 0 ]
else [x * y[0], x * y[1]]
end
elif (y|type) == "number" then multiply(y;x)
else [ x[0] * y[0] - x[1] * y[1], x[0] * y[1] + x[1] * y[0]]
end;
def plus(x; y):
if (x|type) == "number" then
if (y|type) == "number" then [ x+y, 0 ]
else [ x + y[0], y[1]]
end
elif (y|type) == "number" then plus(y;x)
else [ x[0] + y[0], x[1] + y[1] ]
end;
def exp(z):
def expi(x): [ (x|cos), (x|sin) ];
if (z|type) == "number" then z|exp
elif z[0] == 0 then expi(z[1]) # for efficiency
else multiply( (z[0]|exp); expi(z[1]) )
end ;
def pi: 4 * (1|atan);
|
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
| #SPL | SPL | fibo(n)=
s5 = #.sqrt(5)
<= (((1+s5)/2)^n-((1-s5)/2)^n)/s5
. |
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
| #Lang5 | Lang5 | : fact iota 1 + '* reduce ;
5 fact
120
|
http://rosettacode.org/wiki/Euler%27s_identity | Euler's identity |
This page uses content from Wikipedia. The original article was at Euler's_identity. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In mathematics, Euler's identity is the equality:
ei
π
{\displaystyle \pi }
+ 1 = 0
where
e is Euler's number, the base of natural logarithms,
i is the imaginary unit, which satisfies i2 = −1, and
π
{\displaystyle \pi }
is pi, the ratio of the circumference of a circle to its diameter.
Euler's identity is often cited as an example of deep mathematical beauty. Three of the basic arithmetic operations occur exactly once each: addition, multiplication, and exponentiation. The identity also links five fundamental mathematical constants:
The number 0.
The number 1.
The number
π
{\displaystyle \pi }
(
π
{\displaystyle \pi }
= 3.14159+),
The number e (e = 2.71828+), which occurs widely in mathematical analysis.
The number i, the imaginary unit of the complex numbers.
Task
Show in your language that Euler's identity is true. As much as possible and practical, mimic the Euler's identity equation.
Most languages are limited to IEEE 754 floating point calculations so will have some error in the calculation.
If that is the case, or there is some other limitation, show
that ei
π
{\displaystyle \pi }
+ 1 is approximately equal to zero and
show the amount of error in the calculation.
If your language is capable of symbolic calculations, show
that ei
π
{\displaystyle \pi }
+ 1 is exactly equal to zero for bonus kudos points.
| #Julia | Julia | @show ℯ^(π * im) + 1
@assert ℯ^(π * im) ≈ -1 |
http://rosettacode.org/wiki/Euler%27s_identity | Euler's identity |
This page uses content from Wikipedia. The original article was at Euler's_identity. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In mathematics, Euler's identity is the equality:
ei
π
{\displaystyle \pi }
+ 1 = 0
where
e is Euler's number, the base of natural logarithms,
i is the imaginary unit, which satisfies i2 = −1, and
π
{\displaystyle \pi }
is pi, the ratio of the circumference of a circle to its diameter.
Euler's identity is often cited as an example of deep mathematical beauty. Three of the basic arithmetic operations occur exactly once each: addition, multiplication, and exponentiation. The identity also links five fundamental mathematical constants:
The number 0.
The number 1.
The number
π
{\displaystyle \pi }
(
π
{\displaystyle \pi }
= 3.14159+),
The number e (e = 2.71828+), which occurs widely in mathematical analysis.
The number i, the imaginary unit of the complex numbers.
Task
Show in your language that Euler's identity is true. As much as possible and practical, mimic the Euler's identity equation.
Most languages are limited to IEEE 754 floating point calculations so will have some error in the calculation.
If that is the case, or there is some other limitation, show
that ei
π
{\displaystyle \pi }
+ 1 is approximately equal to zero and
show the amount of error in the calculation.
If your language is capable of symbolic calculations, show
that ei
π
{\displaystyle \pi }
+ 1 is exactly equal to zero for bonus kudos points.
| #Kotlin | Kotlin | // Version 1.2.40
import kotlin.math.sqrt
import kotlin.math.PI
const val EPSILON = 1.0e-16
const val SMALL_PI = '\u03c0'
const val APPROX_EQUALS = '\u2245'
class Complex(val real: Double, val imag: Double) {
operator fun plus(other: Complex) =
Complex(real + other.real, imag + other.imag)
operator fun times(other: Complex) = Complex(
real * other.real - imag * other.imag,
real * other.imag + imag * other.real
)
fun inv(): Complex {
val denom = real * real + imag * imag
return Complex(real / denom, -imag / denom)
}
operator fun unaryMinus() = Complex(-real, -imag)
operator fun minus(other: Complex) = this + (-other)
operator fun div(other: Complex) = this * other.inv()
val modulus: Double get() = sqrt(real * real + imag * imag)
override fun toString() =
if (imag >= 0.0) "$real + ${imag}i"
else "$real - ${-imag}i"
}
fun main(args: Array<String>) {
var fact = 1.0
val x = Complex(0.0, PI)
var e = Complex(1.0, PI)
var n = 2
var pow = x
do {
val e0 = e
fact *= n++
pow *= x
e += pow / Complex(fact, 0.0)
}
while ((e - e0).modulus >= EPSILON)
e += Complex(1.0, 0.0)
println("e^${SMALL_PI}i + 1 = $e $APPROX_EQUALS 0")
} |
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
| #SQL | SQL |
SELECT round ( EXP ( SUM (ln ( ( 1 + SQRT( 5 ) ) / 2)
) OVER ( ORDER BY level ) ) / SQRT( 5 ) ) fibo
FROM dual
CONNECT BY level <= 10;
|
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
| #langur | langur | val .factorial = f fold(f .x x .y, pseries .n)
writeln .factorial(7) |
http://rosettacode.org/wiki/Euler%27s_identity | Euler's identity |
This page uses content from Wikipedia. The original article was at Euler's_identity. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In mathematics, Euler's identity is the equality:
ei
π
{\displaystyle \pi }
+ 1 = 0
where
e is Euler's number, the base of natural logarithms,
i is the imaginary unit, which satisfies i2 = −1, and
π
{\displaystyle \pi }
is pi, the ratio of the circumference of a circle to its diameter.
Euler's identity is often cited as an example of deep mathematical beauty. Three of the basic arithmetic operations occur exactly once each: addition, multiplication, and exponentiation. The identity also links five fundamental mathematical constants:
The number 0.
The number 1.
The number
π
{\displaystyle \pi }
(
π
{\displaystyle \pi }
= 3.14159+),
The number e (e = 2.71828+), which occurs widely in mathematical analysis.
The number i, the imaginary unit of the complex numbers.
Task
Show in your language that Euler's identity is true. As much as possible and practical, mimic the Euler's identity equation.
Most languages are limited to IEEE 754 floating point calculations so will have some error in the calculation.
If that is the case, or there is some other limitation, show
that ei
π
{\displaystyle \pi }
+ 1 is approximately equal to zero and
show the amount of error in the calculation.
If your language is capable of symbolic calculations, show
that ei
π
{\displaystyle \pi }
+ 1 is exactly equal to zero for bonus kudos points.
| #Lambdatalk | Lambdatalk |
{require lib_complex}
'{C.exp {C.mul {C.new 0 1} {C.new {PI} 0}}} // e^πi = exp( [π,0] * [0,1] )
-> (-1 1.2246467991473532e-16) // = -1
|
http://rosettacode.org/wiki/Euler%27s_identity | Euler's identity |
This page uses content from Wikipedia. The original article was at Euler's_identity. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In mathematics, Euler's identity is the equality:
ei
π
{\displaystyle \pi }
+ 1 = 0
where
e is Euler's number, the base of natural logarithms,
i is the imaginary unit, which satisfies i2 = −1, and
π
{\displaystyle \pi }
is pi, the ratio of the circumference of a circle to its diameter.
Euler's identity is often cited as an example of deep mathematical beauty. Three of the basic arithmetic operations occur exactly once each: addition, multiplication, and exponentiation. The identity also links five fundamental mathematical constants:
The number 0.
The number 1.
The number
π
{\displaystyle \pi }
(
π
{\displaystyle \pi }
= 3.14159+),
The number e (e = 2.71828+), which occurs widely in mathematical analysis.
The number i, the imaginary unit of the complex numbers.
Task
Show in your language that Euler's identity is true. As much as possible and practical, mimic the Euler's identity equation.
Most languages are limited to IEEE 754 floating point calculations so will have some error in the calculation.
If that is the case, or there is some other limitation, show
that ei
π
{\displaystyle \pi }
+ 1 is approximately equal to zero and
show the amount of error in the calculation.
If your language is capable of symbolic calculations, show
that ei
π
{\displaystyle \pi }
+ 1 is exactly equal to zero for bonus kudos points.
| #Lua | Lua | local c = {
new = function(s,r,i) s.__index=s return setmetatable({r=r, i=i}, s) end,
add = function(s,o) return s:new(s.r+o.r, s.i+o.i) end,
exp = function(s) local e=math.exp(s.r) return s:new(e*math.cos(s.i), e*math.sin(s.i)) end,
mul = function(s,o) return s:new(s.r*o.r+s.i*o.i, s.r*o.i+s.i*o.r) end
}
local i = c:new(0, 1)
local pi = c:new(math.pi, 0)
local one = c:new(1, 0)
local zero = i:mul(pi):exp():add(one)
print(string.format("e^(i*pi)+1 is approximately zero: %.18g%+.18gi", zero.r, zero.i)) |
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
| #SSEM | SSEM | 10101000000000100000000000000000 0. -21 to c acc = -n
01101000000001100000000000000000 1. c to 22 temp = acc
00101000000001010000000000000000 2. Sub. 20 acc -= m
10101000000001100000000000000000 3. c to 21 n = acc
10101000000000100000000000000000 4. -21 to c acc = -n
10101000000001100000000000000000 5. c to 21 n = acc
01101000000000100000000000000000 6. -22 to c acc = -temp
00101000000001100000000000000000 7. c to 20 m = acc
11101000000000100000000000000000 8. -23 to c acc = -count
00011000000001010000000000000000 9. Sub. 24 acc -= -1
00000000000000110000000000000000 10. Test skip next if acc<0
10011000000000000000000000000000 11. 25 to CI goto (15 + 1)
11101000000001100000000000000000 12. c to 23 count = acc
11101000000000100000000000000000 13. -23 to c acc = -count
11101000000001100000000000000000 14. c to 23 count = acc
00011000000000000000000000000000 15. 24 to CI goto (-1 + 1)
10101000000000100000000000000000 16. -21 to c acc = -n
10101000000001100000000000000000 17. c to 21 n = acc
10101000000000100000000000000000 18. -21 to c acc = -n
00000000000001110000000000000000 19. Stop
00000000000000000000000000000000 20. 0 var m = 0
10000000000000000000000000000000 21. 1 var n = 1
00000000000000000000000000000000 22. 0 var temp = 0
10010000000000000000000000000000 23. 9 var count = 9
11111111111111111111111111111111 24. -1 const -1
11110000000000000000000000000000 25. 15 const 15 |
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
| #Lasso | Lasso | define factorial(n) => {
local(x = 1)
with i in generateSeries(2, #n)
do {
#x *= #i
}
return #x
} |
http://rosettacode.org/wiki/Euler%27s_identity | Euler's identity |
This page uses content from Wikipedia. The original article was at Euler's_identity. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In mathematics, Euler's identity is the equality:
ei
π
{\displaystyle \pi }
+ 1 = 0
where
e is Euler's number, the base of natural logarithms,
i is the imaginary unit, which satisfies i2 = −1, and
π
{\displaystyle \pi }
is pi, the ratio of the circumference of a circle to its diameter.
Euler's identity is often cited as an example of deep mathematical beauty. Three of the basic arithmetic operations occur exactly once each: addition, multiplication, and exponentiation. The identity also links five fundamental mathematical constants:
The number 0.
The number 1.
The number
π
{\displaystyle \pi }
(
π
{\displaystyle \pi }
= 3.14159+),
The number e (e = 2.71828+), which occurs widely in mathematical analysis.
The number i, the imaginary unit of the complex numbers.
Task
Show in your language that Euler's identity is true. As much as possible and practical, mimic the Euler's identity equation.
Most languages are limited to IEEE 754 floating point calculations so will have some error in the calculation.
If that is the case, or there is some other limitation, show
that ei
π
{\displaystyle \pi }
+ 1 is approximately equal to zero and
show the amount of error in the calculation.
If your language is capable of symbolic calculations, show
that ei
π
{\displaystyle \pi }
+ 1 is exactly equal to zero for bonus kudos points.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | E^(I Pi) + 1 |
http://rosettacode.org/wiki/Euler%27s_identity | Euler's identity |
This page uses content from Wikipedia. The original article was at Euler's_identity. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In mathematics, Euler's identity is the equality:
ei
π
{\displaystyle \pi }
+ 1 = 0
where
e is Euler's number, the base of natural logarithms,
i is the imaginary unit, which satisfies i2 = −1, and
π
{\displaystyle \pi }
is pi, the ratio of the circumference of a circle to its diameter.
Euler's identity is often cited as an example of deep mathematical beauty. Three of the basic arithmetic operations occur exactly once each: addition, multiplication, and exponentiation. The identity also links five fundamental mathematical constants:
The number 0.
The number 1.
The number
π
{\displaystyle \pi }
(
π
{\displaystyle \pi }
= 3.14159+),
The number e (e = 2.71828+), which occurs widely in mathematical analysis.
The number i, the imaginary unit of the complex numbers.
Task
Show in your language that Euler's identity is true. As much as possible and practical, mimic the Euler's identity equation.
Most languages are limited to IEEE 754 floating point calculations so will have some error in the calculation.
If that is the case, or there is some other limitation, show
that ei
π
{\displaystyle \pi }
+ 1 is approximately equal to zero and
show the amount of error in the calculation.
If your language is capable of symbolic calculations, show
that ei
π
{\displaystyle \pi }
+ 1 is exactly equal to zero for bonus kudos points.
| #Nim | Nim | import math, complex
echo "exp(iπ) + 1 = ", exp(complex(0.0, PI)) + 1, " ~= 0" |
http://rosettacode.org/wiki/Euler%27s_identity | Euler's identity |
This page uses content from Wikipedia. The original article was at Euler's_identity. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In mathematics, Euler's identity is the equality:
ei
π
{\displaystyle \pi }
+ 1 = 0
where
e is Euler's number, the base of natural logarithms,
i is the imaginary unit, which satisfies i2 = −1, and
π
{\displaystyle \pi }
is pi, the ratio of the circumference of a circle to its diameter.
Euler's identity is often cited as an example of deep mathematical beauty. Three of the basic arithmetic operations occur exactly once each: addition, multiplication, and exponentiation. The identity also links five fundamental mathematical constants:
The number 0.
The number 1.
The number
π
{\displaystyle \pi }
(
π
{\displaystyle \pi }
= 3.14159+),
The number e (e = 2.71828+), which occurs widely in mathematical analysis.
The number i, the imaginary unit of the complex numbers.
Task
Show in your language that Euler's identity is true. As much as possible and practical, mimic the Euler's identity equation.
Most languages are limited to IEEE 754 floating point calculations so will have some error in the calculation.
If that is the case, or there is some other limitation, show
that ei
π
{\displaystyle \pi }
+ 1 is approximately equal to zero and
show the amount of error in the calculation.
If your language is capable of symbolic calculations, show
that ei
π
{\displaystyle \pi }
+ 1 is exactly equal to zero for bonus kudos points.
| #OCaml | OCaml | # open Complex;;
# let pi = acos (-1.0);;
val pi : float = 3.14159265358979312
# add (exp { re = 0.0; im = pi }) { re = 1.0; im = 0.0 };;
- : Complex.t = {re = 0.; im = 1.22464679914735321e-16} |
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
| #Stata | Stata | program fib
args n
clear
qui set obs `n'
qui gen a=1
qui replace a=a[_n-1]+a[_n-2] in 3/l
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
| #Latitude | Latitude | factorial := {
1 upto ($1 + 1) product.
}. |
http://rosettacode.org/wiki/Euler%27s_identity | Euler's identity |
This page uses content from Wikipedia. The original article was at Euler's_identity. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In mathematics, Euler's identity is the equality:
ei
π
{\displaystyle \pi }
+ 1 = 0
where
e is Euler's number, the base of natural logarithms,
i is the imaginary unit, which satisfies i2 = −1, and
π
{\displaystyle \pi }
is pi, the ratio of the circumference of a circle to its diameter.
Euler's identity is often cited as an example of deep mathematical beauty. Three of the basic arithmetic operations occur exactly once each: addition, multiplication, and exponentiation. The identity also links five fundamental mathematical constants:
The number 0.
The number 1.
The number
π
{\displaystyle \pi }
(
π
{\displaystyle \pi }
= 3.14159+),
The number e (e = 2.71828+), which occurs widely in mathematical analysis.
The number i, the imaginary unit of the complex numbers.
Task
Show in your language that Euler's identity is true. As much as possible and practical, mimic the Euler's identity equation.
Most languages are limited to IEEE 754 floating point calculations so will have some error in the calculation.
If that is the case, or there is some other limitation, show
that ei
π
{\displaystyle \pi }
+ 1 is approximately equal to zero and
show the amount of error in the calculation.
If your language is capable of symbolic calculations, show
that ei
π
{\displaystyle \pi }
+ 1 is exactly equal to zero for bonus kudos points.
| #Perl | Perl | use Math::Complex;
print exp(pi * i) + 1, "\n"; |
http://rosettacode.org/wiki/Euler%27s_identity | Euler's identity |
This page uses content from Wikipedia. The original article was at Euler's_identity. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In mathematics, Euler's identity is the equality:
ei
π
{\displaystyle \pi }
+ 1 = 0
where
e is Euler's number, the base of natural logarithms,
i is the imaginary unit, which satisfies i2 = −1, and
π
{\displaystyle \pi }
is pi, the ratio of the circumference of a circle to its diameter.
Euler's identity is often cited as an example of deep mathematical beauty. Three of the basic arithmetic operations occur exactly once each: addition, multiplication, and exponentiation. The identity also links five fundamental mathematical constants:
The number 0.
The number 1.
The number
π
{\displaystyle \pi }
(
π
{\displaystyle \pi }
= 3.14159+),
The number e (e = 2.71828+), which occurs widely in mathematical analysis.
The number i, the imaginary unit of the complex numbers.
Task
Show in your language that Euler's identity is true. As much as possible and practical, mimic the Euler's identity equation.
Most languages are limited to IEEE 754 floating point calculations so will have some error in the calculation.
If that is the case, or there is some other limitation, show
that ei
π
{\displaystyle \pi }
+ 1 is approximately equal to zero and
show the amount of error in the calculation.
If your language is capable of symbolic calculations, show
that ei
π
{\displaystyle \pi }
+ 1 is exactly equal to zero for bonus kudos points.
| #Phix | Phix | with javascript_semantics
include builtins\complex.e
complex i = complex_new(0,1),
res = complex_add(complex_exp(complex_mul(PI,i)),1)
?complex_sprint(res,both:=true)
?complex_sprint(complex_round(res,1e16),true)
?complex_sprint(complex_round(res,1e15),true)
|
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
| #StreamIt | StreamIt | void->int feedbackloop Fib {
join roundrobin(0,1);
body in->int filter {
work pop 1 push 1 peek 2 { push(peek(0) + peek(1)); pop(); }
};
loop Identity<int>;
split duplicate;
enqueue(0);
enqueue(1);
} |
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
| #LFE | LFE |
(defun factorial (n)
(cond
((== n 0) 1)
((> n 0) (* n (factorial (- n 1))))))
|
http://rosettacode.org/wiki/Euler%27s_identity | Euler's identity |
This page uses content from Wikipedia. The original article was at Euler's_identity. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In mathematics, Euler's identity is the equality:
ei
π
{\displaystyle \pi }
+ 1 = 0
where
e is Euler's number, the base of natural logarithms,
i is the imaginary unit, which satisfies i2 = −1, and
π
{\displaystyle \pi }
is pi, the ratio of the circumference of a circle to its diameter.
Euler's identity is often cited as an example of deep mathematical beauty. Three of the basic arithmetic operations occur exactly once each: addition, multiplication, and exponentiation. The identity also links five fundamental mathematical constants:
The number 0.
The number 1.
The number
π
{\displaystyle \pi }
(
π
{\displaystyle \pi }
= 3.14159+),
The number e (e = 2.71828+), which occurs widely in mathematical analysis.
The number i, the imaginary unit of the complex numbers.
Task
Show in your language that Euler's identity is true. As much as possible and practical, mimic the Euler's identity equation.
Most languages are limited to IEEE 754 floating point calculations so will have some error in the calculation.
If that is the case, or there is some other limitation, show
that ei
π
{\displaystyle \pi }
+ 1 is approximately equal to zero and
show the amount of error in the calculation.
If your language is capable of symbolic calculations, show
that ei
π
{\displaystyle \pi }
+ 1 is exactly equal to zero for bonus kudos points.
| #Prolog | Prolog |
% reduce() prints the intermediate results so that one can see Prolog "thinking."
%
reduce(A, C) :-
simplify(A, B),
(B = A -> C = A; io:format("= ~w~n", [B]), reduce(B, C)).
simplify(exp(i*X), cos(X) + i*sin(X)) :- !.
simplify(0 + A, A) :- !.
simplify(A + 0, A) :- !.
simplify(A + B, C) :-
integer(A),
integer(B), !,
C is A + B.
simplify(A + B, C + D) :- !,
simplify(A, C),
simplify(B, D).
simplify(0 * _, 0) :- !.
simplify(_ * 0, 0) :- !.
simplify(1 * A, A) :- !.
simplify(A * 1, A) :- !.
simplify(A * B, C) :-
integer(A),
integer(B), !,
C is A * B.
simplify(A * B, C * D) :- !,
simplify(A, C),
simplify(B, D).
simplify(cos(0), 1) :- !.
simplify(sin(0), 0) :- !.
simplify(cos(pi), -1) :- !.
simplify(sin(pi), 0) :- !.
simplify(X, X).
|
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
| #SuperCollider | SuperCollider |
f = { |n| if(n < 2) { n } { f.(n-1) + f.(n-2) } };
(0..20).collect(f)
|
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
| #Liberty_BASIC | Liberty BASIC | for i =0 to 40
print " FactorialI( "; using( "####", i); ") = "; factorialI( i)
print " FactorialR( "; using( "####", i); ") = "; factorialR( i)
next i
wait
function factorialI( n)
if n >1 then
f =1
For i = 2 To n
f = f * i
Next i
else
f =1
end if
factorialI =f
end function
function factorialR( n)
if n <2 then
f =1
else
f =n *factorialR( n -1)
end if
factorialR =f
end function
end |
http://rosettacode.org/wiki/Euler%27s_identity | Euler's identity |
This page uses content from Wikipedia. The original article was at Euler's_identity. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In mathematics, Euler's identity is the equality:
ei
π
{\displaystyle \pi }
+ 1 = 0
where
e is Euler's number, the base of natural logarithms,
i is the imaginary unit, which satisfies i2 = −1, and
π
{\displaystyle \pi }
is pi, the ratio of the circumference of a circle to its diameter.
Euler's identity is often cited as an example of deep mathematical beauty. Three of the basic arithmetic operations occur exactly once each: addition, multiplication, and exponentiation. The identity also links five fundamental mathematical constants:
The number 0.
The number 1.
The number
π
{\displaystyle \pi }
(
π
{\displaystyle \pi }
= 3.14159+),
The number e (e = 2.71828+), which occurs widely in mathematical analysis.
The number i, the imaginary unit of the complex numbers.
Task
Show in your language that Euler's identity is true. As much as possible and practical, mimic the Euler's identity equation.
Most languages are limited to IEEE 754 floating point calculations so will have some error in the calculation.
If that is the case, or there is some other limitation, show
that ei
π
{\displaystyle \pi }
+ 1 is approximately equal to zero and
show the amount of error in the calculation.
If your language is capable of symbolic calculations, show
that ei
π
{\displaystyle \pi }
+ 1 is exactly equal to zero for bonus kudos points.
| #Python | Python | >>> import math
>>> math.e ** (math.pi * 1j) + 1
1.2246467991473532e-16j |
http://rosettacode.org/wiki/Euler%27s_identity | Euler's identity |
This page uses content from Wikipedia. The original article was at Euler's_identity. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In mathematics, Euler's identity is the equality:
ei
π
{\displaystyle \pi }
+ 1 = 0
where
e is Euler's number, the base of natural logarithms,
i is the imaginary unit, which satisfies i2 = −1, and
π
{\displaystyle \pi }
is pi, the ratio of the circumference of a circle to its diameter.
Euler's identity is often cited as an example of deep mathematical beauty. Three of the basic arithmetic operations occur exactly once each: addition, multiplication, and exponentiation. The identity also links five fundamental mathematical constants:
The number 0.
The number 1.
The number
π
{\displaystyle \pi }
(
π
{\displaystyle \pi }
= 3.14159+),
The number e (e = 2.71828+), which occurs widely in mathematical analysis.
The number i, the imaginary unit of the complex numbers.
Task
Show in your language that Euler's identity is true. As much as possible and practical, mimic the Euler's identity equation.
Most languages are limited to IEEE 754 floating point calculations so will have some error in the calculation.
If that is the case, or there is some other limitation, show
that ei
π
{\displaystyle \pi }
+ 1 is approximately equal to zero and
show the amount of error in the calculation.
If your language is capable of symbolic calculations, show
that ei
π
{\displaystyle \pi }
+ 1 is exactly equal to zero for bonus kudos points.
| #R | R | # lang R
exp(1i * pi) + 1 |
http://rosettacode.org/wiki/Euler%27s_identity | Euler's identity |
This page uses content from Wikipedia. The original article was at Euler's_identity. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In mathematics, Euler's identity is the equality:
ei
π
{\displaystyle \pi }
+ 1 = 0
where
e is Euler's number, the base of natural logarithms,
i is the imaginary unit, which satisfies i2 = −1, and
π
{\displaystyle \pi }
is pi, the ratio of the circumference of a circle to its diameter.
Euler's identity is often cited as an example of deep mathematical beauty. Three of the basic arithmetic operations occur exactly once each: addition, multiplication, and exponentiation. The identity also links five fundamental mathematical constants:
The number 0.
The number 1.
The number
π
{\displaystyle \pi }
(
π
{\displaystyle \pi }
= 3.14159+),
The number e (e = 2.71828+), which occurs widely in mathematical analysis.
The number i, the imaginary unit of the complex numbers.
Task
Show in your language that Euler's identity is true. As much as possible and practical, mimic the Euler's identity equation.
Most languages are limited to IEEE 754 floating point calculations so will have some error in the calculation.
If that is the case, or there is some other limitation, show
that ei
π
{\displaystyle \pi }
+ 1 is approximately equal to zero and
show the amount of error in the calculation.
If your language is capable of symbolic calculations, show
that ei
π
{\displaystyle \pi }
+ 1 is exactly equal to zero for bonus kudos points.
| #Racket | Racket | #lang racket
(+ (exp (* 0+i pi)) 1) |
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
| #Swift | Swift | import Cocoa
func fibonacci(n: Int) -> Int {
let square_root_of_5 = sqrt(5.0)
let p = (1 + square_root_of_5) / 2
let q = 1 / p
return Int((pow(p,CDouble(n)) + pow(q,CDouble(n))) / square_root_of_5 + 0.5)
}
for i in 1...30 {
println(fibonacci(i))
} |
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
| #Lingo | Lingo | on fact (n)
if n<=1 then return 1
return n * fact(n-1)
end |
http://rosettacode.org/wiki/Euler%27s_identity | Euler's identity |
This page uses content from Wikipedia. The original article was at Euler's_identity. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In mathematics, Euler's identity is the equality:
ei
π
{\displaystyle \pi }
+ 1 = 0
where
e is Euler's number, the base of natural logarithms,
i is the imaginary unit, which satisfies i2 = −1, and
π
{\displaystyle \pi }
is pi, the ratio of the circumference of a circle to its diameter.
Euler's identity is often cited as an example of deep mathematical beauty. Three of the basic arithmetic operations occur exactly once each: addition, multiplication, and exponentiation. The identity also links five fundamental mathematical constants:
The number 0.
The number 1.
The number
π
{\displaystyle \pi }
(
π
{\displaystyle \pi }
= 3.14159+),
The number e (e = 2.71828+), which occurs widely in mathematical analysis.
The number i, the imaginary unit of the complex numbers.
Task
Show in your language that Euler's identity is true. As much as possible and practical, mimic the Euler's identity equation.
Most languages are limited to IEEE 754 floating point calculations so will have some error in the calculation.
If that is the case, or there is some other limitation, show
that ei
π
{\displaystyle \pi }
+ 1 is approximately equal to zero and
show the amount of error in the calculation.
If your language is capable of symbolic calculations, show
that ei
π
{\displaystyle \pi }
+ 1 is exactly equal to zero for bonus kudos points.
| #Raku | Raku | sub infix:<> is tighter(&infix:<**>) { $^a * $^b };
say 'e**iπ + 1 ≅ 0 : ', e**iπ + 1 ≅ 0;
say 'Error: ', e**iπ + 1; |
http://rosettacode.org/wiki/Euler%27s_identity | Euler's identity |
This page uses content from Wikipedia. The original article was at Euler's_identity. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In mathematics, Euler's identity is the equality:
ei
π
{\displaystyle \pi }
+ 1 = 0
where
e is Euler's number, the base of natural logarithms,
i is the imaginary unit, which satisfies i2 = −1, and
π
{\displaystyle \pi }
is pi, the ratio of the circumference of a circle to its diameter.
Euler's identity is often cited as an example of deep mathematical beauty. Three of the basic arithmetic operations occur exactly once each: addition, multiplication, and exponentiation. The identity also links five fundamental mathematical constants:
The number 0.
The number 1.
The number
π
{\displaystyle \pi }
(
π
{\displaystyle \pi }
= 3.14159+),
The number e (e = 2.71828+), which occurs widely in mathematical analysis.
The number i, the imaginary unit of the complex numbers.
Task
Show in your language that Euler's identity is true. As much as possible and practical, mimic the Euler's identity equation.
Most languages are limited to IEEE 754 floating point calculations so will have some error in the calculation.
If that is the case, or there is some other limitation, show
that ei
π
{\displaystyle \pi }
+ 1 is approximately equal to zero and
show the amount of error in the calculation.
If your language is capable of symbolic calculations, show
that ei
π
{\displaystyle \pi }
+ 1 is exactly equal to zero for bonus kudos points.
| #REXX | REXX | /*REXX program proves Euler's identity by showing that: e^(i pi) + 1 ≡ 0 */
numeric digits length( pi() ) - length(.) /*define pi; set # dec. digs precision*/
cosPI= fmt( cos(pi) ) /*calculate the value of cos(pi). */
sinPI= fmt( sin(pi) ) /* " " " " sin(pi). */
say ' cos(pi) = ' cosPI /*display " " " cos(Pi). */
say ' sin(pi) = ' sinPI /* " " " " sin(Pi). */
say /*separate the wheat from the chaff. */
$= cosPI + mult( sqrt(-1), sinPI ) + 1 /*calc. product of sin(x) and sqrt(-1).*/
say ' e^(i pi) + 1 = ' fmt($) ' ' word("unproven proven", ($=0) + 1)
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
fmt: procedure; parse arg x; x= format(x, , digits() %2, 0); return left('', x>=0)x /1
mult: procedure; parse arg a,b; if a=0 | b=0 then return 0; return a*b
pi: pi= 3.1415926535897932384626433832795028841971693993751058209749445923; return pi
cos: procedure; parse arg x; z= 1; _= 1; q= x*x; i= -1; return .sinCos()
sin: procedure; parse arg x 1 z 1 _; q= x*x; i= 1; return .sinCos()
.sinCos: do k=2 by 2 until p=z; p=z; _= -_ * q/(k*(k+i)); z= z+_; end; return z
/*──────────────────────────────────────────────────────────────────────────────────────*/
sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); i=; h= d+6
numeric digits; numeric form; if x<0 then do; x= -x; i= 'i'; end; m.= 9
parse value format(x, 2, 1, , 0) 'E0' with g 'E' _ .; g= g * .5'e'_ % 2
do j=0 while h>9; m.j= h; h= h % 2 + 1; end
do k=j+5 to 0 by -1; numeric digits m.k; g= (g+x/g) *.5; end; return g || i |
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.
| #11l | 11l | F euler(f, y0, a, b, h)
V t = a
V y = y0
L t <= b
print(‘#2.3 #2.3’.format(t, y))
t += h
y += h * f(t, y)
V newtoncooling = (time, temp) -> -0.07 * (temp - 20)
euler(newtoncooling, 100.0, 0.0, 100.0, 10.0) |
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
| #Tailspin | Tailspin |
templates nthFibonacci
when <=0|=1> do $ !
otherwise ($ - 1 -> #) + ($ - 2 -> #) !
end nthFibonacci
|
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
| #Lisaac | Lisaac | - factorial x : INTEGER : INTEGER <- (
+ result : INTEGER;
(x <= 1).if {
result := 1;
} else {
result := x * factorial(x - 1);
};
result
); |
http://rosettacode.org/wiki/Euler%27s_identity | Euler's identity |
This page uses content from Wikipedia. The original article was at Euler's_identity. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In mathematics, Euler's identity is the equality:
ei
π
{\displaystyle \pi }
+ 1 = 0
where
e is Euler's number, the base of natural logarithms,
i is the imaginary unit, which satisfies i2 = −1, and
π
{\displaystyle \pi }
is pi, the ratio of the circumference of a circle to its diameter.
Euler's identity is often cited as an example of deep mathematical beauty. Three of the basic arithmetic operations occur exactly once each: addition, multiplication, and exponentiation. The identity also links five fundamental mathematical constants:
The number 0.
The number 1.
The number
π
{\displaystyle \pi }
(
π
{\displaystyle \pi }
= 3.14159+),
The number e (e = 2.71828+), which occurs widely in mathematical analysis.
The number i, the imaginary unit of the complex numbers.
Task
Show in your language that Euler's identity is true. As much as possible and practical, mimic the Euler's identity equation.
Most languages are limited to IEEE 754 floating point calculations so will have some error in the calculation.
If that is the case, or there is some other limitation, show
that ei
π
{\displaystyle \pi }
+ 1 is approximately equal to zero and
show the amount of error in the calculation.
If your language is capable of symbolic calculations, show
that ei
π
{\displaystyle \pi }
+ 1 is exactly equal to zero for bonus kudos points.
| #Ruby | Ruby |
include Math
E ** (PI * 1i) + 1
# => (0.0+0.0i) |
http://rosettacode.org/wiki/Euler%27s_identity | Euler's identity |
This page uses content from Wikipedia. The original article was at Euler's_identity. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In mathematics, Euler's identity is the equality:
ei
π
{\displaystyle \pi }
+ 1 = 0
where
e is Euler's number, the base of natural logarithms,
i is the imaginary unit, which satisfies i2 = −1, and
π
{\displaystyle \pi }
is pi, the ratio of the circumference of a circle to its diameter.
Euler's identity is often cited as an example of deep mathematical beauty. Three of the basic arithmetic operations occur exactly once each: addition, multiplication, and exponentiation. The identity also links five fundamental mathematical constants:
The number 0.
The number 1.
The number
π
{\displaystyle \pi }
(
π
{\displaystyle \pi }
= 3.14159+),
The number e (e = 2.71828+), which occurs widely in mathematical analysis.
The number i, the imaginary unit of the complex numbers.
Task
Show in your language that Euler's identity is true. As much as possible and practical, mimic the Euler's identity equation.
Most languages are limited to IEEE 754 floating point calculations so will have some error in the calculation.
If that is the case, or there is some other limitation, show
that ei
π
{\displaystyle \pi }
+ 1 is approximately equal to zero and
show the amount of error in the calculation.
If your language is capable of symbolic calculations, show
that ei
π
{\displaystyle \pi }
+ 1 is exactly equal to zero for bonus kudos points.
| #Rust | Rust | use std::f64::consts::PI;
extern crate num_complex;
use num_complex::Complex;
fn main() {
println!("{:e}", Complex::new(0.0, PI).exp() + 1.0);
} |
http://rosettacode.org/wiki/Euler%27s_identity | Euler's identity |
This page uses content from Wikipedia. The original article was at Euler's_identity. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In mathematics, Euler's identity is the equality:
ei
π
{\displaystyle \pi }
+ 1 = 0
where
e is Euler's number, the base of natural logarithms,
i is the imaginary unit, which satisfies i2 = −1, and
π
{\displaystyle \pi }
is pi, the ratio of the circumference of a circle to its diameter.
Euler's identity is often cited as an example of deep mathematical beauty. Three of the basic arithmetic operations occur exactly once each: addition, multiplication, and exponentiation. The identity also links five fundamental mathematical constants:
The number 0.
The number 1.
The number
π
{\displaystyle \pi }
(
π
{\displaystyle \pi }
= 3.14159+),
The number e (e = 2.71828+), which occurs widely in mathematical analysis.
The number i, the imaginary unit of the complex numbers.
Task
Show in your language that Euler's identity is true. As much as possible and practical, mimic the Euler's identity equation.
Most languages are limited to IEEE 754 floating point calculations so will have some error in the calculation.
If that is the case, or there is some other limitation, show
that ei
π
{\displaystyle \pi }
+ 1 is approximately equal to zero and
show the amount of error in the calculation.
If your language is capable of symbolic calculations, show
that ei
π
{\displaystyle \pi }
+ 1 is exactly equal to zero for bonus kudos points.
| #Scala | Scala | import spire.math.{Complex, Real}
object Scratch extends App{
//Declare values with friendly names to clean up the final expression
val e = Complex[Real](Real.e, 0)
val pi = Complex[Real](Real.pi, 0)
val i = Complex[Real](0, 1)
val one = Complex.one[Real]
println(e.pow(pi*i) + one)
} |
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.
| #Ada | Ada |
generic
type Number is digits <>;
package Euler is
type Waveform is array (Integer range <>) of Number;
function Solve
( F : not null access function (T, Y : Number) return Number;
Y0 : Number;
T0, T1 : Number;
N : Positive
) return Waveform;
end Euler;
|
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
| #Tcl | Tcl | proc fibiter n {
if {$n < 2} {return $n}
set prev 1
set fib 1
for {set i 2} {$i < $n} {incr i} {
lassign [list $fib [incr fib $prev]] prev fib
}
return $fib
} |
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.
| #C.2B.2B | C++ | #include <algorithm>
#include <cassert>
#include <iomanip>
#include <iostream>
#include <map>
#include <vector>
#include <primesieve.hpp>
class erdos_selfridge {
public:
explicit erdos_selfridge(int limit);
uint64_t get_prime(int index) const { return primes_[index].first; }
int get_category(int index);
private:
std::vector<std::pair<uint64_t, int>> primes_;
size_t get_index(uint64_t prime) const;
};
erdos_selfridge::erdos_selfridge(int limit) {
primesieve::iterator iter;
for (int i = 0; i < limit; ++i)
primes_.emplace_back(iter.next_prime(), 0);
}
int erdos_selfridge::get_category(int index) {
auto& pair = primes_[index];
if (pair.second != 0)
return pair.second;
int max_category = 0;
uint64_t n = pair.first + 1;
for (int i = 0; n > 1; ++i) {
uint64_t p = primes_[i].first;
if (p * p > n)
break;
int count = 0;
for (; n % p == 0; ++count)
n /= p;
if (count != 0) {
int category = (p <= 3) ? 1 : 1 + get_category(i);
max_category = std::max(max_category, category);
}
}
if (n > 1) {
int category = (n <= 3) ? 1 : 1 + get_category(get_index(n));
max_category = std::max(max_category, category);
}
pair.second = max_category;
return max_category;
}
size_t erdos_selfridge::get_index(uint64_t prime) const {
auto it = std::lower_bound(primes_.begin(), primes_.end(), prime,
[](const std::pair<uint64_t, int>& p,
uint64_t n) { return p.first < n; });
assert(it != primes_.end());
assert(it->first == prime);
return std::distance(primes_.begin(), it);
}
auto get_primes_by_category(erdos_selfridge& es, int limit) {
std::map<int, std::vector<uint64_t>> primes_by_category;
for (int i = 0; i < limit; ++i) {
uint64_t prime = es.get_prime(i);
int category = es.get_category(i);
primes_by_category[category].push_back(prime);
}
return primes_by_category;
}
int main() {
const int limit1 = 200, limit2 = 1000000;
erdos_selfridge es(limit2);
std::cout << "First 200 primes:\n";
for (const auto& p : get_primes_by_category(es, limit1)) {
std::cout << "Category " << p.first << ":\n";
for (size_t i = 0, n = p.second.size(); i != n; ++i) {
std::cout << std::setw(4) << p.second[i]
<< ((i + 1) % 15 == 0 ? '\n' : ' ');
}
std::cout << "\n\n";
}
std::cout << "First 1,000,000 primes:\n";
for (const auto& p : get_primes_by_category(es, limit2)) {
const auto& v = p.second;
std::cout << "Category " << std::setw(2) << p.first << ": "
<< "first = " << std::setw(7) << v.front()
<< " last = " << std::setw(8) << v.back()
<< " count = " << v.size() << '\n';
}
} |
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
| #Little_Man_Computer | Little Man Computer |
// Little Man Computer
// Reads an integer n and prints n factorial
// Works for n = 0..6
LDA one // initialize factorial to 1
STA fac
INP // get n from user
BRZ done // if n = 0, return 1
STA n // else store n
LDA one // initialize k = 1
outer STA k // outer loop: store latest k
LDA n // test for k = n
SUB k
BRZ done // done if so
LDA fac // save previous factorial
STA prev
LDA k // initialize i = k
inner STA i // inner loop: store latest i
LDA fac // build factorial by repeated addition
ADD prev
STA fac
LDA i // decrement i
SUB one
BRZ next_k // if i = 0, move on to next k
BRA inner // else loop for another addition
next_k LDA k // increment k
ADD one
BRA outer // back to start of outer loop
done LDA fac // done, load the result
OUT // print it
HLT // halt
n DAT 0 // input value
k DAT 0 // outer loop counter, 1 up to n
i DAT 0 // inner loop counter, k down to 0
fac DAT 0 // holds k!, i.e. n! when done
prev DAT 0 // previous value of fac
one DAT 1 // constant 1
// end
|
http://rosettacode.org/wiki/Euler%27s_identity | Euler's identity |
This page uses content from Wikipedia. The original article was at Euler's_identity. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In mathematics, Euler's identity is the equality:
ei
π
{\displaystyle \pi }
+ 1 = 0
where
e is Euler's number, the base of natural logarithms,
i is the imaginary unit, which satisfies i2 = −1, and
π
{\displaystyle \pi }
is pi, the ratio of the circumference of a circle to its diameter.
Euler's identity is often cited as an example of deep mathematical beauty. Three of the basic arithmetic operations occur exactly once each: addition, multiplication, and exponentiation. The identity also links five fundamental mathematical constants:
The number 0.
The number 1.
The number
π
{\displaystyle \pi }
(
π
{\displaystyle \pi }
= 3.14159+),
The number e (e = 2.71828+), which occurs widely in mathematical analysis.
The number i, the imaginary unit of the complex numbers.
Task
Show in your language that Euler's identity is true. As much as possible and practical, mimic the Euler's identity equation.
Most languages are limited to IEEE 754 floating point calculations so will have some error in the calculation.
If that is the case, or there is some other limitation, show
that ei
π
{\displaystyle \pi }
+ 1 is approximately equal to zero and
show the amount of error in the calculation.
If your language is capable of symbolic calculations, show
that ei
π
{\displaystyle \pi }
+ 1 is exactly equal to zero for bonus kudos points.
| #Scheme | Scheme | ; A way to get pi.
(define pi (acos -1))
; Print the value of e^(i*pi) + 1 -- should be 0.
(printf "e^(i*pi) + 1 = ~a~%" (+ (exp (* +i pi)) 1)) |
http://rosettacode.org/wiki/Euler%27s_identity | Euler's identity |
This page uses content from Wikipedia. The original article was at Euler's_identity. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In mathematics, Euler's identity is the equality:
ei
π
{\displaystyle \pi }
+ 1 = 0
where
e is Euler's number, the base of natural logarithms,
i is the imaginary unit, which satisfies i2 = −1, and
π
{\displaystyle \pi }
is pi, the ratio of the circumference of a circle to its diameter.
Euler's identity is often cited as an example of deep mathematical beauty. Three of the basic arithmetic operations occur exactly once each: addition, multiplication, and exponentiation. The identity also links five fundamental mathematical constants:
The number 0.
The number 1.
The number
π
{\displaystyle \pi }
(
π
{\displaystyle \pi }
= 3.14159+),
The number e (e = 2.71828+), which occurs widely in mathematical analysis.
The number i, the imaginary unit of the complex numbers.
Task
Show in your language that Euler's identity is true. As much as possible and practical, mimic the Euler's identity equation.
Most languages are limited to IEEE 754 floating point calculations so will have some error in the calculation.
If that is the case, or there is some other limitation, show
that ei
π
{\displaystyle \pi }
+ 1 is approximately equal to zero and
show the amount of error in the calculation.
If your language is capable of symbolic calculations, show
that ei
π
{\displaystyle \pi }
+ 1 is exactly equal to zero for bonus kudos points.
| #Sidef | Sidef | say ('e**iπ + 1 ≅ 0 : ', Num.e**Num.pi.i + 1 ≅ 0)
say ('Error: ', Num.e**Num.pi.i + 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.
| #ALGOL_68 | ALGOL 68 | #
Approximates y(t) in y'(t)=f(t,y) with y(a)=y0 and
t=a..b and the step size h.
#
PROC euler = (PROC(REAL,REAL)REAL f, REAL y0, a, b, h)REAL: (
REAL y := y0,
t := a;
WHILE t < b DO
printf(($g(-6,3)": "g(-7,3)l$, t, y));
y +:= h * f(t, y);
t +:= h
OD;
printf($"done"l$);
y
);
# Example: Newton's cooling law #
PROC newton cooling law = (REAL time, t)REAL: (
-0.07 * (t - 20)
);
main: (
euler(newton cooling law, 100, 0, 100, 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
| #Tern | Tern | func fib(n) {
if (n < 2) {
return 1;
}
return fib(n - 1) + fib(n - 2);
} |
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.
| #F.23 | F# |
// Erdös-Selfridge categorization of primes. Nigel Galloway: April 12th., 2022
let rec fG n g=match n,g with ((_,1),_)|(_,[])->n |((_,p),h::_) when h>p->n |((p,q),h::_) when q%h=0->fG (p,q/h) g |(_,_::g)->fG n g
let fN g=Seq.unfold(fun(n,g)->let n,g=n|>List.map(fun n->fG n g)|>List.partition(fun(_,n)->n<>1) in let g=g|>List.map fst in if g=[] then None else Some(g,(n,g)))(primes32()|>Seq.take g|>Seq.map(fun n->(n,n+1))|>List.ofSeq,[2;3])
fN 200|>Seq.iteri(fun n g->printfn "Category %d: %A" (n+1) g)
fN 1000000|>Seq.iteri(fun n g->printfn "Category %d: first->%d last->%d count->%d" (n+1) (List.head g) (List.last g) (
|
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
| #LiveCode | LiveCode | // recursive
function factorialr n
if n < 2 then
return 1
else
return n * factorialr(n-1)
end if
end factorialr
// using accumulator
function factorialacc n acc
if n = 0 then
return acc
else
return factorialacc(n-1, n * acc)
end if
end factorialacc
function factorial n
return factorialacc(n,1)
end factorial
// iterative
function factorialit n
put 1 into f
if n > 1 then
repeat with i = 1 to n
multiply f by i
end repeat
end if
return f
end factorialit |
http://rosettacode.org/wiki/Euler%27s_identity | Euler's identity |
This page uses content from Wikipedia. The original article was at Euler's_identity. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In mathematics, Euler's identity is the equality:
ei
π
{\displaystyle \pi }
+ 1 = 0
where
e is Euler's number, the base of natural logarithms,
i is the imaginary unit, which satisfies i2 = −1, and
π
{\displaystyle \pi }
is pi, the ratio of the circumference of a circle to its diameter.
Euler's identity is often cited as an example of deep mathematical beauty. Three of the basic arithmetic operations occur exactly once each: addition, multiplication, and exponentiation. The identity also links five fundamental mathematical constants:
The number 0.
The number 1.
The number
π
{\displaystyle \pi }
(
π
{\displaystyle \pi }
= 3.14159+),
The number e (e = 2.71828+), which occurs widely in mathematical analysis.
The number i, the imaginary unit of the complex numbers.
Task
Show in your language that Euler's identity is true. As much as possible and practical, mimic the Euler's identity equation.
Most languages are limited to IEEE 754 floating point calculations so will have some error in the calculation.
If that is the case, or there is some other limitation, show
that ei
π
{\displaystyle \pi }
+ 1 is approximately equal to zero and
show the amount of error in the calculation.
If your language is capable of symbolic calculations, show
that ei
π
{\displaystyle \pi }
+ 1 is exactly equal to zero for bonus kudos points.
| #Tcl | Tcl | # Set up complex sandbox (since we're doing a star import)
namespace eval complex_ns {
package require math::complexnumbers
namespace import ::math::complexnumbers::*
set pi [expr {acos(-1)}]
set r [+ [exp [complex 0 $pi]] [complex 1 0]]
puts "e**(pi*i) = [real $r]+[imag $r]i"
} |
http://rosettacode.org/wiki/Euler%27s_identity | Euler's identity |
This page uses content from Wikipedia. The original article was at Euler's_identity. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In mathematics, Euler's identity is the equality:
ei
π
{\displaystyle \pi }
+ 1 = 0
where
e is Euler's number, the base of natural logarithms,
i is the imaginary unit, which satisfies i2 = −1, and
π
{\displaystyle \pi }
is pi, the ratio of the circumference of a circle to its diameter.
Euler's identity is often cited as an example of deep mathematical beauty. Three of the basic arithmetic operations occur exactly once each: addition, multiplication, and exponentiation. The identity also links five fundamental mathematical constants:
The number 0.
The number 1.
The number
π
{\displaystyle \pi }
(
π
{\displaystyle \pi }
= 3.14159+),
The number e (e = 2.71828+), which occurs widely in mathematical analysis.
The number i, the imaginary unit of the complex numbers.
Task
Show in your language that Euler's identity is true. As much as possible and practical, mimic the Euler's identity equation.
Most languages are limited to IEEE 754 floating point calculations so will have some error in the calculation.
If that is the case, or there is some other limitation, show
that ei
π
{\displaystyle \pi }
+ 1 is approximately equal to zero and
show the amount of error in the calculation.
If your language is capable of symbolic calculations, show
that ei
π
{\displaystyle \pi }
+ 1 is exactly equal to zero for bonus kudos points.
| #Wren | Wren | import "/complex" for Complex
System.print((Complex.new(0, Num.pi).exp + Complex.one).toString) |
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.
| #ALGOL_W | ALGOL W | begin % Euler's method %
% Approximates y(t) in y'(t)=f(t,y) with y(a)=y0 and t=a..b and the step size h. %
real procedure euler ( real procedure f; real value y0, a, b, h ) ;
begin
real y, t;
y := y0;
t := a;
while t < b do begin
write( r_format := "A", r_w := 8, r_d := 4, s_w := 0, t, ": ", y );
y := y + ( h * f(t, y) );
t := t + h
end while_t_lt_b ;
write( "done" );
y
end euler ;
% Example: Newton's cooling law %
real procedure newtonCoolingLaw ( real value time, t ) ; -0.07 * (t - 20);
euler( newtonCoolingLaw, 100, 0, 100, 10 )
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.
| #BASIC | BASIC | PROCeuler("-0.07*(y-20)", 100, 0, 100, 2)
PROCeuler("-0.07*(y-20)", 100, 0, 100, 5)
PROCeuler("-0.07*(y-20)", 100, 0, 100, 10)
END
DEF PROCeuler(df$, y, a, b, s)
LOCAL t, @%
@% = &2030A
t = a
WHILE t <= b
PRINT t, y
y += s * EVAL(df$)
t += s
ENDWHILE
ENDPROC |
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
| #TI-83_BASIC | TI-83 BASIC | [Y=]
nMin=0
u(n)=u(n-1)+u(n-2)
u(nMin)={1,0}
[TABLE]
n u(n)
------- -------
0 0
1 1
2 1
3 2
4 3
5 5
6 8
7 13
8 21
9 34
10 55
11 89
12 144 |
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.
| #Factor | Factor | USING: assocs combinators formatting grouping grouping.extras io
kernel math math.primes math.primes.factors math.statistics
prettyprint sequences sequences.deep ;
PREDICATE: >3 < integer 3 > ;
GENERIC: depth ( seq -- n )
M: sequence depth
0 swap [ flatten1 [ 1 + ] dip ] to-fixed-point drop ;
M: integer depth drop 1 ;
MEMO: pfactors ( n -- seq ) 1 + factors ;
: category ( m -- n )
[ dup >3? [ pfactors ] when ] deep-map depth ;
: categories ( n -- assoc ) nprimes [ category ] collect-by ;
: table. ( seq n -- )
[ "" pad-groups ] keep group simple-table. ;
: categories... ( assoc -- )
[ [ "Category %d:\n" printf ] dip 15 table. ] assoc-each ;
: row. ( category first last count -- )
"Category %d: first->%d last->%d count->%d\n" printf ;
: categories. ( assoc -- )
[ [ minmax ] keep length row. ] assoc-each ;
200 categories categories... nl
1,000,000 categories categories. |
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.
| #Go | Go | package main
import (
"fmt"
"math"
"rcu"
)
var limit = int(math.Log(1e6) * 1e6 * 1.2) // should be more than enough
var primes = rcu.Primes(limit)
var prevCats = make(map[int]int)
func cat(p int) int {
if v, ok := prevCats[p]; ok {
return v
}
pf := rcu.PrimeFactors(p + 1)
all := true
for _, f := range pf {
if f != 2 && f != 3 {
all = false
break
}
}
if all {
return 1
}
if p > 2 {
len := len(pf)
for i := len - 1; i >= 1; i-- {
if pf[i-1] == pf[i] {
pf = append(pf[:i], pf[i+1:]...)
}
}
}
for c := 2; c <= 11; c++ {
all := true
for _, f := range pf {
if cat(f) >= c {
all = false
break
}
}
if all {
prevCats[p] = c
return c
}
}
return 12
}
func main() {
es := make([][]int, 12)
fmt.Println("First 200 primes:\n")
for _, p := range primes[0:200] {
c := cat(p)
es[c-1] = append(es[c-1], p)
}
for c := 1; c <= 6; c++ {
if len(es[c-1]) > 0 {
fmt.Println("Category", c, "\b:")
fmt.Println(es[c-1])
fmt.Println()
}
}
fmt.Println("First million primes:\n")
for _, p := range primes[200:1e6] {
c := cat(p)
es[c-1] = append(es[c-1], p)
}
for c := 1; c <= 12; c++ {
e := es[c-1]
if len(e) > 0 {
format := "Category %-2d: First = %7d Last = %8d Count = %6d\n"
fmt.Printf(format, c, e[0], e[len(e)-1], len(e))
}
}
} |
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
| #LLVM | LLVM | ; ModuleID = 'factorial.c'
; source_filename = "factorial.c"
; target datalayout = "e-m:w-i64:64-f80:128-n8:16:32:64-S128"
; target triple = "x86_64-pc-windows-msvc19.21.27702"
; This is not strictly LLVM, as it uses the C library function "printf".
; LLVM does not provide a way to print values, so the alternative would be
; to just load the string into memory, and that would be boring.
; Additional comments have been inserted, as well as changes made from the output produced by clang such as putting more meaningful labels for the jumps
$"\01??_C@_04PEDNGLFL@?$CFld?6?$AA@" = comdat any
@"\01??_C@_04PEDNGLFL@?$CFld?6?$AA@" = linkonce_odr unnamed_addr constant [5 x i8] c"%ld\0A\00", comdat, align 1
;--- The declaration for the external C printf function.
declare i32 @printf(i8*, ...)
; Function Attrs: noinline nounwind optnone uwtable
define i32 @factorial(i32) #0 {
;-- local copy of n
%2 = alloca i32, align 4
;-- long result
%3 = alloca i32, align 4
;-- int i
%4 = alloca i32, align 4
;-- local n = parameter n
store i32 %0, i32* %2, align 4
;-- result = 1
store i32 1, i32* %3, align 4
;-- i = 1
store i32 1, i32* %4, align 4
br label %loop
loop:
;-- i <= n
%5 = load i32, i32* %4, align 4
%6 = load i32, i32* %2, align 4
%7 = icmp sle i32 %5, %6
br i1 %7, label %loop_body, label %exit
loop_body:
;-- result *= i
%8 = load i32, i32* %4, align 4
%9 = load i32, i32* %3, align 4
%10 = mul nsw i32 %9, %8
store i32 %10, i32* %3, align 4
br label %loop_increment
loop_increment:
;-- ++i
%11 = load i32, i32* %4, align 4
%12 = add nsw i32 %11, 1
store i32 %12, i32* %4, align 4
br label %loop
exit:
;-- return result
%13 = load i32, i32* %3, align 4
ret i32 %13
}
; Function Attrs: noinline nounwind optnone uwtable
define i32 @main() #0 {
;-- factorial(5)
%1 = call i32 @factorial(i32 5)
;-- printf("%ld\n", factorial(5))
%2 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([5 x i8], [5 x i8]* @"\01??_C@_04PEDNGLFL@?$CFld?6?$AA@", i32 0, i32 0), i32 %1)
;-- return 0
ret i32 0
}
attributes #0 = { noinline nounwind optnone uwtable "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "no-frame-pointer-elim"="false" "no-infs-fp-math"="false" "no-jump-tables"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+fxsr,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" }
!llvm.module.flags = !{!0, !1}
!llvm.ident = !{!2}
!0 = !{i32 1, !"wchar_size", i32 2}
!1 = !{i32 7, !"PIC Level", i32 2}
!2 = !{!"clang version 6.0.1 (tags/RELEASE_601/final)"} |
http://rosettacode.org/wiki/Euler%27s_identity | Euler's identity |
This page uses content from Wikipedia. The original article was at Euler's_identity. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In mathematics, Euler's identity is the equality:
ei
π
{\displaystyle \pi }
+ 1 = 0
where
e is Euler's number, the base of natural logarithms,
i is the imaginary unit, which satisfies i2 = −1, and
π
{\displaystyle \pi }
is pi, the ratio of the circumference of a circle to its diameter.
Euler's identity is often cited as an example of deep mathematical beauty. Three of the basic arithmetic operations occur exactly once each: addition, multiplication, and exponentiation. The identity also links five fundamental mathematical constants:
The number 0.
The number 1.
The number
π
{\displaystyle \pi }
(
π
{\displaystyle \pi }
= 3.14159+),
The number e (e = 2.71828+), which occurs widely in mathematical analysis.
The number i, the imaginary unit of the complex numbers.
Task
Show in your language that Euler's identity is true. As much as possible and practical, mimic the Euler's identity equation.
Most languages are limited to IEEE 754 floating point calculations so will have some error in the calculation.
If that is the case, or there is some other limitation, show
that ei
π
{\displaystyle \pi }
+ 1 is approximately equal to zero and
show the amount of error in the calculation.
If your language is capable of symbolic calculations, show
that ei
π
{\displaystyle \pi }
+ 1 is exactly equal to zero for bonus kudos points.
| #zkl | zkl | var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library)
Z,pi,e := GSL.Z, (0.0).pi, (0.0).e;
println("e^(\u03c0i) + 1 = %s \u2245 0".fmt( Z(e).pow(Z(0,1)*pi) + 1 ));
println("TMI: ",(Z(e).pow(Z(0,1)*pi) + 1 ).format(0,25,"g")); |
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.
| #C | C | #include <stdio.h>
#include <math.h>
typedef double (*deriv_f)(double, double);
#define FMT " %7.3f"
void ivp_euler(deriv_f f, double y, int step, int end_t)
{
int t = 0;
printf(" Step %2d: ", (int)step);
do {
if (t % 10 == 0) printf(FMT, y);
y += step * f(t, y);
} while ((t += step) <= end_t);
printf("\n");
}
void analytic()
{
double t;
printf(" Time: ");
for (t = 0; t <= 100; t += 10) printf(" %7g", t);
printf("\nAnalytic: ");
for (t = 0; t <= 100; t += 10)
printf(FMT, 20 + 80 * exp(-0.07 * t));
printf("\n");
}
double cooling(double t, double temp)
{
return -0.07 * (temp - 20);
}
int main()
{
analytic();
ivp_euler(cooling, 100, 2, 100);
ivp_euler(cooling, 100, 5, 100);
ivp_euler(cooling, 100, 10, 100);
return 0;
} |
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
| #TI-89_BASIC | TI-89 BASIC | fib(n)
when(n<2, n, fib(n-1) + fib(n-2)) |
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.
| #Java | Java | import java.util.*;
public class ErdosSelfridge {
private int[] primes;
private int[] category;
public static void main(String[] args) {
ErdosSelfridge es = new ErdosSelfridge(1000000);
System.out.println("First 200 primes:");
for (var e : es.getPrimesByCategory(200).entrySet()) {
int category = e.getKey();
List<Integer> primes = e.getValue();
System.out.printf("Category %d:\n", category);
for (int i = 0, n = primes.size(); i != n; ++i)
System.out.printf("%4d%c", primes.get(i), (i + 1) % 15 == 0 ? '\n' : ' ');
System.out.printf("\n\n");
}
System.out.println("First 1,000,000 primes:");
for (var e : es.getPrimesByCategory(1000000).entrySet()) {
int category = e.getKey();
List<Integer> primes = e.getValue();
System.out.printf("Category %2d: first = %7d last = %8d count = %d\n", category,
primes.get(0), primes.get(primes.size() - 1), primes.size());
}
}
private ErdosSelfridge(int limit) {
PrimeGenerator primeGen = new PrimeGenerator(100000, 200000);
List<Integer> primeList = new ArrayList<>();
for (int i = 0; i < limit; ++i)
primeList.add(primeGen.nextPrime());
primes = new int[primeList.size()];
for (int i = 0; i < primes.length; ++i)
primes[i] = primeList.get(i);
category = new int[primes.length];
}
private Map<Integer, List<Integer>> getPrimesByCategory(int limit) {
Map<Integer, List<Integer>> result = new TreeMap<>();
for (int i = 0; i < limit; ++i) {
var p = result.computeIfAbsent(getCategory(i), k -> new ArrayList<Integer>());
p.add(primes[i]);
}
return result;
}
private int getCategory(int index) {
if (category[index] != 0)
return category[index];
int maxCategory = 0;
int n = primes[index] + 1;
for (int i = 0; n > 1; ++i) {
int p = primes[i];
if (p * p > n)
break;
int count = 0;
for (; n % p == 0; ++count)
n /= p;
if (count != 0) {
int category = (p <= 3) ? 1 : 1 + getCategory(i);
maxCategory = Math.max(maxCategory, category);
}
}
if (n > 1) {
int category = (n <= 3) ? 1 : 1 + getCategory(getIndex(n));
maxCategory = Math.max(maxCategory, category);
}
category[index] = maxCategory;
return maxCategory;
}
private int getIndex(int prime) {
return Arrays.binarySearch(primes, prime);
}
} |
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
| #Logo | Logo | to factorial :n
if :n < 2 [output 1]
output :n * factorial :n-1
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.
| #C.23 | C# | using System;
namespace prog
{
class MainClass
{
const float T0 = 100f;
const float TR = 20f;
const float k = 0.07f;
readonly static float[] delta_t = {2.0f,5.0f,10.0f};
const int n = 100;
public delegate float func(float t);
static float NewtonCooling(float t)
{
return -k * (t-TR);
}
public static void Main (string[] args)
{
func f = new func(NewtonCooling);
for(int i=0; i<delta_t.Length; i++)
{
Console.WriteLine("delta_t = " + delta_t[i]);
Euler(f,T0,n,delta_t[i]);
}
}
public static void Euler(func f, float y, int n, float h)
{
for(float x=0; x<=n; x+=h)
{
Console.WriteLine("\t" + x + "\t" + y);
y += h * f(y);
}
}
}
} |
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
| #Tiny_BASIC | Tiny BASIC | 10 LET A = 0
20 LET B = 1
30 PRINT "Which F_n do you want?"
40 INPUT N
50 IF N = 0 THEN GOTO 140
60 IF N = 1 THEN GOTO 120
70 LET C = B + A
80 LET A = B
90 LET B = C
100 LET N = N - 1
110 GOTO 60
120 PRINT B
130 END
140 PRINT 0
150 END
|
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.
| #Julia | Julia | using Primes
primefactors(n) = collect(keys(factor(n)))
function ErdösSelfridge(n)
highfactors = filter(>(3), primefactors(n + 1))
category = 1
while !isempty(highfactors)
highfactors = unique(reduce(vcat, [filter(>(3), primefactors(a + 1)) for a in highfactors]))
category += 1
end
return category
end
function testES(numshowprimes, numtotalprimes)
println("First $numshowprimes primes by Erdös-Selfridge categories:")
dict = Dict{Int, Vector{Int}}(i => [] for i in 1:5)
for p in primes(prime(numshowprimes))
push!(dict[ErdösSelfridge(p)], p)
end
for cat in 1:5
println("$cat => ", dict[cat])
end
dict2 = Dict{Int, Tuple{Int, Int, Int}}(i => (0, 0, 0) for i in 1:11)
println("\nTotals for first $numtotalprimes primes by Erdös-Selfridge categories:")
for p in primes(prime(numtotalprimes))
cat = ErdösSelfridge(p)
fir, tot, las = dict2[cat]
fir == 0 && (fir = p)
dict2[cat] = (fir, tot + 1, p)
end
for cat in 1:11
first, total, last = dict2[cat]
println("Category", lpad(cat, 3), " => first:", lpad(first, 8), ", total:", lpad(total, 7), ", last:", last)
end
end
testES(200, 1_000_000)
|
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.
| #Perl | Perl | use strict;
use warnings;
use feature 'say';
use List::Util 'max';
use ntheory qw/factor/;
use Primesieve qw(generate_primes);
my @primes = (0, generate_primes (1, 10**8));
my %cat = (2 => 1, 3 => 1);
sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r }
sub ES {
my ($n) = @_;
my @factors = factor $n + 1;
my $category = max map { defined $cat{$_} and $cat{$_} } @factors;
unless (defined $cat{ $factors[-1] }) {
$category = max $category, (1 + max map { $cat{$_} } factor 1 + $factors[-1]);
$cat{ $factors[-1] } = $category;
}
$category
}
my %es;
my $upto = 200;
push @{$es{ES($_)}}, $_ for @primes[1..$upto];
say "First $upto primes, Erdös-Selfridge categorized:";
say "$_: " . join ' ', sort {$a <=> $b} @{$es{$_}} for sort keys %es;
%es = ();
$upto = 1_000_000;
say "\nSummary of first @{[comma $upto]} primes, Erdös-Selfridge categorized:";
push @{$es{ES($_)}}, $_ for @primes[1..$upto];
printf "Category %2d: first: %9s last: %10s count: %s\n",
map { comma $_ } $_, (sort {$a <=> $b} @{$es{$_}})[0, -1], scalar @{$es{$_}}
for sort {$a <=> $b} keys %es; |
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
| #LOLCODE | LOLCODE | HAI 1.3
HOW IZ I Faktorial YR Number
BOTH SAEM 1 AN BIGGR OF Number AN 1
O RLY?
YA RLY
FOUND YR 1
NO WAI
FOUND YR PRODUKT OF Number AN I IZ Faktorial YR DIFFRENCE OF Number AN 1 MKAY
OIC
IF U SAY SO
IM IN YR LOOP UPPIN YR Index WILE DIFFRINT Index AN 13
VISIBLE Index "! = " I IZ Faktorial YR Index MKAY
IM OUTTA YR LOOP
KTHXBYE |
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.
| #C.2B.2B | C++ | #include <iomanip>
#include <iostream>
typedef double F(double,double);
/*
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 f, double y0, double a, double b, double h)
{
double y = y0;
for (double t = a; t < b; t += h)
{
std::cout << std::fixed << std::setprecision(3) << t << " " << y << "\n";
y += h * f(t, y);
}
std::cout << "done\n";
}
// Example: Newton's cooling law
double newtonCoolingLaw(double, double t)
{
return -0.07 * (t - 20);
}
int main()
{
euler(newtonCoolingLaw, 100, 0, 100, 2);
euler(newtonCoolingLaw, 100, 0, 100, 5);
euler(newtonCoolingLaw, 100, 0, 100, 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
| #True_BASIC | True BASIC | FUNCTION fibonacci (n)
LET n1 = 0
LET n2 = 1
FOR k = 1 TO ABS(n)
LET sum = n1 + n2
LET n1 = n2
LET n2 = sum
NEXT k
IF n < 0 THEN
LET fibonacci = n1 * ((-1) ^ ((-n) + 1))
ELSE
LET fibonacci = n1
END IF
END FUNCTION
PRINT fibonacci(0) ! 0
PRINT fibonacci(13) ! 233
PRINT fibonacci(-42) !-267914296
PRINT fibonacci(47) ! 2971215073
END |
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
| #11l | 11l | F isEsthetic(=n, b)
I n == 0 {R 0B}
V i = n % b
n I/= b
L n > 0
V j = n % b
I abs(i - j) != 1
R 0B
n I/= b
i = j
R 1B
F listEsths(Int64 n1, n2, m1, m2; perLine, all)
[Int64] esths
F dfs(Int64 n, m, i) -> N
I i C n .. m
@esths.append(i)
I i == 0 | i > m {R}
V d = i % 10
V i1 = i * 10 + d - 1
V i2 = i1 + 2
I d == 0
@dfs(n, m, i2)
E I d == 9
@dfs(n, m, i1)
E
@dfs(n, m, i1)
@dfs(n, m, i2)
L(i) 10
dfs(n2, m2, i)
print(‘Base 10: ’esths.len‘ esthetic numbers between ’n1‘ and ’m1‘:’)
I all
L(esth) esths
print(esth, end' I (L.index + 1) % perLine == 0 {"\n"} E ‘ ’)
print()
E
L(i) 0 .< perLine
print(esths[i], end' ‘ ’)
print("\n............")
L(i) esths.len - perLine .< esths.len
print(esths[i], end' ‘ ’)
print()
print()
L(b) 2..16
print(‘Base ’b‘: ’(4 * b)‘th to ’(6 * b)‘th esthetic numbers:’)
V n = Int64(1)
V c = Int64(0)
L c < 6 * b
I isEsthetic(n, b)
c++
I c >= 4 * b
print(String(n, radix' b), end' ‘ ’)
n++
print("\n")
listEsths(1000, 1010, 9999, 9898, 16, 1B)
listEsths(100'000'000, 101'010'101, 130'000'000, 123'456'789, 9, 1B)
listEsths(100'000'000'000, 101'010'101'010, 130'000'000'000, 123'456'789'898, 7, 0B)
listEsths(100'000'000'000'000, 101'010'101'010'101, 130'000'000'000, 123'456'789'898'989, 5, 0B)
listEsths(100'000'000'000'000'000, 101'010'101'010'101'010, 130'000'000'000'000'000, 123'456'789'898'989'898, 4, 0B) |
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.
| #Phix | Phix | with javascript_semantics
sequence escache = {}
function es_cat(integer p)
if p>length(escache) and platform()!=JS then
escache &= repeat(0,p-length(escache))
end if
integer category = escache[p]
if not category then
sequence f = filter(prime_factors(p+1,false,-1),">",3)
category = 1
if length(f) then
category += max(apply(f,es_cat))
end if
escache[p] = category
end if
return category
end function
procedure categorise(integer n)
sequence p = get_primes(n)
printf(1,"First %,d primes:\n",n)
atom t1 = time()
sequence es = {}
for i=1 to n do
if time()>t1 then
progress("categorising %d/%d...",{i,n})
t1 = time()+1
end if
integer category = es_cat(p[i])
while length(es)<category do
es = append(es,{})
end while
es[category] &= p[i]
end for
progress("")
for c=1 to length(es) do
sequence e = es[c]
if n=200 then
printf(1,"Category %d: %s\n",{c,join(shorten(e,"primes",5,"%d"),",")})
else
printf(1,"Category %2d: %7d .. %-8d Count: %d\n",{c,e[1],e[$],length(e)})
end if
end for
printf(1,"\n")
end procedure
atom t0 = time()
categorise(200)
categorise(1e6)
?elapsed(time()-t0)
|
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
| #Lua | Lua | function fact(n)
return n > 0 and n * fact(n-1) or 1
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.
| #Clay | Clay |
import printer.formatter as pf;
euler(f, y, a, b, h) {
while (a < b) {
println(pf.rightAligned(2, a), " ", y);
a += h;
y += h * f(y);
}
}
main() {
for (i in [2.0, 5.0, 10.0]) {
println("\nFor delta = ", i, ":");
euler((temp) => -0.07 * (temp - 20), 100.0, 0.0, 100.0, i);
}
}
|
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.
| #Clojure | Clojure | (ns newton-cooling
(:gen-class))
(defn euler [f y0 a b h]
"Euler's Method.
Approximates y(time) in y'(time)=f(time,y) with y(a)=y0 and t=a..b and the step size h."
(loop [t a
y y0
result []]
(if (<= t b)
(recur (+ t h) (+ y (* (f (+ t h) y) h)) (conj result [(double t) (double y)]))
result)))
(defn newton-coolling [t temp]
"Newton's cooling law, f(t,T) = -0.07*(T-20)"
(* -0.07 (- temp 20)))
; Run for case h = 10
(println "Example output")
(doseq [q (euler newton-coolling 100 0 100 10)]
(println (apply format "%.3f %.3f" q)))
|
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
| #TSE_SAL | TSE SAL |
// library: math: get: series: fibonacci <description></description> <version control></version control> <version>1.0.0.0.3</version> <version control></version control> (filenamemacro=getmasfi.s) [<Program>] [<Research>] [kn, ri, su, 20-01-2013 22:04:02]
INTEGER PROC FNMathGetSeriesFibonacciI( INTEGER nI )
//
// Method:
//
// 1. Take the sum of the last 2 terms
//
// 2. Let the sum be the last term
// and goto step 1
//
INTEGER I = 0
INTEGER minI = 1
INTEGER maxI = nI
INTEGER term1I = 0
INTEGER term2I = 1
INTEGER term3I = 0
//
FOR I = minI TO maxI
//
// make value 3 equal to sum of two previous values 1 and 2
//
term3I = term1I + term2I
//
// make value 1 equal to next value 2
//
term1I = term2I
//
// make value 2 equal to next value 3
//
term2I = term3I
//
ENDFOR
//
RETURN( term3I )
//
END
PROC Main()
STRING s1[255] = "3"
REPEAT
IF ( NOT ( Ask( " = ", s1, _EDIT_HISTORY_ ) ) AND ( Length( s1 ) > 0 ) ) RETURN() ENDIF
Warn( FNMathGetSeriesFibonacciI( Val( s1 ) ) ) // gives e.g. 3
UNTIL FALSE
END
|
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
| #ALGOL_68 | ALGOL 68 | BEGIN # find some esthetic numbers: numbers whose successive digits differ by 1 #
# returns TRUE if n is esthetic in the specified base, FALSE otherwise #
PRIO ISESTHETIC = 1;
OP ISESTHETIC = ( INT n, base )BOOL:
BEGIN
INT v := ABS n;
BOOL is esthetic := TRUE;
INT prev digit := v MOD base;
v OVERAB base;
WHILE v > 0 AND is esthetic
DO
INT next digit := v MOD base;
is esthetic := ABS ( next digit - prev digit ) = 1;
prev digit := next digit;
v OVERAB base
OD;
is esthetic
END # ISESTHETIC # ;
# returns an array of the first n esthetic numbers in the specified base #
PRIO ESTHETIC = 1;
OP ESTHETIC = ( INT n, base )[]INT:
BEGIN
[ 1 : n ]INT result;
INT e count := 0;
FOR i WHILE e count < n DO
IF i ISESTHETIC base THEN result[ e count +:= 1 ] := i FI
OD;
result
END # ESTHETIC # ;
# returns a string erpresentation of n in the specified base, 2 <= base <= 16 must be TRUE #
PRIO TOBASESTRING = 1;
OP TOBASESTRING = ( INT n, base )STRING:
IF base < 2 OR base > 16
THEN # invalid vbase #
"?" + whole( n, 0 ) + ":" + whole( base, 0 ) + "?"
ELSE
INT v := ABS n;
STRING digits = "0123456789abcdef";
STRING result := digits[ ( v MOD base ) + 1 ];
WHILE ( v OVERAB base ) > 0 DO
digits[ ( v MOD base ) + 1 ] +=: result
OD;
IF n < 0 THEN "-" +=: result FI;
result
FI # TOBASESTRING # ;
# sets count to the number of esthetic numbers with length digits in base b less than max #
# also displays the esthetic numbers #
PROC show esthetic = ( INT number, base, length, max, REF INT count )VOID:
IF length = 1
THEN # number is esthetic #
IF number <= max THEN
# number is in the required range #
print( ( " ", whole( number, 0 ) ) );
IF ( count +:= 1 ) MOD 9 = 0 THEN print( ( newline ) ) FI
FI
ELSE
# find the esthetic numbers that start with number #
INT digit = number MOD base;
INT prefix = number * base;
IF digit > 0 THEN # can have a lower digit #
show esthetic( prefix + ( digit - 1 ), base, length - 1, max, count )
FI;
IF digit < base - 1 THEN # can have a higher digit #
show esthetic( prefix + ( digit + 1 ), base, length - 1, max, count )
FI
FI # show esthetic # ;
# task #
# esthetic numbers from base * 4 to base * 6 for bases 2 to 16 #
FOR base FROM 2 TO 16 DO
INT e from = base * 4;
INT e to = base * 6;
print( ( "Esthetic numbers ", whole( e from, 0 ), " to ", whole( e to, 0 ), " in base ", whole( base, 0 ), newline ) );
[]INT e numbers = e to ESTHETIC base;
print( ( " " ) );
FOR n FROM e from TO e to DO
print( ( " ", e numbers[ n ] TOBASESTRING base ) )
OD;
print( ( newline ) )
OD;
# esthetic base 10 numbers between 1000 and 9999 #
print( ( "Base 10 eshetic numbers between 1000 and 9999", newline ) );
INT e count := 0;
FOR i FROM 1000 TO 9999 DO
IF i ISESTHETIC 10 THEN
print( ( " ", whole( i, 0 ) ) );
IF ( e count +:= 1 ) MOD 16 = 0 THEN print( ( newline ) ) FI
FI
OD;
print( ( newline, newline ) );
print( ( "Esthetic numbers between 100 000 000 and 130 000 000:", newline ) );
e count := 0;
show esthetic( 1, 10, 9, 130 000 000, e count );
print( ( newline ) );
print( ( "Found ", whole( e count, 0 ), " esthetic numbers", newline ) )
END |
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.
| #Raku | Raku | use Prime::Factor;
use Lingua::EN::Numbers;
use Math::Primesieve;
my $sieve = Math::Primesieve.new;
my %cat = 2 => 1, 3 => 1;
sub Erdös-Selfridge ($n) {
my @factors = prime-factors $n + 1;
my $category = max %cat{ @factors };
unless %cat{ @factors[*-1] } {
$category max= ( 1 + max %cat{ prime-factors 1 + @factors[*-1] } );
%cat{ @factors[*-1] } = $category;
}
$category
}
my $upto = 200;
say "First { cardinal $upto } primes; Erdös-Selfridge categorized:";
.say for sort $sieve.n-primes($upto).categorize: &Erdös-Selfridge;
$upto = 1_000_000;
say "\nSummary of first { cardinal $upto } primes; Erdös-Selfridge categorized:";
printf "Category %2d: first: %9s last: %10s count: %s\n", ++$, |(.[0], .[*-1], .elems).map: &comma
for $sieve.n-primes($upto).categorize( &Erdös-Selfridge ).sort(+*.key)».value; |
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
| #M2000_Interpreter | M2000 Interpreter |
Module CheckIt {
Locale 1033 ' ensure #,### print with comma
Function factorial (n){
If n<0 then Error "Factorial Error!"
If n>27 then Error "Overflow"
m=1@:While n>1 {m*=n:n--}:=m
}
Const Proportional=4
Const ProportionalLeftJustification=5
Const NonProportional=0
Const NonProportionalLeftJustification=1
For i=1 to 27
\\ we can print over (erasing line first), without new line at the end
\\ and we can change how numbers apears, and the with of columns
\\ numbers by default have right justification
\\ all $() format have temporary use in this kind of print.
Print Over $(Proportional),$("\f\a\c\t\o\r\i\a\l\(#\)\=",15), i, $(ProportionalLeftJustification), $("#,###",40), factorial(i)
Print \\ new line
Next i
}
Checkit
|
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.
| #0815 | 0815 |
}:s:|=<:2:x~#:e:=/~%~<:20:~$=<:73:x<:69:~$~$~<:20:~$=^:o:<:65:
x<:76:=$=$~$<:6E:~$<:a:~$^:s:}:o:<:6F:x<:64:x~$~$$<:a:~$^:s:
|
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.
| #COBOL | COBOL | DELEGATE-ID func.
PROCEDURE DIVISION USING VALUE t AS FLOAT-LONG
RETURNING ret AS FLOAT-LONG.
END DELEGATE.
CLASS-ID. MainClass.
78 T0 VALUE 100.0.
78 TR VALUE 20.0.
78 k VALUE 0.07.
01 delta-t INITIALIZE ONLY STATIC
FLOAT-LONG OCCURS 3 VALUES 2.0, 5.0, 10.0.
78 n VALUE 100.
METHOD-ID NewtonCooling STATIC.
PROCEDURE DIVISION USING VALUE t AS FLOAT-LONG
RETURNING ret AS FLOAT-LONG.
COMPUTE ret = - k * (t - TR)
END METHOD.
METHOD-ID Main STATIC.
DECLARE f AS TYPE func
SET f TO METHOD self::NewtonCooling
DECLARE delta-t-len AS BINARY-LONG
MOVE delta-t::Length TO delta-t-len
PERFORM VARYING i AS BINARY-LONG FROM 1 BY 1
UNTIL i > delta-t-len
DECLARE elt AS FLOAT-LONG = delta-t (i)
INVOKE TYPE Console::WriteLine("delta-t = {0:F4}", elt)
INVOKE self::Euler(f, T0, n, elt)
END-PERFORM
END METHOD.
METHOD-ID Euler STATIC.
PROCEDURE DIVISION USING VALUE f AS TYPE func, y AS FLOAT-LONG,
n AS BINARY-LONG, h AS FLOAT-LONG.
PERFORM VARYING x AS BINARY-LONG FROM 0 BY h UNTIL x >= n
INVOKE TYPE Console::WriteLine("x = {0:F4}, y = {1:F4}", x, y)
COMPUTE y = y + h * RUN f(y)
END-PERFORM
END METHOD.
END CLASS. |
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
| #11l | 11l | F binomial_coeff(n, k)
V result = 1
L(i) 1..k
result = result * (n - i + 1) / i
R result
print(binomial_coeff(5, 3)) |
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
| #Turing | Turing | % Recursive
function fibb (n: int) : int
if n < 2 then
result n
else
result fibb (n-1) + fibb (n-2)
end if
end fibb
% Iterative
function ifibb (n: int) : int
var a := 0
var b := 1
for : 1 .. n
a := a + b
b := a - b
end for
result a
end ifibb
for i : 0 .. 10
put fibb (i) : 4, ifibb (i) : 4
end for |
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
| #Arturo | Arturo | esthetic?: function [n, b][
if n=0 -> return false
k: n % b
l: n / b
while [l>0][
j: l % b
if 1 <> abs k-j -> return false
l: l / b
k: j
]
return true
]
HEX: "0000000000ABCDEF"
getHex: function [ds][
map ds 'd [
(d < 10)? -> to :string d
-> to :string HEX\[d]
]
]
findEsthetics: function [base][
limDown: base * 4
limUp: base * 6
cnt: 0
i: 1
result: new []
while [cnt < limUp][
if esthetic? i base [
cnt: cnt + 1
if cnt >= limDown ->
'result ++ join getHex digits.base: base i
]
i: i + 1
]
print ["Base" base "->" (to :string limDown)++"th" "to" (to :string limUp)++"th" "esthetic numbers:"]
print result
print ""
]
loop 2..16 'bs ->
findEsthetics bs
print "Esthetic numbers between 1000 and 9999:"
loop split.every: 16 select 1000..9999 'num -> esthetic? num 10 'row [
print map to [:string] row 'item -> pad item 4
] |
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.
| #Rust | Rust | // [dependencies]
// primal = "0.3"
use std::collections::BTreeMap;
struct ErdosSelfridge {
primes: Vec<usize>,
category: Vec<u32>,
}
impl ErdosSelfridge {
fn new(limit: usize) -> ErdosSelfridge {
let mut es = ErdosSelfridge {
primes: primal::Primes::all().take(limit).collect(),
category: Vec::new(),
};
es.category.resize(es.primes.len(), 0);
es
}
fn get_category(&mut self, index: usize) -> u32 {
if self.category[index] != 0 {
return self.category[index];
}
let mut max_category = 0;
let mut n = self.primes[index] + 1;
for i in 0.. {
let p = self.primes[i];
if p * p > n {
break;
}
let mut count = 0;
while n % p == 0 {
n /= p;
count += 1;
}
if count != 0 {
let category = if p <= 3 { 1 } else { 1 + self.get_category(i) };
max_category = std::cmp::max(max_category, category);
}
}
if n > 1 {
let i = self.get_index(n);
let category = if n <= 3 { 1 } else { 1 + self.get_category(i) };
max_category = std::cmp::max(max_category, category);
}
self.category[index] = max_category;
max_category
}
fn get_index(&self, prime: usize) -> usize {
self.primes.binary_search(&prime).unwrap()
}
fn get_primes_by_category(&mut self, limit: usize) -> BTreeMap<u32, Vec<usize>> {
let mut primes_by_category: BTreeMap<u32, Vec<usize>> = BTreeMap::new();
for i in 0..limit {
let category = self.get_category(i);
let prime = self.primes[i];
if let Some(primes) = primes_by_category.get_mut(&category) {
primes.push(prime);
} else {
let mut primes = Vec::new();
primes.push(prime);
primes_by_category.insert(category, primes);
}
}
primes_by_category
}
}
fn main() {
let mut es = ErdosSelfridge::new(1000000);
let primes_by_category = es.get_primes_by_category(200);
println!("First 200 primes:");
for (category, primes) in primes_by_category.iter() {
println!("Category {}:", category);
for i in 0..primes.len() {
print!(
"{:4}{}",
primes[i],
if (i + 1) % 15 == 0 { "\n" } else { " " }
);
}
print!("\n\n");
}
println!("First 1,000,000 primes:");
let primes_by_category = es.get_primes_by_category(1000000);
for (category, primes) in primes_by_category.iter() {
let first = primes[0];
let count = primes.len();
let last = primes[count - 1];
println!(
"Category {:2}: first = {:7} last = {:8} count = {}",
category, first, last, count
);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.