Click here to Skip to main content
15,881,812 members
Articles / Programming Languages / Delphi

Calculating the Factorial of a Number in Delphi: Recursive and Iterative Methods

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
28 Dec 2012CPOL 16.9K   2  
The purpose here is not the mathematical stuff, but to provide two implementations of the factorial of a number in Delphi (Object Pascal).

The factorial function can be defined in both recursive and iterative ways. Take a look at the following definitions borrowed from Wikipedia.

Recursive Definition

Factorial Recursive definition

Iterative Definition

Factorial Iterative Definition

For both the above definitions, we have that:

Zero Factorial

The purpose here is not the mathematical stuff, but to provide the implementation of such definitions in Delphi (Object Pascal).

First, I bring you one recursive implementation of the factorial function. Notice how the function calls itself, which is what the recursion really is:

Delphi
function Factorial(aNumber: Integer): Integer;
begin
  if aNumber < 0 then
    raise Exception.Create('The factorial function is not defined for negative integers.');

  Result:= 1; 
  if aNumber > 0 then
    Result:= Factorial(aNumber-1) * aNumber; 
end;

Second, I present you one iterative implementation of the factorial function. You can easily see the iteration performed in the "for" loop below:

Delphi
function Factorial(aNumber: Integer): Integer;
var
  i: Integer;
begin
  if aNumber < 0 then
    raise Exception.Create('The factorial function is not defined for negative integers.');

  Result:= 1; 
  for i:=1 to aNumber do
    Result:= Result * i; 
end;

Big-O Considerations

The recursive factorial function implemented before has a linear growth O(n), not O (n!). In addition, the iterative factorial function is also linear O(n).

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
-- There are no messages in this forum --