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/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
| #Python | Python | from math import *
def analytic_fibonacci(n):
sqrt_5 = sqrt(5);
p = (1 + sqrt_5) / 2;
q = 1/p;
return int( (p**n + q**n) / sqrt_5 + 0.5 )
for i in range(1,31):
print analytic_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
| #FunL | FunL | def factorial( n ) =
if n < 0
error( 'factorial: n should be non-negative' )
else
res = 1
for i <- 2..n
res *= i
res |
http://rosettacode.org/wiki/Execute_Brain**** | Execute Brain**** | Execute Brain**** is an implementation of Brainf***.
Other implementations of Brainf***.
RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages.
Below are links to each of the versions of RCBF.
An implementation need only properly implement the following instructions:
Command
Description
>
Move the pointer to the right
<
Move the pointer to the left
+
Increment the memory cell under the pointer
-
Decrement the memory cell under the pointer
.
Output the character signified by the cell at the pointer
,
Input a character and store it in the cell at the pointer
[
Jump past the matching ] if the cell under the pointer is 0
]
Jump back to the matching [ if the cell under the pointer is nonzero
Any cell size is allowed, EOF (End-O-File) support is optional, as is whether you have bounded or unbounded memory.
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 GO SUB 1000
20 LET e=LEN p$
30 LET a$=p$(ip)
40 IF a$=">" THEN LET dp=dp+1
50 IF a$="<" THEN LET dp=dp-1
60 IF a$="+" THEN LET d(dp)=d(dp)+1
70 IF a$="-" THEN LET d(dp)=d(dp)-1
80 IF a$="." THEN PRINT CHR$ d(dp);
90 IF a$="," THEN INPUT d(dp)
100 IF a$="[" THEN GO SUB 500
110 IF a$="]" THEN LET bp=bp-1: IF d(dp)<>0 THEN LET ip=b(bp)-1
120 LET ip=ip+1
130 IF ip>e THEN PRINT "eof": STOP
140 GO TO 30
499 REM match close
500 LET bc=1: REM bracket counter
510 FOR x=ip+1 TO e
520 IF p$(x)="[" THEN LET bc=bc+1
530 IF p$(x)="]" THEN LET bc=bc-1
540 IF bc=0 THEN LET b(bp)=ip: LET be=x: LET x=e: REM bc will be 0 once all the subnests have been counted over
550 IF bc=0 AND d(dp)=0 THEN LET ip=be: LET bp=bp-1
560 NEXT x
570 LET bp=bp+1
580 RETURN
999 REM initialisation
1000 DIM d(100): REM data stack
1010 LET dp=1: REM data pointer
1020 LET ip=1: REM instruction pointer
1030 DIM b(30): REM bracket stack
1040 LET bp=1: REM bracket pointer
1050 LET p$="++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>+++++.": REM program, marginally modified from Wikipedia; outputs CHR$ 13 at the end instead of CHR$ 10 as ZX Spectrum Basic handles the carriage return better than the line feed
1060 RETURN |
http://rosettacode.org/wiki/Evolutionary_algorithm | Evolutionary algorithm | Starting with:
The target string: "METHINKS IT IS LIKE A WEASEL".
An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent).
A fitness function that computes the ‘closeness’ of its argument to the target string.
A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated.
While the parent is not yet the target:
copy the parent C times, each time allowing some random probability that another character might be substituted using mutate.
Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others.
repeat until the parent converges, (hopefully), to the target.
See also
Wikipedia entry: Weasel algorithm.
Wikipedia entry: Evolutionary algorithm.
Note: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions
A cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically,
While the parent is not yet the target:
copy the parent C times, each time allowing some random probability that another character might be substituted using mutate.
Note that some of the the solutions given retain characters in the mutated string that are correct in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of "converges"
(:* repeat until the parent converges, (hopefully), to the target.
Strictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by not being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent!
As illustration of this error, the code for 8th has the following remark.
Create a new string based on the TOS, changing randomly any characters which
don't already match the target:
NOTE: this has been changed, the 8th version is completely random now
Clearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters!
To ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.
| #zkl | zkl | const target = "METHINKS IT IS LIKE A WEASEL";
const C = 100; // Number of children in each generation.
const P = 0.05; // Mutation probability.
const A2ZS = ["A".."Z"].walk().append(" ").concat();
fcn fitness(s){ Utils.zipWith('!=,target,s).sum(0) } // bigger is worser
fcn rnd{ A2ZS[(0).random(27)] }
fcn mutate(s){ s.apply(fcn(c){ if((0.0).random(1) < P) rnd() else c }) }
parent := target.len().pump(String,rnd); // random string of "A..Z "
gen:=0; do{ // mutate C copies of parent and pick the fittest
parent = (0).pump(C,List,T(Void,parent),mutate)
.reduce(fcn(a,b){ if(fitness(a)<fitness(b)) a else b });
println("Gen %2d, dist=%2d: %s".fmt(gen+=1, fitness(parent), parent));
}while(parent != target); |
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
| #QB64_2 | QB64 | _DEFINE F AS _UNSIGNED _INTEGER64
CLS
PRINT
PRINT "Enter 40 to more easily see the difference in calculation speeds."
PRINT
INPUT "Enter n for Fibonacci(n): ", n
PRINT
PRINT " Analytic Method (Fastest): F("; LTRIM$(STR$(n)); ") ="; fA(n)
PRINT "Iterative Method (Fast): F("; LTRIM$(STR$(n)); ") ="; fI(n)
PRINT "Recursive Method (Slow): F("; LTRIM$(STR$(n)); ") ="; fR(n)
END
' === Analytic Fibonacci Function (Fastest)
FUNCTION fA (n)
fA = INT(0.5 + (((SQR(5) + 1) / 2) ^ n) / SQR(5))
END FUNCTION
' === Iterative Fibonacci Function (Fast)
FUNCTION fI (n)
FOR i = 1 TO n
IF i < 3 THEN a = 1: b = 1
t = fI + b: fI = b: b = t
NEXT
END FUNCTION
' === Recursive Fibonacci function (Slow)
FUNCTION fR (n)
IF n <= 1 THEN
fR = n
ELSE
fR = fR(n - 1) + fR(n - 2)
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
| #Futhark | Futhark |
fun fact(n: int): int =
if n == 0 then 1
else n * fact(n-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
| #Qi | Qi |
(define fib
0 -> 0
1 -> 1
N -> (+ (fib-r (- N 1))
(fib-r (- N 2))))
|
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
| #Iterative_34 | Iterative |
fun fact(n: int): int =
loop (out = 1) = for i < n do
out * (i+1)
in out
|
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
| #Quackery | Quackery | [ 0 1 rot times [ tuck + ] drop ] is fibo ( n --> n )
100 fibo echo |
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
| #FutureBasic | FutureBasic | window 1, @"Factorial", ( 0, 0, 300, 550 )
local fn factorialIterative( n as long ) as double
double f
long i
if ( n > 1 )
f = 1
for i = 2 to n
f = f * i
next
else
f = 1
end if
end fn = f
local fn factorialRecursive( n as long ) as double
double f
if ( n < 2 )
f = 1
else
f = n * fn factorialRecursive( n -1 )
end if
end fn = f
long i
for i = 0 to 12
print "Iterative:"; using "####"; i; " = "; fn factorialIterative( i )
print "Recursive:"; using "####"; i; " = "; fn factorialRecursive( i )
print
next
HandleEvents |
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
| #R | R | fib=function(n,x=c(0,1)) {
if (abs(n)>1) for (i in seq(abs(n)-1)) x=c(x[2],sum(x))
if (n<0) return(x[2]*(-1)^(abs(n)-1)) else if (n) return(x[2]) else return(0)
}
sapply(seq(-31,31),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
| #Gambas | Gambas |
' Task: Factorial
' Language: Gambas
' Author: Sinuhe Masan (2019)
' Function factorial iterative
Function factorial_iter(num As Integer) As Long
Dim fact As Long
Dim i As Integer
fact = 1
If num > 1 Then
For i = 2 To num
fact = fact * i
Next
Endif
Return fact
End
' Function factorial recursive
Function factorial_rec(num As Integer) As Long
If num <= 1 Then
Return 1
Else
Return num * factorial_rec(num - 1)
Endif
End
Public Sub Main()
Print factorial_iter(6)
Print factorial_rec(7)
End
|
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
| #Ra | Ra |
class FibonacciSequence
**Prints the nth fibonacci number**
on start
args := program arguments
if args empty
print .fibonacci(8)
else
try
print .fibonacci(integer.parse(args[0]))
catch FormatException
print to Console.error made !, "Input must be an integer"
exit program with error code
catch OverflowException
print to Console.error made !, "Number too large"
exit program with error code
define fibonacci(n as integer) as integer is shared
**Returns the nth fibonacci number**
test
assert fibonacci(0) = 0
assert fibonacci(1) = 1
assert fibonacci(2) = 1
assert fibonacci(3) = 2
assert fibonacci(4) = 3
assert fibonacci(5) = 5
assert fibonacci(6) = 8
assert fibonacci(7) = 13
assert fibonacci(8) = 21
body
a, b := 0, 1
for n
a, b := b, a + b
return 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
| #GAP | GAP | # Built-in
Factorial(5);
# An implementation
fact := n -> Product([1 .. n]); |
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
| #Racket | Racket |
(define (fib n)
(let loop ((cnt 0) (a 0) (b 1))
(if (= n cnt)
a
(loop (+ cnt 1) b (+ a b)))))
|
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
| #Genyris | Genyris | def factorial (n)
if (< n 2) 1
* n
factorial (- n 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
| #Raku | Raku | constant @fib = 0, 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
| #GML | GML | n = argument0
j = 1
for(i = 1; i <= n; i += 1)
j *= i
return j |
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
| #RASEL | RASEL | 1&-:?v2\:2\01\--2\
>$.@ |
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
| #gnuplot | gnuplot | set xrange [0:4.95]
set key left
plot int(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
| #Red | Red | palindrome: [fn: fn-1 + fn-1: fn]
fibonacci: func [n][
fn-1: 0
fn: 1
loop n palindrome
] |
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
| #Go | Go | package main
import (
"fmt"
"math/big"
)
func main() {
fmt.Println(factorial(800))
}
func factorial(n int64) *big.Int {
if n < 0 {
return nil
}
r := big.NewInt(1)
var f big.Int
for i := int64(2); i <= n; i++ {
r.Mul(r, f.SetInt64(i))
}
return r
} |
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
Fn = Fn+2 - Fn+1, if n<0
support for negative n in the solution is optional.
Related tasks
Fibonacci n-step number sequences
Leonardo numbers
References
Wikipedia, Fibonacci number
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #Relation | Relation |
function fibonacci (n)
if n < 2
set result = n
else
set f0 = 0
set f1 = 1
set k = 2
while k <= n
set result = f0 + f1
set f0 = f1
set f1 = result
set k = k + 1
end while
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
| #Golfscript | Golfscript | {.!{1}{,{)}%{*}*}if}:fact;
5fact puts # test |
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
| #Retro | Retro | : fib ( n-m ) dup [ 0 = ] [ 1 = ] bi or if; [ 1- fib ] sip [ 2 - fib ] do + ; |
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
| #Gridscript | Gridscript |
#FACTORIAL.
@width 14
@height 8
(1,3):START
(7,1):CHECKPOINT 0
(3,3):INPUT INT TO n
(5,3):STORE n
(7,3):GO EAST
(9,3):DECREMENT n
(11,3):SWITCH n
(11,5):MULTIPLY BY n
(11,7):GOTO 0
(13,3):PRINT
|
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
| #REXX | REXX | /*REXX program calculates the Nth Fibonacci number, N can be zero or negative. */
numeric digits 210000 /*be able to handle ginormous numbers. */
parse arg x y . /*allow a single number or a range. */
if x=='' | x=="," then do; x=-40; y=+40; end /*No input? Then use range -40 ──► +40*/
if y=='' | y=="," then y=x /*if only one number, display fib(X).*/
w= max(length(x), length(y) ) /*W: used for making formatted output.*/
fw= 10 /*Minimum maximum width. Sounds ka─razy*/
do j=x to y; q= fib(j) /*process all of the Fibonacci requests*/
L= length(q) /*obtain the length (decimal digs) of Q*/
fw= max(fw, L) /*fib number length, or the max so far.*/
say 'Fibonacci('right(j,w)") = " right(q,fw) /*right justify Q.*/
if L>10 then say 'Fibonacci('right(j, w)") has a length of" L
end /*j*/ /* [↑] list a Fib. sequence of x──►y */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
fib: procedure; parse arg n; an= abs(n) /*use │n│ (the absolute value of N).*/
a= 0; b= 1; if an<2 then return an /*handle two special cases: zero & one.*/
/* [↓] this method is non─recursive. */
do k=2 to an; $= a+b; a= b; b= $ /*sum the numbers up to │n│ */
end /*k*/ /* [↑] (only positive Fibs nums used).*/
/* [↓] an//2 [same as] (an//2==1).*/
if n>0 | an//2 then return $ /*Positive or even? Then return sum. */
return -$ /*Negative and odd? Return negative sum*/ |
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
| #Groovy | Groovy | def rFact
rFact = { (it > 1) ? it * rFact(it - 1) : 1 as BigInteger } |
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
| #Ring | Ring |
give n
x = fib(n)
see n + " Fibonacci is : " + x
func fib nr if nr = 0 return 0 ok
if nr = 1 return 1 ok
if nr > 1 return fib(nr-1) + fib(nr-2) ok
|
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
| #Haskell | Haskell | factorial n = product [1..n] |
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
| #Rockstar | Rockstar |
Fibonacci takes Number
FNow is 0
FNext is 1
While FNow is less than Number
Say FNow
Put FNow into Temp
Put FNow into FNext
Put FNext plus Temp into FNext
Say Fibonacci taking 1000 (prints out highest number in Fibonacci sequence less than 1000)
|
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
| #Haxe | Haxe | static function factorial(n:Int):Int {
var result = 1;
while (1<n)
result *= n--;
return result;
} |
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
| #Ruby | Ruby | def fib(n)
if n < 2
n
else
prev, fib = 0, 1
(n-1).times do
prev, fib = fib, fib + prev
end
fib
end
end
p (0..10).map { |i| fib(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
| #hexiscript | hexiscript | fun fac n
let acc 1
while n > 0
let acc (acc * n--)
endwhile
return acc
endfun |
http://rosettacode.org/wiki/Euler%27s_constant_0.5772... | Euler's constant 0.5772... |
Task.
Compute the Euler constant 0.5772...
Discovered by Leonhard Euler around 1730, it is the most ubiquitous mathematical constant after pi and e, but appears more arcane than these.
Denoted gamma (γ), it measures the amount by which the partial sums of the harmonic series (the simplest diverging series) differ from the logarithmic function (its approximating integral): lim n → ∞ (1 + 1/2 + 1/3 + … + 1/n − log(n)).
The definition of γ converges too slowly to be numerically useful, but in 1735 Euler himself applied his recently discovered summation formula to compute ‘the notable number’ accurate to 15 places. For a single-precision implementation this is still the most economic algorithm.
In 1961, the young Donald Knuth used Euler's method to evaluate γ to 1271 places. Knuth found that the computation of the Bernoulli numbers required in the Euler-Maclaurin formula was the most time-consuming part of the procedure.
The next year Dura Sweeney computed 3566 places, using a formula based on the expansion of the exponential integral which didn't need Bernoulli numbers. It's a bit-hungry method though: 2d digits of working precision obtain d correct places only.
This was remedied in 1988 by David Bailey; meanwhile Richard Brent and Ed McMillan had published an even more efficient algorithm based on Bessel function identities and found 30100 places in 20 hours time.
Nowadays the old records have far been exceeded: over 6·1011 decimal places are already known. These massive computations suggest that γ is neither rational nor algebraic, but this is yet to be proven.
References.
[1]
Gourdon and Sebah, The Euler constant γ. (for all formulas)
[2]
Euler's original journal article translated from the latin (p. 9)
| #Burlesque | Burlesque | 33ro{JroJJJL[\/JL[\/nr\/{-1}\/.*FLJL[ro?^?*\/JL[{2}\/.*FL\/?^?*\/{1.+}m[J{lg}m[\/?/?*++\/1 3.0./\/?^.*}m[++-2 3 2lg.*./.*2lg2./.+ |
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
| #Run_BASIC | Run BASIC | for i = 0 to 10
print i;" ";fibR(i);" ";fibI(i)
next i
end
function fibR(n)
if n < 2 then fibR = n else fibR = fibR(n-1) + fibR(n-2)
end function
function fibI(n)
b = 1
for i = 1 to n
t = a + b
a = b
b = t
next i
fibI = a
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
| #HicEst | HicEst | WRITE(Clipboard) factorial(6) ! pasted: 720
FUNCTION factorial(n)
factorial = 1
DO i = 2, n
factorial = factorial * i
ENDDO
END |
http://rosettacode.org/wiki/Euler%27s_constant_0.5772... | Euler's constant 0.5772... |
Task.
Compute the Euler constant 0.5772...
Discovered by Leonhard Euler around 1730, it is the most ubiquitous mathematical constant after pi and e, but appears more arcane than these.
Denoted gamma (γ), it measures the amount by which the partial sums of the harmonic series (the simplest diverging series) differ from the logarithmic function (its approximating integral): lim n → ∞ (1 + 1/2 + 1/3 + … + 1/n − log(n)).
The definition of γ converges too slowly to be numerically useful, but in 1735 Euler himself applied his recently discovered summation formula to compute ‘the notable number’ accurate to 15 places. For a single-precision implementation this is still the most economic algorithm.
In 1961, the young Donald Knuth used Euler's method to evaluate γ to 1271 places. Knuth found that the computation of the Bernoulli numbers required in the Euler-Maclaurin formula was the most time-consuming part of the procedure.
The next year Dura Sweeney computed 3566 places, using a formula based on the expansion of the exponential integral which didn't need Bernoulli numbers. It's a bit-hungry method though: 2d digits of working precision obtain d correct places only.
This was remedied in 1988 by David Bailey; meanwhile Richard Brent and Ed McMillan had published an even more efficient algorithm based on Bessel function identities and found 30100 places in 20 hours time.
Nowadays the old records have far been exceeded: over 6·1011 decimal places are already known. These massive computations suggest that γ is neither rational nor algebraic, but this is yet to be proven.
References.
[1]
Gourdon and Sebah, The Euler constant γ. (for all formulas)
[2]
Euler's original journal article translated from the latin (p. 9)
| #C | C | /*********************************************
Subject: Comparing five methods for
computing Euler's constant 0.5772...
tested : tcc-0.9.27
--------------------------------------------*/
#include <math.h>
#include <stdio.h>
#define eps 1e-6
int main(void) {
double a, b, h, n2, r, u, v;
int k, k2, m, n;
printf("From the definition, err. 3e-10\n");
n = 400;
h = 1;
for (k = 2; k <= n; k++) {
h += 1.0 / k;
}
//faster convergence: Negoi, 1997
a = log(n +.5 + 1.0 / (24*n));
printf("Hn %.16f\n", h);
printf("gamma %.16f\nk = %d\n\n", h - a, n);
printf("Sweeney, 1963, err. idem\n");
n = 21;
double s[] = {0, n};
r = n;
k = 1;
do {
k += 1;
r *= (double) n / k;
s[k & 1] += r / k;
} while (r > eps);
printf("gamma %.16f\nk = %d\n\n", s[1] - s[0] - log(n), k);
printf("Bailey, 1988\n");
n = 5;
a = 1;
h = 1;
n2 = pow(2,n);
r = 1;
k = 1;
do {
k += 1;
r *= n2 / k;
h += 1.0 / k;
b = a; a += r * h;
} while (fabs(b - a) > eps);
a *= n2 / exp(n2);
printf("gamma %.16f\nk = %d\n\n", a - n * log(2), k);
printf("Brent-McMillan, 1980\n");
n = 13;
a = -log(n);
b = 1;
u = a;
v = b;
n2 = n * n;
k2 = 0;
k = 0;
do {
k2 += 2*k + 1;
k += 1;
a *= n2 / k;
b *= n2 / k2;
a = (a + b) / k;
u += a;
v += b;
} while (fabs(a) > eps);
printf("gamma %.16f\nk = %d\n\n", u / v, k);
printf("How Euler did it in 1735\n");
//Bernoulli numbers with even indices
double B2[] = {1.0,1.0/6,-1.0/30,1.0/42,-1.0/30,\
5.0/66,-691.0/2730,7.0/6,-3617.0/510,43867.0/798};
m = 7;
if (m > 9) return(0);
n = 10;
//n-th harmonic number
h = 1;
for (k = 2; k <= n; k++) {
h += 1.0 / k;
}
printf("Hn %.16f\n", h);
h -= log(n);
printf(" -ln %.16f\n", h);
//expansion C = -digamma(1)
a = -1.0 / (2*n);
n2 = n * n;
r = 1;
for (k = 1; k <= m; k++) {
r *= n2;
a += B2[k] / (2*k * r);
}
printf("err %.16f\ngamma %.16f\nk = %d", a, h + a, n + m);
printf("\n\nC = 0.57721566490153286...\n");
} |
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
| #Rust | Rust | fn main() {
let mut prev = 0;
// Rust needs this type hint for the checked_add method
let mut curr = 1usize;
while let Some(n) = curr.checked_add(prev) {
prev = curr;
curr = n;
println!("{}", 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
| #HolyC | HolyC | U64 Factorial(U64 n) {
U64 i, result = 1;
for (i = 1; i <= n; ++i)
result *= i;
return result;
}
Print("1: %d\n", Factorial(1));
Print("10: %d\n", Factorial(10)); |
http://rosettacode.org/wiki/Euler%27s_constant_0.5772... | Euler's constant 0.5772... |
Task.
Compute the Euler constant 0.5772...
Discovered by Leonhard Euler around 1730, it is the most ubiquitous mathematical constant after pi and e, but appears more arcane than these.
Denoted gamma (γ), it measures the amount by which the partial sums of the harmonic series (the simplest diverging series) differ from the logarithmic function (its approximating integral): lim n → ∞ (1 + 1/2 + 1/3 + … + 1/n − log(n)).
The definition of γ converges too slowly to be numerically useful, but in 1735 Euler himself applied his recently discovered summation formula to compute ‘the notable number’ accurate to 15 places. For a single-precision implementation this is still the most economic algorithm.
In 1961, the young Donald Knuth used Euler's method to evaluate γ to 1271 places. Knuth found that the computation of the Bernoulli numbers required in the Euler-Maclaurin formula was the most time-consuming part of the procedure.
The next year Dura Sweeney computed 3566 places, using a formula based on the expansion of the exponential integral which didn't need Bernoulli numbers. It's a bit-hungry method though: 2d digits of working precision obtain d correct places only.
This was remedied in 1988 by David Bailey; meanwhile Richard Brent and Ed McMillan had published an even more efficient algorithm based on Bessel function identities and found 30100 places in 20 hours time.
Nowadays the old records have far been exceeded: over 6·1011 decimal places are already known. These massive computations suggest that γ is neither rational nor algebraic, but this is yet to be proven.
References.
[1]
Gourdon and Sebah, The Euler constant γ. (for all formulas)
[2]
Euler's original journal article translated from the latin (p. 9)
| #FreeBASIC | FreeBASIC | '**********************************************
'Subject: Comparing five methods for
' computing Euler's constant 0.5772...
'tested : FreeBasic 1.08.1
'----------------------------------------------
const eps = 1e-6
dim as double a, b, h, n2, r, u, v
dim as integer k, k2, m, n
? "From the definition, err. 3e-10"
n = 400
h = 1
for k = 2 to n
h += 1 / k
next k
'faster convergence: Negoi, 1997
a = log(n +.5 + 1 / (24*n))
? "Hn "; h
? "gamma"; h - a; !"\nk ="; n
?
? "Sweeney, 1963, err. idem"
n = 21
dim as double s(1) = {0, n}
r = n
k = 1
do
k += 1
r *= n / k
s(k and 1) += r / k
loop until r < eps
? "gamma"; s(1) - s(0) - log(n); !"\nk ="; k
?
? "Bailey, 1988"
n = 5
a = 1
h = 1
n2 = 2^n
r = 1
k = 1
do
k += 1
r *= n2 / k
h += 1 / k
b = a: a += r * h
loop until abs(b - a) < eps
a *= n2 / exp(n2)
? "gamma"; a - n * log(2); !"\nk ="; k
?
? "Brent-McMillan, 1980"
n = 13
a = -log(n)
b = 1
u = a
v = b
n2 = n * n
k2 = 0
k = 0
do
k2 += 2*k + 1
k += 1
a *= n2 / k
b *= n2 / k2
a = (a + b) / k
u += a
v += b
loop until abs(a) < eps
? "gamma"; u / v; !"\nk ="; k
?
? "How Euler did it in 1735"
'Bernoulli numbers with even indices
dim as double B2(9) = {1,1/6,-1/30,1/42,_
-1/30,5/66,-691/2730,7/6,-3617/510,43867/798}
m = 7
if m > 9 then end
n = 10
'n-th harmonic number
h = 1
for k = 2 to n
h += 1 / k
next k
? "Hn "; h
h -= log(n)
? " -ln"; h
'expansion C = -digamma(1)
a = -1 / (2*n)
n2 = n * n
r = 1
for k = 1 to m
r *= n2
a += B2(k) / (2*k * r)
next k
? "err "; a; !"\ngamma"; h + a; !"\nk ="; n + m
?
? "C = 0.57721566490153286..."
end |
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
| #S-BASIC | S-BASIC |
rem - iterative function to calculate nth fibonacci number
function fibonacci(n = integer) = integer
var f, i, p1, p2 = integer
p1 = 0
p2 = 1
if n = 0 then
f = 0
else
for i = 1 to n
f = p1 + p2
p2 = p1
p1 = f
next i
end = f
rem - exercise the function
var i = integer
for i = 0 to 10
print fibonacci(i);
next i
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
| #Hy | Hy | (defn ! [n]
(reduce *
(range 1 (inc n))
1))
(print (! 6)) ; 720
(print (! 0)) ; 1 |
http://rosettacode.org/wiki/Euler%27s_constant_0.5772... | Euler's constant 0.5772... |
Task.
Compute the Euler constant 0.5772...
Discovered by Leonhard Euler around 1730, it is the most ubiquitous mathematical constant after pi and e, but appears more arcane than these.
Denoted gamma (γ), it measures the amount by which the partial sums of the harmonic series (the simplest diverging series) differ from the logarithmic function (its approximating integral): lim n → ∞ (1 + 1/2 + 1/3 + … + 1/n − log(n)).
The definition of γ converges too slowly to be numerically useful, but in 1735 Euler himself applied his recently discovered summation formula to compute ‘the notable number’ accurate to 15 places. For a single-precision implementation this is still the most economic algorithm.
In 1961, the young Donald Knuth used Euler's method to evaluate γ to 1271 places. Knuth found that the computation of the Bernoulli numbers required in the Euler-Maclaurin formula was the most time-consuming part of the procedure.
The next year Dura Sweeney computed 3566 places, using a formula based on the expansion of the exponential integral which didn't need Bernoulli numbers. It's a bit-hungry method though: 2d digits of working precision obtain d correct places only.
This was remedied in 1988 by David Bailey; meanwhile Richard Brent and Ed McMillan had published an even more efficient algorithm based on Bessel function identities and found 30100 places in 20 hours time.
Nowadays the old records have far been exceeded: over 6·1011 decimal places are already known. These massive computations suggest that γ is neither rational nor algebraic, but this is yet to be proven.
References.
[1]
Gourdon and Sebah, The Euler constant γ. (for all formulas)
[2]
Euler's original journal article translated from the latin (p. 9)
| #jq | jq | # Bailey, 1988
def bailey($n; $eps):
pow(2; $n) as $n2
| {a :1, b: 0, h: 1, r: 1, k: 1}
| until( (.b - .a)|fabs <= $eps;
.k += 1
| .r *= ($n2 / .k)
| .h += (1.0 / .k)
| .b = .a
| .a += (.r * .h) )
| (.a * $n2 / ($n2|exp) ) - ($n * (2|log)) ; |
http://rosettacode.org/wiki/Euler%27s_constant_0.5772... | Euler's constant 0.5772... |
Task.
Compute the Euler constant 0.5772...
Discovered by Leonhard Euler around 1730, it is the most ubiquitous mathematical constant after pi and e, but appears more arcane than these.
Denoted gamma (γ), it measures the amount by which the partial sums of the harmonic series (the simplest diverging series) differ from the logarithmic function (its approximating integral): lim n → ∞ (1 + 1/2 + 1/3 + … + 1/n − log(n)).
The definition of γ converges too slowly to be numerically useful, but in 1735 Euler himself applied his recently discovered summation formula to compute ‘the notable number’ accurate to 15 places. For a single-precision implementation this is still the most economic algorithm.
In 1961, the young Donald Knuth used Euler's method to evaluate γ to 1271 places. Knuth found that the computation of the Bernoulli numbers required in the Euler-Maclaurin formula was the most time-consuming part of the procedure.
The next year Dura Sweeney computed 3566 places, using a formula based on the expansion of the exponential integral which didn't need Bernoulli numbers. It's a bit-hungry method though: 2d digits of working precision obtain d correct places only.
This was remedied in 1988 by David Bailey; meanwhile Richard Brent and Ed McMillan had published an even more efficient algorithm based on Bessel function identities and found 30100 places in 20 hours time.
Nowadays the old records have far been exceeded: over 6·1011 decimal places are already known. These massive computations suggest that γ is neither rational nor algebraic, but this is yet to be proven.
References.
[1]
Gourdon and Sebah, The Euler constant γ. (for all formulas)
[2]
Euler's original journal article translated from the latin (p. 9)
| #Julia | Julia | display(MathConstants.γ) # γ = 0.5772156649015...
|
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
| #SAS | SAS | data fib;
a=0;
b=1;
do n=0 to 20;
f=a;
output;
a=b;
b=f+a;
end;
keep n f;
run; |
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
| #i | i | concept factorial(n) {
return n!
}
software {
print(factorial(-23))
print(factorial(0))
print(factorial(1))
print(factorial(2))
print(factorial(3))
print(factorial(22))
}
|
http://rosettacode.org/wiki/Euler%27s_constant_0.5772... | Euler's constant 0.5772... |
Task.
Compute the Euler constant 0.5772...
Discovered by Leonhard Euler around 1730, it is the most ubiquitous mathematical constant after pi and e, but appears more arcane than these.
Denoted gamma (γ), it measures the amount by which the partial sums of the harmonic series (the simplest diverging series) differ from the logarithmic function (its approximating integral): lim n → ∞ (1 + 1/2 + 1/3 + … + 1/n − log(n)).
The definition of γ converges too slowly to be numerically useful, but in 1735 Euler himself applied his recently discovered summation formula to compute ‘the notable number’ accurate to 15 places. For a single-precision implementation this is still the most economic algorithm.
In 1961, the young Donald Knuth used Euler's method to evaluate γ to 1271 places. Knuth found that the computation of the Bernoulli numbers required in the Euler-Maclaurin formula was the most time-consuming part of the procedure.
The next year Dura Sweeney computed 3566 places, using a formula based on the expansion of the exponential integral which didn't need Bernoulli numbers. It's a bit-hungry method though: 2d digits of working precision obtain d correct places only.
This was remedied in 1988 by David Bailey; meanwhile Richard Brent and Ed McMillan had published an even more efficient algorithm based on Bessel function identities and found 30100 places in 20 hours time.
Nowadays the old records have far been exceeded: over 6·1011 decimal places are already known. These massive computations suggest that γ is neither rational nor algebraic, but this is yet to be proven.
References.
[1]
Gourdon and Sebah, The Euler constant γ. (for all formulas)
[2]
Euler's original journal article translated from the latin (p. 9)
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | N[EulerGamma, 1000] |
http://rosettacode.org/wiki/Euler%27s_constant_0.5772... | Euler's constant 0.5772... |
Task.
Compute the Euler constant 0.5772...
Discovered by Leonhard Euler around 1730, it is the most ubiquitous mathematical constant after pi and e, but appears more arcane than these.
Denoted gamma (γ), it measures the amount by which the partial sums of the harmonic series (the simplest diverging series) differ from the logarithmic function (its approximating integral): lim n → ∞ (1 + 1/2 + 1/3 + … + 1/n − log(n)).
The definition of γ converges too slowly to be numerically useful, but in 1735 Euler himself applied his recently discovered summation formula to compute ‘the notable number’ accurate to 15 places. For a single-precision implementation this is still the most economic algorithm.
In 1961, the young Donald Knuth used Euler's method to evaluate γ to 1271 places. Knuth found that the computation of the Bernoulli numbers required in the Euler-Maclaurin formula was the most time-consuming part of the procedure.
The next year Dura Sweeney computed 3566 places, using a formula based on the expansion of the exponential integral which didn't need Bernoulli numbers. It's a bit-hungry method though: 2d digits of working precision obtain d correct places only.
This was remedied in 1988 by David Bailey; meanwhile Richard Brent and Ed McMillan had published an even more efficient algorithm based on Bessel function identities and found 30100 places in 20 hours time.
Nowadays the old records have far been exceeded: over 6·1011 decimal places are already known. These massive computations suggest that γ is neither rational nor algebraic, but this is yet to be proven.
References.
[1]
Gourdon and Sebah, The Euler constant γ. (for all formulas)
[2]
Euler's original journal article translated from the latin (p. 9)
| #Nim | Nim | import std/math
const n = 1e6
var result = 1.0
for i in 2..int(n):
result += 1/i
echo result - ln(n)
|
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
| #Sather | Sather | class MAIN is
-- RECURSIVE --
fibo(n :INTI):INTI
pre n >= 0
is
if n < 2.inti then return n; end;
return fibo(n - 2.inti) + fibo(n - 1.inti);
end;
-- ITERATIVE --
fibo_iter(n :INTI):INTI
pre n >= 0
is
n3w :INTI;
if n < 2.inti then return n; end;
last ::= 0.inti; this ::= 1.inti;
loop (n - 1.inti).times!;
n3w := last + this;
last := this;
this := n3w;
end;
return this;
end;
main is
loop i ::= 0.upto!(16);
#OUT + fibo(i.inti) + " ";
#OUT + fibo_iter(i.inti) + "\n";
end;
end;
end; |
http://rosettacode.org/wiki/Factorial | Factorial | Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a number.
Solutions can be iterative or recursive.
Support for trapping negative n errors is optional.
Related task
Primorial numbers
| #Icon_and_Unicon | Icon and Unicon | procedure factorial(n)
n := integer(n) | runerr(101, n)
if n < 0 then fail
return if n = 0 then 1 else n*factorial(n-1)
end |
http://rosettacode.org/wiki/Euler%27s_constant_0.5772... | Euler's constant 0.5772... |
Task.
Compute the Euler constant 0.5772...
Discovered by Leonhard Euler around 1730, it is the most ubiquitous mathematical constant after pi and e, but appears more arcane than these.
Denoted gamma (γ), it measures the amount by which the partial sums of the harmonic series (the simplest diverging series) differ from the logarithmic function (its approximating integral): lim n → ∞ (1 + 1/2 + 1/3 + … + 1/n − log(n)).
The definition of γ converges too slowly to be numerically useful, but in 1735 Euler himself applied his recently discovered summation formula to compute ‘the notable number’ accurate to 15 places. For a single-precision implementation this is still the most economic algorithm.
In 1961, the young Donald Knuth used Euler's method to evaluate γ to 1271 places. Knuth found that the computation of the Bernoulli numbers required in the Euler-Maclaurin formula was the most time-consuming part of the procedure.
The next year Dura Sweeney computed 3566 places, using a formula based on the expansion of the exponential integral which didn't need Bernoulli numbers. It's a bit-hungry method though: 2d digits of working precision obtain d correct places only.
This was remedied in 1988 by David Bailey; meanwhile Richard Brent and Ed McMillan had published an even more efficient algorithm based on Bessel function identities and found 30100 places in 20 hours time.
Nowadays the old records have far been exceeded: over 6·1011 decimal places are already known. These massive computations suggest that γ is neither rational nor algebraic, but this is yet to be proven.
References.
[1]
Gourdon and Sebah, The Euler constant γ. (for all formulas)
[2]
Euler's original journal article translated from the latin (p. 9)
| #PARI.2FGP | PARI/GP | \l "euler_const.log"
\p 100
print("gamma ", Euler);
\q |
http://rosettacode.org/wiki/Euler%27s_constant_0.5772... | Euler's constant 0.5772... |
Task.
Compute the Euler constant 0.5772...
Discovered by Leonhard Euler around 1730, it is the most ubiquitous mathematical constant after pi and e, but appears more arcane than these.
Denoted gamma (γ), it measures the amount by which the partial sums of the harmonic series (the simplest diverging series) differ from the logarithmic function (its approximating integral): lim n → ∞ (1 + 1/2 + 1/3 + … + 1/n − log(n)).
The definition of γ converges too slowly to be numerically useful, but in 1735 Euler himself applied his recently discovered summation formula to compute ‘the notable number’ accurate to 15 places. For a single-precision implementation this is still the most economic algorithm.
In 1961, the young Donald Knuth used Euler's method to evaluate γ to 1271 places. Knuth found that the computation of the Bernoulli numbers required in the Euler-Maclaurin formula was the most time-consuming part of the procedure.
The next year Dura Sweeney computed 3566 places, using a formula based on the expansion of the exponential integral which didn't need Bernoulli numbers. It's a bit-hungry method though: 2d digits of working precision obtain d correct places only.
This was remedied in 1988 by David Bailey; meanwhile Richard Brent and Ed McMillan had published an even more efficient algorithm based on Bessel function identities and found 30100 places in 20 hours time.
Nowadays the old records have far been exceeded: over 6·1011 decimal places are already known. These massive computations suggest that γ is neither rational nor algebraic, but this is yet to be proven.
References.
[1]
Gourdon and Sebah, The Euler constant γ. (for all formulas)
[2]
Euler's original journal article translated from the latin (p. 9)
| #Perl | Perl | #!/usr/bin/perl
use strict; # https://en.wikipedia.org/wiki/Euler%27s_constant
use warnings;
use List::Util qw( sum );
print sum( map 1 / $_, 1 .. 1e6) - log 1e6, "\n"; |
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
| #Scala | Scala | def fib(i: Int): Int = i match {
case 0 => 0
case 1 => 1
case _ => fib(i - 1) + fib(i - 2)
} |
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
| #IDL | IDL | function fact,n
return, product(lindgen(n)+1)
end |
http://rosettacode.org/wiki/Euler%27s_constant_0.5772... | Euler's constant 0.5772... |
Task.
Compute the Euler constant 0.5772...
Discovered by Leonhard Euler around 1730, it is the most ubiquitous mathematical constant after pi and e, but appears more arcane than these.
Denoted gamma (γ), it measures the amount by which the partial sums of the harmonic series (the simplest diverging series) differ from the logarithmic function (its approximating integral): lim n → ∞ (1 + 1/2 + 1/3 + … + 1/n − log(n)).
The definition of γ converges too slowly to be numerically useful, but in 1735 Euler himself applied his recently discovered summation formula to compute ‘the notable number’ accurate to 15 places. For a single-precision implementation this is still the most economic algorithm.
In 1961, the young Donald Knuth used Euler's method to evaluate γ to 1271 places. Knuth found that the computation of the Bernoulli numbers required in the Euler-Maclaurin formula was the most time-consuming part of the procedure.
The next year Dura Sweeney computed 3566 places, using a formula based on the expansion of the exponential integral which didn't need Bernoulli numbers. It's a bit-hungry method though: 2d digits of working precision obtain d correct places only.
This was remedied in 1988 by David Bailey; meanwhile Richard Brent and Ed McMillan had published an even more efficient algorithm based on Bessel function identities and found 30100 places in 20 hours time.
Nowadays the old records have far been exceeded: over 6·1011 decimal places are already known. These massive computations suggest that γ is neither rational nor algebraic, but this is yet to be proven.
References.
[1]
Gourdon and Sebah, The Euler constant γ. (for all formulas)
[2]
Euler's original journal article translated from the latin (p. 9)
| #Phix | Phix | -- demo\rosetta\Eulers_constant.exw
with javascript_semantics
constant C = sum(sq_div(1,tagset(1e6)))-log(1e6)
printf(1,"gamma %.12f (max 12d.p. of accuracy)\n",C)
|
http://rosettacode.org/wiki/Euler%27s_constant_0.5772... | Euler's constant 0.5772... |
Task.
Compute the Euler constant 0.5772...
Discovered by Leonhard Euler around 1730, it is the most ubiquitous mathematical constant after pi and e, but appears more arcane than these.
Denoted gamma (γ), it measures the amount by which the partial sums of the harmonic series (the simplest diverging series) differ from the logarithmic function (its approximating integral): lim n → ∞ (1 + 1/2 + 1/3 + … + 1/n − log(n)).
The definition of γ converges too slowly to be numerically useful, but in 1735 Euler himself applied his recently discovered summation formula to compute ‘the notable number’ accurate to 15 places. For a single-precision implementation this is still the most economic algorithm.
In 1961, the young Donald Knuth used Euler's method to evaluate γ to 1271 places. Knuth found that the computation of the Bernoulli numbers required in the Euler-Maclaurin formula was the most time-consuming part of the procedure.
The next year Dura Sweeney computed 3566 places, using a formula based on the expansion of the exponential integral which didn't need Bernoulli numbers. It's a bit-hungry method though: 2d digits of working precision obtain d correct places only.
This was remedied in 1988 by David Bailey; meanwhile Richard Brent and Ed McMillan had published an even more efficient algorithm based on Bessel function identities and found 30100 places in 20 hours time.
Nowadays the old records have far been exceeded: over 6·1011 decimal places are already known. These massive computations suggest that γ is neither rational nor algebraic, but this is yet to be proven.
References.
[1]
Gourdon and Sebah, The Euler constant γ. (for all formulas)
[2]
Euler's original journal article translated from the latin (p. 9)
| #Picat | Picat | main =>
Gamma = 0.57721566490153286060651209008240,
println(Gamma),
foreach(N in 1..8)
G = e(10**N),
println([n=N,g=G,diff=G-Gamma])
end.
e(N) = [1.0/I : I in 1..N].sum-log(N). |
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
| #Scheme | Scheme | (define (fib-iter n)
(do ((num 2 (+ num 1))
(fib-prev 1 fib)
(fib 1 (+ fib fib-prev)))
((>= num n) 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
| #Inform_6 | Inform 6 | [ factorial n;
if(n == 0)
return 1;
else
return n * factorial(n - 1);
]; |
http://rosettacode.org/wiki/Euler%27s_constant_0.5772... | Euler's constant 0.5772... |
Task.
Compute the Euler constant 0.5772...
Discovered by Leonhard Euler around 1730, it is the most ubiquitous mathematical constant after pi and e, but appears more arcane than these.
Denoted gamma (γ), it measures the amount by which the partial sums of the harmonic series (the simplest diverging series) differ from the logarithmic function (its approximating integral): lim n → ∞ (1 + 1/2 + 1/3 + … + 1/n − log(n)).
The definition of γ converges too slowly to be numerically useful, but in 1735 Euler himself applied his recently discovered summation formula to compute ‘the notable number’ accurate to 15 places. For a single-precision implementation this is still the most economic algorithm.
In 1961, the young Donald Knuth used Euler's method to evaluate γ to 1271 places. Knuth found that the computation of the Bernoulli numbers required in the Euler-Maclaurin formula was the most time-consuming part of the procedure.
The next year Dura Sweeney computed 3566 places, using a formula based on the expansion of the exponential integral which didn't need Bernoulli numbers. It's a bit-hungry method though: 2d digits of working precision obtain d correct places only.
This was remedied in 1988 by David Bailey; meanwhile Richard Brent and Ed McMillan had published an even more efficient algorithm based on Bessel function identities and found 30100 places in 20 hours time.
Nowadays the old records have far been exceeded: over 6·1011 decimal places are already known. These massive computations suggest that γ is neither rational nor algebraic, but this is yet to be proven.
References.
[1]
Gourdon and Sebah, The Euler constant γ. (for all formulas)
[2]
Euler's original journal article translated from the latin (p. 9)
| #Processing | Processing |
/*********************************************
Subject: Comparing five methods for
computing Euler's constant 0.5772...
// https://rosettacode.org/wiki/Euler%27s_constant_0.5772...
--------------------------------------------*/
double a, b, h, n2, r, u, v;
float floatA, floatB, floatN2;
int k, k2, m, n;
double eps = 1e-6;
void setup() {
size(100, 100);
noLoop();
}
void draw() {
println("From the definition, err. 3e-10\n");
n = 400;
h = 1;
for (int k = 2; k <= n; k++) {
h += 1.0 / k;
}
//faster convergence: Negoi, 1997
a = log(n +.5 + 1.0 / (24*n));
println("Hn ", h);
println("gamma ", h - a);
println("k = ", n);
println("");
println("Sweeney, 1963, err. idem");
n = 21;
double s[] = {0, n};
r = n;
k = 1;
while (r > eps) {
k ++;
r *= (double) n / k;
s[k & 1] = s[k & 1] + r / k;
}
// println("gamma %.16f\nk = %d\n\n", s[1] - s[0] - log(n), k);
println("Hn ", h);
println("gamma ", s[1] - s[0] - log(n));
println("k = ", k);
println("");
println("Bailey, 1988");
n = 5;
floatA = 1;
h = 1;
floatN2 = pow(2, n);
r = 1;
k = 1;
while (abs(floatB - floatA) > eps) {
k += 1;
r *= floatN2 / k;
h += 1.0 / k;
floatB = floatA;
floatA += r * h;
}
floatA *= floatN2 / exp(floatN2);
println("gamma ", floatA - n * log(2));
println("k = ", k);
println("");
println("Brent-McMillan, 1980");
n = 13;
floatA = -log(n);
floatB = 1;
u = a;
v = b;
n2 = n * n;
k2 = 0;
k = 0;
while (abs(floatA) > eps) {
k2 += 2*k + 1;
k += 1;
floatA *= n2 / k;
floatB *= n2 / k2;
floatA = (floatA + floatB) / k;
u += floatA;
v += floatB;
}
println("gamma ", u / v);
println("k ", k);
println("How Euler did it in 1735\n");
//Bernoulli numbers with even indices
double[] B2 = new double[11];
B2[1] = 1.0;
B2[2] = 1.0/6;
B2[3] = -1.0/30;
B2[4] = 1.0/42;
B2[5] = -1.0/30;
B2[6] = 5.0/66;
B2[7] = -691.0/2730;
B2[8] = 7.0/6;
B2[9] = -3617.0/510;
B2[10]= 43867.0/798;
m = 7;
n = 10;
//n-th harmonic number
h = 1;
for (k = 2; k <= n; k++) {
h += 1.0 / k;
}
println("Hn ", h);
h -= log(n);
println(" -ln ", h);
//expansion C = -digamma(1)
a = -1.0 / (2*n);
n2 = n * n;
r = 1;
for (k = 1; k <= m; k++) {
r *= n2;
a += B2[k] / (2*k * r);
}
println("");
println("err ", a);
println("gamma ", h + a );
println("k = ", n + m);
println("");
println("C = 0.57721566490153286...\n");
}
|
http://rosettacode.org/wiki/Euler%27s_constant_0.5772... | Euler's constant 0.5772... |
Task.
Compute the Euler constant 0.5772...
Discovered by Leonhard Euler around 1730, it is the most ubiquitous mathematical constant after pi and e, but appears more arcane than these.
Denoted gamma (γ), it measures the amount by which the partial sums of the harmonic series (the simplest diverging series) differ from the logarithmic function (its approximating integral): lim n → ∞ (1 + 1/2 + 1/3 + … + 1/n − log(n)).
The definition of γ converges too slowly to be numerically useful, but in 1735 Euler himself applied his recently discovered summation formula to compute ‘the notable number’ accurate to 15 places. For a single-precision implementation this is still the most economic algorithm.
In 1961, the young Donald Knuth used Euler's method to evaluate γ to 1271 places. Knuth found that the computation of the Bernoulli numbers required in the Euler-Maclaurin formula was the most time-consuming part of the procedure.
The next year Dura Sweeney computed 3566 places, using a formula based on the expansion of the exponential integral which didn't need Bernoulli numbers. It's a bit-hungry method though: 2d digits of working precision obtain d correct places only.
This was remedied in 1988 by David Bailey; meanwhile Richard Brent and Ed McMillan had published an even more efficient algorithm based on Bessel function identities and found 30100 places in 20 hours time.
Nowadays the old records have far been exceeded: over 6·1011 decimal places are already known. These massive computations suggest that γ is neither rational nor algebraic, but this is yet to be proven.
References.
[1]
Gourdon and Sebah, The Euler constant γ. (for all formulas)
[2]
Euler's original journal article translated from the latin (p. 9)
| #Racket | Racket | #lang racket/base
(require math/number-theory
math/base)
gamma.0
;; if you want to work it out the hard way...
(define (H n)
(for/sum ((i n)) (/ (add1 i))))
(define (g #:n (n 10) #:k (k 7))
(+ (- (H n)
(log n)
(/ (* n 2)))
(for/sum ((2k (in-range 2 (* 2 (add1 k)) 2)))
(/ (bernoulli-number 2k) (* (expt n 2k) 2k)))))
(g) |
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
| #Scilab | Scilab | clear
n=46
f1=0; f2=1
printf("fibo(%d)=%d\n",0,f1)
printf("fibo(%d)=%d\n",1,f2)
for i=2:n
f3=f1+f2
printf("fibo(%d)=%d\n",i,f3)
f1=f2
f2=f3
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
| #Io | Io | 3 factorial |
http://rosettacode.org/wiki/Euler%27s_constant_0.5772... | Euler's constant 0.5772... |
Task.
Compute the Euler constant 0.5772...
Discovered by Leonhard Euler around 1730, it is the most ubiquitous mathematical constant after pi and e, but appears more arcane than these.
Denoted gamma (γ), it measures the amount by which the partial sums of the harmonic series (the simplest diverging series) differ from the logarithmic function (its approximating integral): lim n → ∞ (1 + 1/2 + 1/3 + … + 1/n − log(n)).
The definition of γ converges too slowly to be numerically useful, but in 1735 Euler himself applied his recently discovered summation formula to compute ‘the notable number’ accurate to 15 places. For a single-precision implementation this is still the most economic algorithm.
In 1961, the young Donald Knuth used Euler's method to evaluate γ to 1271 places. Knuth found that the computation of the Bernoulli numbers required in the Euler-Maclaurin formula was the most time-consuming part of the procedure.
The next year Dura Sweeney computed 3566 places, using a formula based on the expansion of the exponential integral which didn't need Bernoulli numbers. It's a bit-hungry method though: 2d digits of working precision obtain d correct places only.
This was remedied in 1988 by David Bailey; meanwhile Richard Brent and Ed McMillan had published an even more efficient algorithm based on Bessel function identities and found 30100 places in 20 hours time.
Nowadays the old records have far been exceeded: over 6·1011 decimal places are already known. These massive computations suggest that γ is neither rational nor algebraic, but this is yet to be proven.
References.
[1]
Gourdon and Sebah, The Euler constant γ. (for all formulas)
[2]
Euler's original journal article translated from the latin (p. 9)
| #Raku | Raku | # 20211124 Raku programming solution
sub gamma (\N where N > 1) { # Vacca series https://w.wiki/4ybp
# convert terms to FatRat for arbitrary precision
return (1/2 - 1/3) + [+] (2..N).race.map: -> \n {
my ($power, $sign, $term) = 2**n, -1;
for ($power..^2*$power) { $term += ($sign = -$sign) / $_ }
n*$term
}
}
say gamma 23 ; |
http://rosettacode.org/wiki/Euler%27s_constant_0.5772... | Euler's constant 0.5772... |
Task.
Compute the Euler constant 0.5772...
Discovered by Leonhard Euler around 1730, it is the most ubiquitous mathematical constant after pi and e, but appears more arcane than these.
Denoted gamma (γ), it measures the amount by which the partial sums of the harmonic series (the simplest diverging series) differ from the logarithmic function (its approximating integral): lim n → ∞ (1 + 1/2 + 1/3 + … + 1/n − log(n)).
The definition of γ converges too slowly to be numerically useful, but in 1735 Euler himself applied his recently discovered summation formula to compute ‘the notable number’ accurate to 15 places. For a single-precision implementation this is still the most economic algorithm.
In 1961, the young Donald Knuth used Euler's method to evaluate γ to 1271 places. Knuth found that the computation of the Bernoulli numbers required in the Euler-Maclaurin formula was the most time-consuming part of the procedure.
The next year Dura Sweeney computed 3566 places, using a formula based on the expansion of the exponential integral which didn't need Bernoulli numbers. It's a bit-hungry method though: 2d digits of working precision obtain d correct places only.
This was remedied in 1988 by David Bailey; meanwhile Richard Brent and Ed McMillan had published an even more efficient algorithm based on Bessel function identities and found 30100 places in 20 hours time.
Nowadays the old records have far been exceeded: over 6·1011 decimal places are already known. These massive computations suggest that γ is neither rational nor algebraic, but this is yet to be proven.
References.
[1]
Gourdon and Sebah, The Euler constant γ. (for all formulas)
[2]
Euler's original journal article translated from the latin (p. 9)
| #Ruby | Ruby | n = 1e6
p (1..n).sum{ 1.0/_1 } - Math.log(n) |
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
| #sed | sed | #!/bin/sed -f
# First we need to convert each number into the right number of ticks
# Start by marking digits
s/[0-9]/<&/g
# We have to do the digits manually.
s/0//g; s/1/|/g; s/2/||/g; s/3/|||/g; s/4/||||/g; s/5/|||||/g
s/6/||||||/g; s/7/|||||||/g; s/8/||||||||/g; s/9/|||||||||/g
# Multiply by ten for each digit from the front.
:tens
s/|</<||||||||||/g
t tens
# Done with digit markers
s/<//g
# Now the actual work.
:split
# Convert each stretch of n >= 2 ticks into two of n-1, with a mark between
s/|\(|\+\)/\1-\1/g
# Convert the previous mark and the first tick after it to a different mark
# giving us n-1+n-2 marks.
s/-|/+/g
# Jump back unless we're done.
t split
# Get rid of the pluses, we're done with them.
s/+//g
# Convert back to digits
:back
s/||||||||||/</g
s/<\([0-9]*\)$/<0\1/g
s/|||||||||/9/g;
s/|||||||||/9/g; s/||||||||/8/g; s/|||||||/7/g; s/||||||/6/g;
s/|||||/5/g; s/||||/4/g; s/|||/3/g; s/||/2/g; s/|/1/g;
s/</|/g
t back
s/^$/0/ |
http://rosettacode.org/wiki/Factorial | Factorial | Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a number.
Solutions can be iterative or recursive.
Support for trapping negative n errors is optional.
Related task
Primorial numbers
| #J | J | ! 8 NB. Built in factorial operator
40320 |
http://rosettacode.org/wiki/Euler%27s_constant_0.5772... | Euler's constant 0.5772... |
Task.
Compute the Euler constant 0.5772...
Discovered by Leonhard Euler around 1730, it is the most ubiquitous mathematical constant after pi and e, but appears more arcane than these.
Denoted gamma (γ), it measures the amount by which the partial sums of the harmonic series (the simplest diverging series) differ from the logarithmic function (its approximating integral): lim n → ∞ (1 + 1/2 + 1/3 + … + 1/n − log(n)).
The definition of γ converges too slowly to be numerically useful, but in 1735 Euler himself applied his recently discovered summation formula to compute ‘the notable number’ accurate to 15 places. For a single-precision implementation this is still the most economic algorithm.
In 1961, the young Donald Knuth used Euler's method to evaluate γ to 1271 places. Knuth found that the computation of the Bernoulli numbers required in the Euler-Maclaurin formula was the most time-consuming part of the procedure.
The next year Dura Sweeney computed 3566 places, using a formula based on the expansion of the exponential integral which didn't need Bernoulli numbers. It's a bit-hungry method though: 2d digits of working precision obtain d correct places only.
This was remedied in 1988 by David Bailey; meanwhile Richard Brent and Ed McMillan had published an even more efficient algorithm based on Bessel function identities and found 30100 places in 20 hours time.
Nowadays the old records have far been exceeded: over 6·1011 decimal places are already known. These massive computations suggest that γ is neither rational nor algebraic, but this is yet to be proven.
References.
[1]
Gourdon and Sebah, The Euler constant γ. (for all formulas)
[2]
Euler's original journal article translated from the latin (p. 9)
| #Rust | Rust | // 20220322 Rust programming solution
fn gamma(N: u32) -> f64 { // Vacca series https://w.wiki/4ybp
return 1f64 / 2f64 - 1f64 / 3f64
+ ((2..=N).map(|n| {
let power: u32 = 2u32.pow(n);
let mut sign: f64 = -1f64;
let mut term: f64 = 0f64;
for denominator in power..=(2 * power - 1) {
sign *= -1f64;
term += sign / f64::from(denominator);
}
return f64::from(n) * term;
}))
.sum::<f64>();
}
fn main() {
println!("{}", gamma(23));
} |
http://rosettacode.org/wiki/Euler%27s_constant_0.5772... | Euler's constant 0.5772... |
Task.
Compute the Euler constant 0.5772...
Discovered by Leonhard Euler around 1730, it is the most ubiquitous mathematical constant after pi and e, but appears more arcane than these.
Denoted gamma (γ), it measures the amount by which the partial sums of the harmonic series (the simplest diverging series) differ from the logarithmic function (its approximating integral): lim n → ∞ (1 + 1/2 + 1/3 + … + 1/n − log(n)).
The definition of γ converges too slowly to be numerically useful, but in 1735 Euler himself applied his recently discovered summation formula to compute ‘the notable number’ accurate to 15 places. For a single-precision implementation this is still the most economic algorithm.
In 1961, the young Donald Knuth used Euler's method to evaluate γ to 1271 places. Knuth found that the computation of the Bernoulli numbers required in the Euler-Maclaurin formula was the most time-consuming part of the procedure.
The next year Dura Sweeney computed 3566 places, using a formula based on the expansion of the exponential integral which didn't need Bernoulli numbers. It's a bit-hungry method though: 2d digits of working precision obtain d correct places only.
This was remedied in 1988 by David Bailey; meanwhile Richard Brent and Ed McMillan had published an even more efficient algorithm based on Bessel function identities and found 30100 places in 20 hours time.
Nowadays the old records have far been exceeded: over 6·1011 decimal places are already known. These massive computations suggest that γ is neither rational nor algebraic, but this is yet to be proven.
References.
[1]
Gourdon and Sebah, The Euler constant γ. (for all formulas)
[2]
Euler's original journal article translated from the latin (p. 9)
| #Scheme | Scheme | ; Procedure to compute factorial.
(define fact
(lambda (n)
(if (<= n 0)
1
(* n (fact (1- n))))))
; Compute Euler's gamma constant as the difference of log(n) from a sum.
; See section 2.3 of <http://numbers.computation.free.fr/Constants/Gamma/gamma.html>.
(define gamma
(lambda (n)
(let ((sum 0))
(do ((k 1 (1+ k)))
((> k (* 3.5911 n)) (- sum (log n)))
(set! sum (+ sum (/ (* (expt -1 (1- k)) (expt n k)) (* k (fact k)))))))))
; Show Euler's gamma constant computed at log(100).
(printf "Euler's gamma constant: ~a~%" (gamma 100)) |
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
| #Seed7 | Seed7 | const func integer: fib (in integer: number) is func
result
var integer: result is 1;
begin
if number > 2 then
result := fib(pred(number)) + fib(number - 2);
elsif number = 0 then
result := 0;
end if;
end func; |
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
| #Janet | Janet |
(defn factorial [x]
(cond
(< x 0) nil
(= x 0) 1
(* x (factorial (dec x)))))
|
http://rosettacode.org/wiki/Euler%27s_constant_0.5772... | Euler's constant 0.5772... |
Task.
Compute the Euler constant 0.5772...
Discovered by Leonhard Euler around 1730, it is the most ubiquitous mathematical constant after pi and e, but appears more arcane than these.
Denoted gamma (γ), it measures the amount by which the partial sums of the harmonic series (the simplest diverging series) differ from the logarithmic function (its approximating integral): lim n → ∞ (1 + 1/2 + 1/3 + … + 1/n − log(n)).
The definition of γ converges too slowly to be numerically useful, but in 1735 Euler himself applied his recently discovered summation formula to compute ‘the notable number’ accurate to 15 places. For a single-precision implementation this is still the most economic algorithm.
In 1961, the young Donald Knuth used Euler's method to evaluate γ to 1271 places. Knuth found that the computation of the Bernoulli numbers required in the Euler-Maclaurin formula was the most time-consuming part of the procedure.
The next year Dura Sweeney computed 3566 places, using a formula based on the expansion of the exponential integral which didn't need Bernoulli numbers. It's a bit-hungry method though: 2d digits of working precision obtain d correct places only.
This was remedied in 1988 by David Bailey; meanwhile Richard Brent and Ed McMillan had published an even more efficient algorithm based on Bessel function identities and found 30100 places in 20 hours time.
Nowadays the old records have far been exceeded: over 6·1011 decimal places are already known. These massive computations suggest that γ is neither rational nor algebraic, but this is yet to be proven.
References.
[1]
Gourdon and Sebah, The Euler constant γ. (for all formulas)
[2]
Euler's original journal article translated from the latin (p. 9)
| #Sidef | Sidef | # 100 decimals of precision
local Num!PREC = 4*100
say Num.EulerGamma |
http://rosettacode.org/wiki/Euler%27s_constant_0.5772... | Euler's constant 0.5772... |
Task.
Compute the Euler constant 0.5772...
Discovered by Leonhard Euler around 1730, it is the most ubiquitous mathematical constant after pi and e, but appears more arcane than these.
Denoted gamma (γ), it measures the amount by which the partial sums of the harmonic series (the simplest diverging series) differ from the logarithmic function (its approximating integral): lim n → ∞ (1 + 1/2 + 1/3 + … + 1/n − log(n)).
The definition of γ converges too slowly to be numerically useful, but in 1735 Euler himself applied his recently discovered summation formula to compute ‘the notable number’ accurate to 15 places. For a single-precision implementation this is still the most economic algorithm.
In 1961, the young Donald Knuth used Euler's method to evaluate γ to 1271 places. Knuth found that the computation of the Bernoulli numbers required in the Euler-Maclaurin formula was the most time-consuming part of the procedure.
The next year Dura Sweeney computed 3566 places, using a formula based on the expansion of the exponential integral which didn't need Bernoulli numbers. It's a bit-hungry method though: 2d digits of working precision obtain d correct places only.
This was remedied in 1988 by David Bailey; meanwhile Richard Brent and Ed McMillan had published an even more efficient algorithm based on Bessel function identities and found 30100 places in 20 hours time.
Nowadays the old records have far been exceeded: over 6·1011 decimal places are already known. These massive computations suggest that γ is neither rational nor algebraic, but this is yet to be proven.
References.
[1]
Gourdon and Sebah, The Euler constant γ. (for all formulas)
[2]
Euler's original journal article translated from the latin (p. 9)
| #Vlang | Vlang | import math
const eps = 1e-6
fn main() {
//.5772
println("From the definition, err. 3e-10")
mut n := 400
mut h := 1.0
for k in 2..n+1 {
h += 1.0/f64(k)
}
//faster convergence: Negoi, 1997
mut a := math.log(f64(n) + 0.5 + 1.0/f64(24*n))
println("Hn ${h:0.16f}")
println("gamma ${h-a:0.16f}\nk = $n\n")
println("Sweeney, 1963, err. idem")
n = 21
mut s := [0.0, f64(n)]
mut r := f64(n)
mut k := 1
for {
k++
r *= f64(n) / f64(k)
s[k & 1] += r/f64(k)
if r <= eps {
break
}
}
println("gamma ${s[1] - s[0] - math.log(n):0.16f}\nk = $k\n")
println("Bailey, 1988")
n = 5
a = 1.0
h = 1.0
mut n2 := math.pow(f64(2),f64(n))
r = 1
k = 1
for {
k++
r *= n2 / f64(k)
h += 1/f64(k)
b := a
a += r * h
if math.abs(b-a) <= eps {
break
}
}
a *= n2 / math.exp(n2)
println("gamma ${a - n * math.log(2):.16f}\nk = $k\n")
println("Brent-McMillan, 1980")
n = 13
a = -math.log(n)
mut b := 1.0
mut u := a
mut v := b
n2 = n * n
mut k2 := 0
k = 0
for {
k2 += 2*k + 1
k++
a *= n2 / f64(k)
b *= n2 / f64(k2)
a = (a + b)/f64(k)
u += a
v += b
if math.abs(a) <= eps {
break
}
}
println("gamma ${u/v:0.16f}\nk = $k\n")
println("How Euler did it in 1735")
// Bernoulli numbers with even indices
b2 := [1.0, 1.0/6, -1.0/30, 1.0/42, -1.0/30, 5.0/66, -691.0/2730, 7.0/6, -3617.0/510, 43867.0/798]
m := 7
n = 10
// n'th harmonic number
h = 1.0
for kz in 2..n+1 {
h += 1.0/f64(kz)
}
println("Hn ${h:0.16f}")
h -= math.log(n)
println(" -ln ${h:0.16f}")
// expansion C = -digamma(1)
a = -1.0 / (2.0*f64(n))
n2 = f64(n * n)
r = 1
for kq in 1..m+1 {
r *= n2
a += b2[kq] / (2.0*f64(kq)*r)
}
println("err ${a:0.16f}\ngamma ${h+a:0.16f}\nk = ${n+m}")
println("\nC = 0.57721566490153286...")
} |
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
| #SequenceL | SequenceL | fibonacci(n) :=
n when n < 2
else
fibonacci(n - 1) + fibonacci(n - 2); |
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
| #Java | Java |
package programas;
import java.math.BigInteger;
import java.util.InputMismatchException;
import java.util.Scanner;
public class IterativeFactorial {
public BigInteger factorial(BigInteger n) {
if ( n == null ) {
throw new IllegalArgumentException();
}
else if ( n.signum() == - 1 ) {
// negative
throw new IllegalArgumentException("Argument must be a non-negative integer");
}
else {
BigInteger factorial = BigInteger.ONE;
for ( BigInteger i = BigInteger.ONE; i.compareTo(n) < 1; i = i.add(BigInteger.ONE) ) {
factorial = factorial.multiply(i);
}
return factorial;
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
BigInteger number, result;
boolean error = false;
System.out.println("FACTORIAL OF A NUMBER");
do {
System.out.println("Enter a number:");
try {
number = scanner.nextBigInteger();
result = new IterativeFactorial().factorial(number);
error = false;
System.out.println("Factorial of " + number + ": " + result);
}
catch ( InputMismatchException e ) {
error = true;
scanner.nextLine();
}
catch ( IllegalArgumentException e ) {
error = true;
scanner.nextLine();
}
}
while ( error );
scanner.close();
}
}
|
http://rosettacode.org/wiki/Euler%27s_constant_0.5772... | Euler's constant 0.5772... |
Task.
Compute the Euler constant 0.5772...
Discovered by Leonhard Euler around 1730, it is the most ubiquitous mathematical constant after pi and e, but appears more arcane than these.
Denoted gamma (γ), it measures the amount by which the partial sums of the harmonic series (the simplest diverging series) differ from the logarithmic function (its approximating integral): lim n → ∞ (1 + 1/2 + 1/3 + … + 1/n − log(n)).
The definition of γ converges too slowly to be numerically useful, but in 1735 Euler himself applied his recently discovered summation formula to compute ‘the notable number’ accurate to 15 places. For a single-precision implementation this is still the most economic algorithm.
In 1961, the young Donald Knuth used Euler's method to evaluate γ to 1271 places. Knuth found that the computation of the Bernoulli numbers required in the Euler-Maclaurin formula was the most time-consuming part of the procedure.
The next year Dura Sweeney computed 3566 places, using a formula based on the expansion of the exponential integral which didn't need Bernoulli numbers. It's a bit-hungry method though: 2d digits of working precision obtain d correct places only.
This was remedied in 1988 by David Bailey; meanwhile Richard Brent and Ed McMillan had published an even more efficient algorithm based on Bessel function identities and found 30100 places in 20 hours time.
Nowadays the old records have far been exceeded: over 6·1011 decimal places are already known. These massive computations suggest that γ is neither rational nor algebraic, but this is yet to be proven.
References.
[1]
Gourdon and Sebah, The Euler constant γ. (for all formulas)
[2]
Euler's original journal article translated from the latin (p. 9)
| #Wren | Wren | import "./fmt" for Fmt
var eps = 1e-6
System.print("From the definition, err. 3e-10")
var n = 400
var h = 1
for (k in 2..n) h = h + 1/k
//faster convergence: Negoi, 1997
var a = (n + 0.5 + 1/(24*n)).log
Fmt.print("Hn $0.14f", h)
Fmt.print("gamma $0.14f\nk = $d\n", h - a, n)
System.print("Sweeney, 1963, err. idem")
n = 21
var s = [0, n]
var r = n
var k = 1
while (true) {
k = k + 1
r = r * n / k
s[k & 1] = s[k & 1] + r/k
if (r <= eps) break
}
Fmt.print("gamma $0.14f\nk = $d\n", s[1] - s[0] - n.log, k)
System.print("Bailey, 1988")
n = 5
a = 1
h = 1
var n2 = 2.pow(n)
r = 1
k = 1
while (true) {
k = k + 1
r = r * n2 / k
h = h + 1/k
var b = a
a = a + r * h
if ((b-a).abs <= eps) break
}
a = a * n2 / n2.exp
Fmt.print("gamma $0.14f\nk = $d\n", a - n * 2.log, k)
System.print("Brent-McMillan, 1980")
n = 13
a = -n.log
var b = 1
var u = a
var v = b
n2 = n * n
var k2 = 0
k = 0
while (true) {
k2 = k2 + 2*k + 1
k = k + 1
a = a * n2 / k
b = b * n2 / k2
a = (a + b)/k
u = u + a
v = v + b
if (a.abs <= eps) break
}
Fmt.print("gamma $0.14f\nk = $d\n", u / v, k)
System.print("How Euler did it in 1735")
// Bernoulli numbers with even indices
var b2 = [1, 1/6, -1/30, 1/42, -1/30, 5/66, -691/2730, 7/6, -3617/510, 43867/798]
var m = 7
n = 10
// n'th harmonic number
h = 1
for (k in 2..n) h = h + 1/k
Fmt.print("Hn $0.14f", h)
h = h - n.log
Fmt.print(" -ln $0.14f", h)
// expansion C = -digamma(1)
a = -1 / (2*n)
n2 = n * n
r = 1
for (k in 1..m) {
r = r * n2
a = a + b2[k] / (2*k*r)
}
Fmt.print("err $0.14f\ngamma $0.14f\nk = $d", a, h + a, n + m)
System.print("\nC = 0.57721566490153286...") |
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
| #SETL | SETL | $ Print out the first ten Fibonacci numbers
$ This uses Set Builder Notation, it roughly means
$ 'collect fib(n) forall n in {0,1,2,3,4,5,6,7,8,9,10}'
print({fib(n) : n in {0..10}});
$ Iterative Fibonacci function
proc fib(n);
A := 0; B := 1; C := n;
for i in {0..n} loop
C := A + B;
A := B;
B := C;
end loop;
return C;
end proc; |
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
| #JavaScript | JavaScript | function factorial(n) {
//check our edge case
if (n < 0) { throw "Number must be non-negative"; }
var result = 1;
//we skip zero and one since both are 1 and are identity
while (n > 1) {
result *= n;
n--;
}
return result;
} |
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
| #Shen | Shen | (define fib
0 -> 0
1 -> 1
N -> (+ (fib (+ N 1)) (fib (+ N 2)))
where (< N 0)
N -> (+ (fib (- N 1)) (fib (- N 2)))) |
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
| #JOVIAL | JOVIAL | PROC FACTORIAL(ARG) U;
BEGIN
ITEM ARG U;
ITEM TEMP U;
TEMP = 1;
FOR I:2 BY 1 WHILE I<=ARG;
TEMP = TEMP*I;
FACTORIAL = TEMP;
END |
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
| #Sidef | Sidef | func fib_iter(n) {
var (a, b) = (0, 1)
{ (a, b) = (b, a+b) } * n
return 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
| #Joy | Joy | DEFINE factorial == [0 =] [pop 1] [dup 1 - factorial *] ifte. |
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.
| #11l | 11l | print(math:e ^ (math:pi * 1i) + 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
| #Simula | Simula | INTEGER PROCEDURE fibonacci(n);
INTEGER n;
BEGIN
INTEGER lo, hi, temp, i;
lo := 0;
hi := 1;
FOR i := 1 STEP 1 UNTIL n - 1 DO
BEGIN
temp := hi;
hi := hi + lo;
lo := temp
END;
fibonacci := hi
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
| #jq | jq | def fact:
reduce range(1; .+1) as $i (1; . * $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.
| #Ada | Ada | with Ada.Long_Complex_Text_IO; use Ada.Long_Complex_Text_IO;
with Ada.Numerics; use Ada.Numerics;
with Ada.Numerics.Long_Complex_Types; use Ada.Numerics.Long_Complex_Types;
with Ada.Numerics.Long_Complex_Elementary_Functions; use Ada.Numerics.Long_Complex_Elementary_Functions;
procedure Eulers_Identity is
begin
Put (Exp (Pi * i) + 1.0);
end Eulers_Identity; |
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.
| #ALGOL_68 | ALGOL 68 | BEGIN
# calculate an approximation to e^(i pi) + 1 which should be 0 (Euler's identity) #
# returns e^ix for long real x, using the series: #
# exp(ix) = 1 - x^2/2! + x^4/4! - ... + i(x - x^3/3! + x^5/5! - x^7/7! ... ) #
# the expansion stops when successive terms differ by less than 1e-15 #
PROC expi = ( LONG REAL x )LONG COMPL:
BEGIN
LONG REAL t := 1;
LONG REAL real part := 1;
LONG REAL imaginary part := 0;
LONG REAL divisor := 1;
BOOL even power := FALSE;
BOOL subtract := FALSE;
LONG REAL diff := 1;
FOR n FROM 1 WHILE ABS diff > 1e-15 DO
divisor *:= n;
t *:= x;
LONG REAL term := t / divisor;
IF even power THEN
# this term is real #
subtract := NOT subtract;
LONG REAL prev := real part;
IF subtract THEN
real part -:= term
ELSE
real part +:= term
FI;
diff := prev - real part
ELSE
# this term is imaginary #
LONG REAL prev := imaginary part;
IF subtract THEN
imaginary part -:= term
ELSE
imaginary part +:= term
FI;
diff := prev - imaginary part
FI;
even power := NOT even power
OD;
( real part, imaginary part )
END # expi # ;
LONG COMPL eulers identity = expi( long pi ) + 1;
print( ( "e^(i*pi) + 1 ~ "
, fixed( re OF eulers identity, -23, 20 )
, " "
, fixed( im OF eulers identity, 23, 20 )
, "i"
, newline
)
)
END |
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
| #SkookumScript | SkookumScript | 42.fibonacci |
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
| #Jsish | Jsish | /* Factorial, in Jsish */
/* recursive */
function fact(n) { return ((n < 2) ? 1 : n * fact(n - 1)); }
/* iterative */
function factorial(n:number) {
if (n < 0) throw format("factorial undefined for negative values: %d", n);
var fac = 1;
while (n > 1) fac *= n--;
return fac;
}
if (Interp.conf('unitTest') > 0) {
;fact(18);
;fact(1);
;factorial(18);
;factorial(42);
try { factorial(-1); } catch (err) { puts(err); }
} |
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.
| #Bracmat | Bracmat | 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.
| #C | C | #include <stdio.h>
#include <math.h>
#include <complex.h>
#include <wchar.h>
#include <locale.h>
int main() {
wchar_t pi = L'\u03c0'; /* Small pi symbol */
wchar_t ae = L'\u2245'; /* Approximately equals symbol */
double complex e = cexp(M_PI * I) + 1.0;
setlocale(LC_CTYPE, "");
printf("e ^ %lci + 1 = [%.16f, %.16f] %lc 0\n", pi, creal(e), cimag(e), ae);
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
| #Slate | Slate | n@(Integer traits) fib
[
n <= 0 ifTrue: [^ 0].
n = 1 ifTrue: [^ 1].
(n - 1) fib + (n - 2) fib
].
slate[15]> 10 fib = 55.
True |
http://rosettacode.org/wiki/Factorial | Factorial | Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a number.
Solutions can be iterative or recursive.
Support for trapping negative n errors is optional.
Related task
Primorial numbers
| #Julia | Julia | help?> factorial
search: factorial Factorization factorize
factorial(n)
Factorial of n. If n is an Integer, the factorial is computed as an integer (promoted to at
least 64 bits). Note that this may overflow if n is not small, but you can use factorial(big(n))
to compute the result exactly in arbitrary precision. If n is not an Integer, factorial(n) is
equivalent to gamma(n+1).
julia> factorial(6)
720
julia> factorial(21)
ERROR: OverflowError()
[...]
julia> factorial(21.0)
5.109094217170944e19
julia> factorial(big(21))
51090942171709440000 |
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.
| #C.23 | C# | using System;
using System.Numerics;
public class Program
{
static void Main() {
Complex e = Math.E;
Complex i = Complex.ImaginaryOne;
Complex π = Math.PI;
Console.WriteLine(Complex.Pow(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.
| #C.2B.2B | C++ | #include <iostream>
#include <complex>
int main() {
std::cout << std::exp(std::complex<double>(0.0, M_PI)) + 1.0 << std::endl;
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
| #Smalltalk | Smalltalk | Integer >> fibI
|aNMinus1 an t|
aNMinus1 := 1.
an := 0.
self timesRepeat:[
t := an.
an := an + aNMinus1 .
aNMinus1 := t.
].
^ an |
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
| #K | K | facti:*/1+!:
facti 5
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.
| #Common_Lisp | Common Lisp |
(+ 1 (exp (complex 0 pi)))
|
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.
| #Delphi | Delphi |
program Euler_identity;
{$APPTYPE CONSOLE}
uses
System.VarCmplx;
begin
var result := VarComplexExp(Pi * VarComplexCreate(0, 1)) + 1;
writeln(result);
readln;
end. |
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
| #smart_BASIC | smart BASIC | FOR i = 0 TO 15
PRINT fibR(i),fibI(i),fibN(i)
NEXT i
/* Recursive Method */
DEF fibR(n)
IF n <= 1 THEN
fibR = n
ELSE
fibR = fibR(n-1) + fibR(n-2)
ENDIF
END DEF
/* Iterative Method */
DEF fibI(n)
a = 0
b = 1
FOR i = 1 TO n
temp = a + b
a = b
b = temp
NEXT i
fibI = a
END DEF
/* N-th Term Method */
DEF fibN(n)
uphi = .5 + SQR(5)/2
lphi = .5 - SQR(5)/2
fibN = (uphi^n-lphi^n)/SQR(5)
END DEF |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.