Taskintro
Compute a factorial
Also called factorial, n!, math.factorial, recursive factorial, iterative factorial, big factorial, gamma function, MulRange, tgamma.
Compute the factorial of a non-negative integer with a loop, with recursion or with a library function. 20! is the largest factorial in 64 bits, so larger ones need big integers.
- Evidence
- Code in 10 languages
Task
Compute the factorial of a non-negative integer. The factorial of n, written n!, is the product of the integers from 1 to n. The Rosetta Code task says: "Write a function to return the factorial of a number. Solutions can be iterative or recursive"1.
The function factorial(n) returns n!. For example, factorial(5) is 5 times 4 times 3 times 2 times 1, which is 120.
The factorial of 0 is 1. "The value of 0! is 1, according to the convention for an empty product"2: a product of no numbers is 1, as the sum of no numbers is 0.
The factorial grows fast: "the factorial has faster than exponential growth"2. 13! does not fit in 32 bits, and 21! does not fit in 64 bits. So the contract has the range 0 to 20, and the pitfalls show what happens above it. For larger n, use big integers.
Solutions
| Language | Loop or library | Big result |
|---|---|---|
| Python | math.factorial(n) |
the same; Python integers have no size limit |
| JavaScript, TypeScript | a loop with BigInt values |
the same |
| Java | a loop with Math.multiplyExact |
BigInteger.multiply in a loop |
| C# | a loop with checked |
BigInteger in a loop |
| Go | a loop | new(big.Int).MulRange(1, n) |
| Rust | (1..=n).product::<i64>() |
none in the standard library |
| C | a loop with long long |
none |
| C++ | a loop with long long |
none |
| Bash | a loop with $((f * i)) |
bc |
- Python.
math.factorialreturns the "factorial of the nonnegative integer n"3. It raisesValueErrorfor a negativen. - JavaScript. There is no factorial function. A
numberholds each factorial up to 22! exactly, but no larger one, so the solution usesBigIntvalues. - TypeScript. The same code as JavaScript, with the type
bigint. - Java. There is no factorial function.
Math.multiplyExactthrows anArithmeticException"if the result overflows a long"4, so 21! fails loudly. - C#. There is no factorial function. A
checkedblock throwsOverflowExceptionon overflow. - Go. There is no factorial function for
int64values. For big integers, "MulRange sets z to the product of all integers in the range [a, b] inclusively and returns z"5, soMulRange(1, n)isn!. - Rust.
productof the range1..=nis the factorial. The empty range1..=0gives 1. - C. The solution uses a loop with
long longvalues. A signed overflow is undefined behavior, so the range of the contract is important. - C++. The same loop as C, as a
constexprfunction, so the compiler can compute a factorial of a constant. - Bash. The solution uses a
forloop with$((f * i)). Bash arithmetic does not check for overflow.
The Python function, with a big result:
import math
print(math.factorial(0), math.factorial(5), math.factorial(20))
print(math.factorial(25))
try:
math.factorial(-1)
except ValueError as e:
print(type(e).__name__)
1 120 2432902008176640000
15511210043330985984000000
ValueError
The Go function for big integers:
package main
import (
"fmt"
"math/big"
)
func main() {
fmt.Println(new(big.Int).MulRange(1, 25))
fmt.Println(new(big.Int).MulRange(1, 0))
}
15511210043330985984000000
1
The recursive form follows the definition n! = n * (n - 1)!, with 0! = 1. Each call waits for the next call, so it uses one stack frame for each step:
fn factorial(n: u64) -> u64 {
if n == 0 { 1 } else { n * factorial(n - 1) }
}
fn main() {
println!("{} {}", factorial(5), factorial(20));
}
120 2432902008176640000
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
fiveandten: small factorials.zero: the factorial of 0 is 1, the empty product.one: the factorial of 1 is 1.largest-32-bit: 12! is 479001600, the largest factorial in a 32-bit signed integer.beyond-32-bit: 13! is 6227020800, which needs more than 32 bits.largest-64-bit: 20! is 2432902008176640000, the largest factorial in a 64-bit signed integer.
Pitfalls
- The product overflows with no error. 21! does not fit in 64 bits. In Java, a
longloop wraps around and gives a negative number.Math.multiplyExactthrows an exception:
This code runs but gives a wrong answer on purpose.
public class Main {
public static void main(String[] args) {
long f = 1;
for (int i = 1; i <= 21; i++) {
f *= i;
}
System.out.println(f);
try {
long g = 1;
for (int i = 1; i <= 21; i++) {
g = Math.multiplyExact(g, i);
}
System.out.println(g);
} catch (ArithmeticException e) {
System.out.println(e.getClass().getSimpleName());
}
}
}
-4249290049419214848
ArithmeticException
See Integer overflow or wraparound and Use big integers.
- A float factorial is not exact. A 64-bit float has 53 bits of precision. The factorials up to 22! are exact as floats, but larger ones are rounded:
This code runs but gives a wrong answer on purpose.
let f = 1;
let g = 1n;
for (let i = 1; i <= 25; i++) {
f *= i;
g *= BigInt(i);
}
console.log(f);
console.log(g);
1.5511210043330986e+25
15511210043330985984000000n
- Deep recursion fails. The recursive form uses a stack frame for each step. In Python, the default recursion limit is about 1000 frames, so a recursive factorial of 5000 fails. The loop has no limit, and the result has 54233 bits:
import math
def factorial(n):
return 1 if n == 0 else n * factorial(n - 1)
try:
factorial(5000)
except RecursionError as e:
print(type(e).__name__)
print(math.factorial(5000).bit_length())
RecursionError
54233
-
A negative argument. The factorial of a negative integer has no value. A loop from 1 to
nreturns 1 for each negativen, with no error. Check the argument first, asmath.factorialdoes. -
The gamma function is not the factorial. The gamma function extends the factorial to other numbers: "The gamma function (shifted one unit left to match the factorials) continuously interpolates the factorial to non-integer values"2.
gamma(n + 1)isn!, and the result is a float. In Python,math.gamma(x)"Return the Gamma function at x"6. In C and C++,tgammareturns the value of the gamma function7:
import math
print(math.gamma(6), math.factorial(5))
print(math.isclose(math.gamma(0.5) ** 2, math.pi))
120.0 120
True
Related tasks
- Sum and multiply a list: the factorial is the product of the list 1 to
n. - Compute Fibonacci numbers: another sequence with a loop form and a recursive form.
- Use big integers: factorials above 20! need big integers.
- Check whether a number is prime: another small task on integers.
The algorithm is on the algorithm site: factorial.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compute-a-factorial/.
import math
def factorial(n: int) -> int:
"""Return n! with the library function."""
return math.factorial(n)
def factorial_loop(n: int) -> int:
"""Return n! with a loop."""
if n < 0:
raise ValueError("n is negative")
f = 1
for i in range(2, n + 1):
f *= i
return f
def factorial_recursive(n: int) -> int:
"""Return n! with recursion. Each step uses one stack frame."""
return 1 if n == 0 else n * factorial_recursive(n - 1)
test_factorial.py 30 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compute-a-factorial/.
import pytest
from factorial import factorial, factorial_loop, factorial_recursive
CASES = [
("five", 5, 120),
("ten", 10, 3628800),
("zero", 0, 1),
("one", 1, 1),
("largest-32-bit", 12, 479001600),
("beyond-32-bit", 13, 6227020800),
("largest-64-bit", 20, 2432902008176640000),
]
@pytest.mark.parametrize(("name", "n", "want"), CASES, ids=[c[0] for c in CASES])
def test_factorial(name, n, want):
assert factorial(n) == want
assert factorial_loop(n) == want
assert factorial_recursive(n) == want
def test_negative_raises():
with pytest.raises(ValueError):
factorial(-1)
with pytest.raises(ValueError):
factorial_loop(-1)
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-a-factorial/.
#ifndef FACTORIAL_HPP
#define FACTORIAL_HPP
// Returns n! for 0 <= n <= 20. constexpr lets the compiler compute the
// factorial of a constant.
constexpr long long factorial(int n) {
long long f = 1;
for (int i = 2; i <= n; i++) {
f *= i;
}
return f;
}
#endif
test_factorial.cpp 44 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-a-factorial/.
#include <cstdio>
#include "factorial.hpp"
namespace {
struct test_case {
const char* name;
int n;
long long want;
};
const test_case cases[] = {
{"five", 5, 120},
{"ten", 10, 3628800},
{"zero", 0, 1},
{"one", 1, 1},
{"largest-32-bit", 12, 479001600},
{"beyond-32-bit", 13, 6227020800LL},
{"largest-64-bit", 20, 2432902008176640000LL},
};
static_assert(factorial(5) == 120);
} // namespace
int main() {
int failures = 0;
for (const auto& c : cases) {
const long long got = factorial(c.n);
if (got != c.want) {
std::printf("FAIL %s: %lld\n", c.name, got);
++failures;
}
}
if (failures != 0) {
return 1;
}
std::printf("ok\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-a-factorial/.
import java.math.BigInteger;
/** The factorial of a non-negative integer. */
public final class Factorial {
private Factorial() {}
/** Returns n!. multiplyExact throws ArithmeticException above 20!. */
public static long factorial(long n) {
if (n < 0) {
throw new IllegalArgumentException("n is negative");
}
long f = 1;
for (long i = 2; i <= n; i++) {
f = Math.multiplyExact(f, i);
}
return f;
}
/** Returns n! as a BigInteger, with no size limit. */
public static BigInteger bigFactorial(int n) {
BigInteger f = BigInteger.ONE;
for (int i = 2; i <= n; i++) {
f = f.multiply(BigInteger.valueOf(i));
}
return f;
}
}
FactorialTest.java 39 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-a-factorial/.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.math.BigInteger;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class FactorialTest {
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("five", 5, 120),
Arguments.of("ten", 10, 3628800),
Arguments.of("zero", 0, 1),
Arguments.of("one", 1, 1),
Arguments.of("largest-32-bit", 12, 479001600),
Arguments.of("beyond-32-bit", 13, 6227020800L),
Arguments.of("largest-64-bit", 20, 2432902008176640000L)
);
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void factorial(String name, long n, long want) {
assertEquals(want, Factorial.factorial(n));
assertEquals(BigInteger.valueOf(want), Factorial.bigFactorial((int) n));
}
@Test
void overflowThrows() {
assertThrows(ArithmeticException.class, () -> Factorial.factorial(21));
assertEquals(new BigInteger("51090942171709440000"), Factorial.bigFactorial(21));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-a-factorial/.
#include "factorial.h"
long long factorial(int n) {
long long f = 1;
for (int i = 2; i <= n; i++) {
f *= i;
}
return f;
}
factorial.h 11 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-a-factorial/.
#ifndef FACTORIAL_H
#define FACTORIAL_H
// Returns n! for 0 <= n <= 20. Above 20, the product overflows, which is
// undefined behavior for a signed type.
long long factorial(int n);
#endif
test_factorial.c 40 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-a-factorial/.
#include "factorial.h"
#include <stdio.h>
#include <stdlib.h>
struct test_case {
const char *name;
int n;
long long want;
};
static const struct test_case cases[] = {
{"five", 5, 120},
{"ten", 10, 3628800},
{"zero", 0, 1},
{"one", 1, 1},
{"largest-32-bit", 12, 479001600},
{"beyond-32-bit", 13, 6227020800LL},
{"largest-64-bit", 20, 2432902008176640000LL},
};
int main(void) {
int failures = 0;
for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
const struct test_case *c = &cases[i];
long long got = factorial(c->n);
if (got != c->want) {
printf("FAIL %s: %lld\n", c->name, got);
failures++;
}
}
if (failures != 0) {
return EXIT_FAILURE;
}
printf("ok\n");
return EXIT_SUCCESS;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-a-factorial/.
using System;
/// <summary>The factorial of a non-negative integer.</summary>
public static class Factorial
{
/// <summary>Returns n!. The checked multiplication throws OverflowException above 20!.</summary>
public static long Compute(long n)
{
ArgumentOutOfRangeException.ThrowIfNegative(n);
long f = 1;
for (long i = 2; i <= n; i++)
{
f = checked(f * i);
}
return f;
}
}
FactorialTests.cs 34 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-a-factorial/.
using System;
using Xunit;
public sealed class FactorialTests
{
public static TheoryData<string, long, long> Cases => new()
{
{ "five", 5, 120 },
{ "ten", 10, 3628800 },
{ "zero", 0, 1 },
{ "one", 1, 1 },
{ "largest-32-bit", 12, 479001600 },
{ "beyond-32-bit", 13, 6227020800 },
{ "largest-64-bit", 20, 2432902008176640000 },
};
[Theory]
[MemberData(nameof(Cases))]
public void Compute(string name, long n, long want)
{
Assert.NotNull(name);
Assert.Equal(want, Factorial.Compute(n));
}
[Fact]
public void OverflowThrows()
{
Assert.Throws<OverflowException>(() => Factorial.Compute(21));
Assert.Throws<ArgumentOutOfRangeException>(() => Factorial.Compute(-1));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-a-factorial/.
/** Returns n! as a BigInt for a non-negative BigInt n. */
export function factorial(n) {
if (n < 0n) {
throw new RangeError("n is negative");
}
let f = 1n;
for (let i = 2n; i <= n; i++) {
f *= i;
}
return f;
}
factorial.test.js 27 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-a-factorial/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { factorial } from "./factorial.js";
const cases = [
["five", 5n, 120n],
["ten", 10n, 3628800n],
["zero", 0n, 1n],
["one", 1n, 1n],
["largest-32-bit", 12n, 479001600n],
["beyond-32-bit", 13n, 6227020800n],
["largest-64-bit", 20n, 2432902008176640000n],
];
for (const [name, n, want] of cases) {
test(name, () => {
assert.equal(factorial(n), want);
});
}
test("negative", () => {
assert.throws(() => factorial(-1n), RangeError);
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-a-factorial/.
/** Returns n! as a bigint for a non-negative bigint n. */
export function factorial(n: bigint): bigint {
if (n < 0n) {
throw new RangeError("n is negative");
}
let f = 1n;
for (let i = 2n; i <= n; i++) {
f *= i;
}
return f;
}
factorial.test.ts 27 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-a-factorial/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { factorial } from "./factorial.ts";
const cases: [string, bigint, bigint][] = [
["five", 5n, 120n],
["ten", 10n, 3628800n],
["zero", 0n, 1n],
["one", 1n, 1n],
["largest-32-bit", 12n, 479001600n],
["beyond-32-bit", 13n, 6227020800n],
["largest-64-bit", 20n, 2432902008176640000n],
];
for (const [name, n, want] of cases) {
test(name, () => {
assert.equal(factorial(n), want);
});
}
test("negative", () => {
assert.throws(() => factorial(-1n), RangeError);
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-a-factorial/.
// Package factorial computes the factorial of a non-negative integer.
package factorial
import "math/big"
// Factorial returns n! for 0 <= n <= 20. Above 20, the product wraps around.
func Factorial(n int64) int64 {
f := int64(1)
for i := int64(2); i <= n; i++ {
f *= i
}
return f
}
// Big returns n! as a big.Int, with no size limit.
func Big(n int64) *big.Int {
return new(big.Int).MulRange(1, n)
}
factorial_test.go 39 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-a-factorial/.
package factorial
import "testing"
var cases = []struct {
name string
n int64
want int64
}{
{"five", 5, 120},
{"ten", 10, 3628800},
{"zero", 0, 1},
{"one", 1, 1},
{"largest-32-bit", 12, 479001600},
{"beyond-32-bit", 13, 6227020800},
{"largest-64-bit", 20, 2432902008176640000},
}
func TestFactorial(t *testing.T) {
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
if got := Factorial(c.n); got != c.want {
t.Fatalf("Factorial(%d) = %d, want %d", c.n, got, c.want)
}
if got := Big(c.n); !got.IsInt64() || got.Int64() != c.want {
t.Fatalf("Big(%d) = %v", c.n, got)
}
})
}
}
func TestBig(t *testing.T) {
if got := Big(21).String(); got != "51090942171709440000" {
t.Fatalf("Big(21) = %s", got)
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-a-factorial/.
/// Returns n! for 0 <= n <= 20. The empty range 1..=0 gives 1.
pub fn factorial(n: i64) -> i64 {
assert!(n >= 0, "n is negative");
(1..=n).product()
}
/// Returns None if n! does not fit in an i64.
pub fn checked_factorial(n: i64) -> Option<i64> {
(1..=n).try_fold(1i64, |f, i| f.checked_mul(i))
}
tests/factorial_test.rs 27 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-a-factorial/.
use algo_compute_a_factorial::{checked_factorial, factorial};
const CASES: &[(&str, i64, i64)] = &[
("five", 5, 120),
("ten", 10, 3628800),
("zero", 0, 1),
("one", 1, 1),
("largest-32-bit", 12, 479001600),
("beyond-32-bit", 13, 6227020800),
("largest-64-bit", 20, 2432902008176640000),
];
#[test]
fn cases() {
for &(name, n, want) in CASES {
assert_eq!(factorial(n), want, "{name}");
assert_eq!(checked_factorial(n), Some(want), "{name}");
}
}
#[test]
fn overflow_is_none() {
assert_eq!(checked_factorial(21), None);
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compute-a-factorial/.
# factorial N
# Prints N! for 0 <= N <= 20. Bash arithmetic does not check for overflow.
# Returns 1 if N is negative.
factorial() {
local n=$1 f=1 i
if ((n < 0)); then
return 1
fi
for ((i = 2; i <= n; i++)); do
f=$((f * i))
done
printf '%s\n' "$f"
}
test_factorial.bats 17 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compute-a-factorial/.
setup() {
source "$BATS_TEST_DIRNAME/factorial.sh"
}
@test "five" { run factorial 5; [ "$output" = "120" ]; }
@test "ten" { run factorial 10; [ "$output" = "3628800" ]; }
@test "zero" { run factorial 0; [ "$output" = "1" ]; }
@test "one" { run factorial 1; [ "$output" = "1" ]; }
@test "largest-32-bit" { run factorial 12; [ "$output" = "479001600" ]; }
@test "beyond-32-bit" { run factorial 13; [ "$output" = "6227020800" ]; }
@test "largest-64-bit" { run factorial 20; [ "$output" = "2432902008176640000" ]; }
@test "negative-fails" { run factorial -1; [ "$status" -eq 1 ]; }
References
- Rosetta Code, Factorial (task text, from acmeism/RosettaCodeData), task text
- Wikipedia, Factorial, Definition; Growth and approximation; Continuous interpolation and non-integer generalization
- The Python Standard Library, math.integer, factorial
- Java SE 25 API, Class Math, multiplyExact(long, long)
- Go standard library, math/big, func (*Int) MulRange
- The Python Standard Library, math, gamma
- cppreference.com, tgamma (C), Return value
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag GJYVDD Edit this page History Report an error Markdown