For any positive integer N, the factorial is calculated by multiplying together all integers up to and including N, that is,
The first few factorials are:N! = 1 × 2 × 3 × . . . × (N - 1) × N
0! = 1 note! 1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 6! = 720 7! = 5040 8! = 40320 9! = 362880
Factorials start out reasonably small but grow extremely rapidly. A famous approximation, named after the Scottish mathematician James Stirling (1692-1770), can be used in a computer to approximate N factorial.
To calculate an exact value, there is no shortcut formula; all of the multiplications must be done explicitly. The program shown below will calculate the exact value of N! for large values of N.N! ≈ (2·π·N)1/2(N/e)N
const SIZE : int := 200
type iarray : array[SIZE] of int
program
var a : iarray
var b : int
put "Enter an integer (> 0) "...
get b
if not bigfact( b, a ) then
put "fail"
end if
end program
function bigfact( n : int, var a : iarray ) : boolean
var c, d, i, j, x : int
var p : real
assert n > 0
for i := 1...SIZE do % init accumulator array
a[i] := 0
end for
p := 0.0 % count number of digits needed
for i := 2...n do
p := p + log10(i) % log(b!) = log(1)+log(2)+log(3)+...
end for
d := floor( p + 1 ) % log(9999) = 3.9999566 so need 4 digits
if d > SIZE then
put "need array size >= ", d
return false
end if
a[1] := 1 % compute factorial
c := 0 % init carry
for i:= 1...n do % 1*2*3*4...
for j := 1...d do % do big multiply for each digit
x := a[j]*i + c
a[j] := x mod 10
c := x div 10
end for
end for
put n, "! = "... % print results
for decreasing i:= d...1 do
put a[i]...
end for
return true
end function