Calculating n! using vector

#include <cstdio>
#include<iostream>
#include <vector>

using namespace std;
int main()
{

//declaration
int i,n,num,val,temp,j,l;
vector< vector<int> > V;
vector<int> v;


//calculation part
v.push_back(1);V.push_back(v);v.clear();
for(i=1;i<=100;i++)
{
temp = 0;v.clear();
l = V[i-1].size();
for(j=0;j<l;j++)
{
val = V[i-1][j]*i+temp;
v.push_back(val%10);
temp = val/10;
}
if(temp != 0) v.push_back(temp);
V.push_back(v);
}


//input output
scanf("%d",&n);
while(n--)
{
scanf("%d",&i);
for(j=V[i].size()-1;j>=0;j--)
cout<<V[i][j];
printf("\n");
}
return 0;
}

well the code gives correct answer till 33! and starts printing garbage after that i dont get why plz help1
Last edited on
Just guessing, as it seems your code is far too complex for just calculating a factorial but perhaps 33! is too big for an int to hold? Though if that's the case you should be failing much earlier than that...
Your problem is that you aren't managing the carry correctly, because a single multiplication can result
in more than one digit of carry. You are assuming that at each multiplication step, there can be only one
digit of carry, but that isn't true. For example, if the element in the vector is 8 and i == 33, then 33 * 8 = 264.
You correctly put 4 in the vector, but then your next carry is 26. The fix is easy. I'll let you figure it out, but
I verified that it works.

This took me longer than it should have because your code is very poorly formatted and you used
meaningless variable names.
Topic archived. No new replies allowed.