Hello, can I do this in pascal: […]
Yes, but there is no built-in support for that, you’ll need—as you already saw—either implement it on your own, or use some sort of library. I haven’t found nothing in the
math unit.
with gmp library you can calculate big number and you have a factorial fonction :
Yes, I like that (using
GMP). If you like you can also use them good old
logarithms, yet it loses precision. On a 64-bit system with an 80-bit FPU, 20! is “already” slightly off.
program factorialFun(input, output, stdErr);
function factorialLn(n: ALUUInt): valReal;
begin
factorialLn := 0.0;
for n := n downto 2 do
begin
factorialLn := factorialLn + ln(n);
end;
end;
var
n: ALUUInt;
begin
for n := 0 to 20 do
begin
writeLn(n:2, ' : ', round(exp(factorialLn(n))):20);
end;
end.
Yet this allows you (to some degree) calculate (or rather
approximate) and use factorials that are
too large for
ALUUInt. Example:
program lottery(input, output, stdErr);
{ function factorialLn as defined above }
function binomialCoefficient(n, k: ALUUint): ALUUint;
begin
binomialCoefficient := round(exp(
factorialLn(n) -
(factorialLn(k) + factorialLn(n - k))
));
end;
begin
writeLn('Germany:':20, binomialCoefficient(49, 6):20);
writeLn('US (MM):':20, binomialCoefficient(75, 5):20);
end.
NB: There are better algorithms to calculate the binomial coefficient.