Factorial of a number without using multiplication
Given a positive number N, the task is to calculate the factorial of N without using the multiplication operator.
Input: N = 5
Input: N = 7
A*B=A+A+A+A...B times. This observation can be used as follows: 5!=5*4*3*2*1 =(5+5+5+5)*3*2*1 =(20+20+20)*2*1 =60+60 =120
Approach: The problem can be solved using the concept of nested loops. Instead of using the multiplication operator, the answer can be manually calculated by using another loop. Follow the steps below to solve the problem:
- Initialize a variable ans to N.
- Iterate from N-1 to 1, using the variable i, and do the following:
- Initialize a variable sum to 0.
- Iterate from 0 to i-1, using the variable j, and add ans to sum
- Add sum to ans.
- Print ans.
Below is the implementation of the above approach
Time Complexity: O(N2)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.