This language bar is your friend. Select your favorite languages!
Select your favorite languages :
- Or search :
Idiom #31 Recursive factorial (simple)
Create the recursive function f which returns the factorial of the non-negative integer i, calculated from f(i-1)
- Ada
- C
- Clojure
- C++
- C#
- C#
- D
- Dart
- Elixir
- Erlang
- Fortran
- Go
- Groovy
- Haskell
- JS
- JS
- Java
- Kotlin
- Kotlin
- Lisp
- Lua
- Obj-C
- PHP
- PHP
- Pascal
- Perl
- Python
- Ruby
- Ruby
- Rust
- Rust
- Scala
- Scheme
- Smalltalk
- VB
uint f(in uint i) pure nothrow @nogc
in {
assert(i <= 12);
} body {
if (i == 0)
return 1;
else
return i * f(i - 1);
}
Assertion is used to prevent silent overflow.
int f(int i) {
if (i == 0)
return 1;
else
return i * f(i - 1);
}
Warnings :
- type int quickly overflows
- high number of recursive calls may cause a stack overflow
- also, f is not tail-recursive
- type int quickly overflows
- high number of recursive calls may cause a stack overflow
- also, f is not tail-recursive
f = Hash.new { |hash, i| hash[i] = i * hash[i -1] }
f[0] = 1
Note that f is not a function but plain old Hash used as a cache for performance.