4 Factorial Computation
4 Factorial Computation
POTLURI SIDDHARTHA
INSTITUTE OF TECHNOLOGY
PROBLEM SOLVING
TECHNIQUES
By
B. Vinay Kumar
Assistant Professor
Dept. of CSE
PVPSIT, Kanuru.
Algorithm 2.4 PVPSIT (Autonomous)
FACTORIAL COMPUTATION
• Problem
• Given a number n, compute n factorial (written as n!) where n >= 0.
• Algorithm development
• We can start the development of this algorithm by examining the definition of
n!.
• We are given that
n! = 1 x 2 x 3 x … x (n-1) x n for n >= 1
• and by definition
0! = 1
• In formulating our design we need to keep in mind that the computer’s
arithmetic unit can only multiply two numbers at a time.
Problem Solving Techniques B. Vinay Kumar Monday, June 9, 2025
PVPSIT (Autonomous)
• Using this definition we can write the first few factorials as:
• From step (2) onwards we are actually repeating the same process over and
over.
• For the general (i+1)th step we have
p := p*i (i+1)
• The general step can be placed in a loop to iteratively generate n!.
• The instance where n=0 is a special case which must be accounted for directly
by the assignment
p := 1 (by definition of 0!)
• The central part of the algorithm for computing n! therefore involves a special
initial step followed by n iterative steps.
1. Treat 0! As a special case (p := 1).
2. Build each of the n remaining products p from its predecessor by an
iterative process.
Write
3.Problem out the value of n factorial.
Solving Techniques B. Vinay Kumar Monday, June 9, 2025
PVPSIT (Autonomous)
• Pseudo-code
• begin
read (n)
factor := 1
for i := 1 to n do
factor := factor * i
nfactorial := factor
write (nfactorial)
•end
• Notes on design
• The algorithm uses n multiplications to compute n!.
• There is in fact a more efficient algorithm that computes n! in
essentially log2n steps.
• The idea of accumulating products is very similar to that of
accumulating sums.
• Applications
• Probability, statistical and mathematical computations.
Solutions
2.4.1 For a given number n, design an algorithm to compute 1/n!.
• Algorithm description
1. Establish n, the factorial required where n >= 0.
2. Set product p for 0! (special case). Also set product count to zero.
3. While less than n products have been calculated repeatedly do
(a) increment product count.
(b) compute ith product p by multiplying i by the most recent product.
4. Calculate result 1/n!.
5. Write out 1/n!.
• Pseudo-code
• begin
read (n)
factor := 1
for i := 1 to n do
factor := factor * i
nfactorial := factor
write out (1/nfactorial)
•end
• Pseudo-code
• begin
read (n)
i := 2
while n > 1 do
begin
n := n / i
i := i + 1
end
Ii n < 1 write out n is not a factorial number
else write out n is a factorial number.
•end