what is wrong in these solution
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
int main(){
long long int T, N, i, fact;
cin >> T;
while(T--){
fact = 1;
cin >> N;
for(i = 1; i <= N; i++){
fact = fact * i;
}
cout << fact << endl;
}
}
Seeing the constraints on the value of n,
n=100 is the worst case. Factorial of 100 is 9.332622e+157 which won’t fit in long long range. The fact variable will overflow yielding wrong results.
1 Like
Then what should i have to do?
you can use these library…
#include <boost/multiprecision/cpp_int.hpp>
using namespace boost::multiprecision;
make the data type as cpp_int T,n,i,fact;
1 Like
You can also refer to this
#include <bits/stdc++.h>
using namespace std;
void multiply(int x,vector<int>&mult){
int carry=0;
for(auto it=mult.begin();it!=mult.end();it++){
int temp_product=(*it)*x+carry;
*it=temp_product%10;
carry=temp_product/10;
}
while(carry){
mult.push_back(carry%10);
carry/=10;
}
}
void factorial(int n){
vector<int>result;
result.push_back(1);
for(int i=2;i<=n;i++)
multiply(i,result);
for(auto it=result.rbegin();it!=result.rend();it++)
cout<<*it;
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int t;
cin>>t;
while(t--){
int n;
cin>>n;
factorial(n);
cout<<"\n";
}
return 0;
}
Boost library is not accepted on many sites. So, I would recommend you for string multiplication