-
-
Notifications
You must be signed in to change notification settings - Fork 7.7k
Description
Detailed description
for example if we want to calculate the factorial of 5 we can simply calculate it as 120 and 120 can be stored in integer data type in cpp but for 100 the output cannot be stored even in long long int.
Input: 100
Output: 933262154439441526816992388562667004-
907159682643816214685929638952175999-
932299156089414639761565182862536979-
208272237582511852109168640000000000-
00000000000000
Context
when we write a program for calculating factorial by our brute force approach which is okay for small numbers but for large numbers it takes lot of time to give output on the screen and sometimes the becomes the output number is out of range of the datatypes available in programming language.
Possible implementation
Possible implementation:
1 Create an array res[] of MAX size where MAX is a number of maximum digits in output.
2 Initialize value stored in res[] as 1 and initialize res_size (size of ‘res[]’) as 1.
3 Multiply x with res[] and update res[] and res_size to store the multiplication result for all the numbers from x = 2 to n. To multiply a number x with the number stored in res[], one by one multiply x with every digit of res[].
4 To implement multiply function perform the following steps:
4.1 Initialize carry as 0.
4.2 Do following for i = 0 to res_size – 1
4.3 Find value of res[i] * x + carry. Let this value be prod.
4.5 Update res[i] by storing the last digit of prod in it.
4.6 Update carry by storing the remaining digits in carry.
5 Put all digits of carry in res[] and increase res_size by the number of digits in carry.
Additional information
No response