12,557,990 members (50,257 online)
Technical Blog
alternative version

7.7K views
1 bookmarked
Posted

# Calculating the factorial of a number in Delphi: Recursive and iterative methods

, 28 Dec 2012 CPOL
 Rate this:
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.

### Iterative definition

For both the above definitions we have that

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:

```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:

```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).

## Share

My name is Yanniel Alvarez Alfonso. I was born in San Antonio de los Baños, Havana Province, Cuba on October 24th, 1982.

I majored in Information Technology Engineering at José Antonio Echeverría Polytechnic Institute (CUJAE) in Havana City, Cuba (July 2006). After that, I got a Masters Degree in Applied Computer Science at the same University (May 2009).

I used to work as a professor of Information Technology at CUJAE. Right now, I work as a Software Developer in Toronto, Canada. I moved to Canada under the Skilled Worker Program on February 26th, 2010.

This is my personal blog: Yanniel's notes; in which I write about miscellaneous topics.

The link at the end of this sentence compiles an index of all the articles I have written so far about Delphi Programming.

 Pro