factorial in cpp of big numbers

Solutions on MaxInterview for factorial in cpp of big numbers by the best coders in the world

showing results for - "factorial in cpp of big numbers"
Oskar
31 Feb 2020
1// C++ program to compute factorial of big numbers 
2#include<iostream> 
3using namespace std; 
4  
5// Maximum number of digits in output 
6#define MAX 500 
7  
8int multiply(int x, int res[], int res_size); 
9  
10// This function finds factorial of large numbers 
11// and prints them 
12void factorial(int n) 
13{ 
14    int res[MAX]; 
15  
16    // Initialize result 
17    res[0] = 1; 
18    int res_size = 1; 
19  
20    // Apply simple factorial formula n! = 1 * 2 * 3 * 4...*n 
21    for (int x=2; x<=n; x++) 
22        res_size = multiply(x, res, res_size); 
23  
24    cout << "Factorial of given number is
25"; 
26    for (int i=res_size-1; i>=0; i--) 
27        cout << res[i]; 
28} 
29  
30// This function multiplies x with the number  
31// represented by res[]. 
32// res_size is size of res[] or number of digits in the  
33// number represented by res[]. This function uses simple  
34// school mathematics for multiplication. 
35// This function may value of res_size and returns the  
36// new value of res_size 
37int multiply(int x, int res[], int res_size) 
38{ 
39    int carry = 0// Initialize carry 
40  
41    // One by one multiply n with individual digits of res[] 
42    for (int i=0; i<res_size; i++) 
43    { 
44        int prod = res[i] * x + carry; 
45  
46        // Store last digit of 'prod' in res[]   
47        res[i] = prod % 10;   
48  
49        // Put rest in carry 
50        carry  = prod/10;     
51    } 
52  
53    // Put carry in res and increase result size 
54    while (carry) 
55    { 
56        res[res_size] = carry%10; 
57        carry = carry/10; 
58        res_size++; 
59    } 
60    return res_size; 
61} 
62  
63// Driver program 
64int main() 
65{ 
66    factorial(100); 
67    return 0; 
68} 
69