I wrote some c++ code to find the factorial of int n. As factorial can be a very large number, so I decided to store the number in a vector. But My Code is not working as expected. Some please point out the bug and guide me. I lowkey feel like I messed with pointers. And Please suggest if there is a more optimal approach for this. Thanks Community.
The Code:
#include <iostream>
#include <vector>
#include <algorithm>
using std::cout;
using std::endl;
using Digits = std::vector<int>;
//define the length of the array, should be the maximum number of digits in the factorial(n)
#define MAX 20
void multiply(int x,Digits res,int res_size){
int carry=0;
for(int i=0;i<res_size;i++){
int prod=carry+ x*res[i];
res[i] = prod%10;
carry = prod/10;
}
while(carry){
res[res_size] = carry%10;
carry/=10;
(res_size)++;
}
}
Digits factorial(int n){
Digits res(MAX);
res[0] = 1;
int res_size=1;
for(int i=2;i<=n;i++){
multiply(i,res,res_size);
}
reverse(res.begin(),res.end());
return res;
}
int main(){
for(auto i: factorial(20)){
cout << i;
}cout << endl;
return 0;
}
The Output:
10000000000000000000
[Done] exited with code=0 in 3.204 seconds