i have run this code in my compiler it work fine till its upper limit as per given in the question.
But codechef gives it wrong every time.
please any body help.
the link to the question given below
enter code here
#include<stdio.h>
int fact(int p[],int q,int t){
t--;
int i,temp=0,x;
for(i=0;i<q;i++){
x=p[i]*t+temp;
p[i]=x%10;
temp=x/10;
}
while(temp>0){
q++;
p[q-1]=temp%10;
temp/=10;
}
if(t>1){
fact(p,q,t);
}
else{
printf("\n");
for(i=q-1;i>=0;i–){
printf("%d",p[i]);
}
}
}
int count(int x){
int p[200],t=x,q=0,i,j;
if(x==1){
printf("%d",x);
}
else{
for(i=0;t>0;i++){
p[i]=t%10;
t/=10;
q++;
}
fact(p,q,x);
}
}
int main(){
int t,i,j,a[100];
scanf("%d",&t);
for(i=0;i<t;i++){
scanf("%d",&a[i]);
}
for(i=0;i<t;i++){
count(a[i]);
}
}
1 Like
I see you fixed your problem with print statements. congrats!
The best way to deal with factorials is, I think, by using dynamic programming. And Python has a solution. If t is the number of test cases, and you input t integers, then the following code suffices in Python.
t=int(raw_input())
max=0
L=[]
for i in range(t):
n=int(raw_input())
if max<n: n=max
L.append(n)
dp=[0,0]
for i in range(2,max+1):
dp.append(dp[i-1]*i)
for i in L:
print dp[i]
2 Likes
what’s wrong with my code?? Please help!!
#include<stdio.h>
int main(){
int j,i,num,times;
long int f;
scanf("%d",×);
for(j=1; j<=times; j++){
scanf("%d",&num);
f = i =1;
while(i<=num){
f=f*i;
i++;
}
printf("%ld\n",f);
}
return 0;
}
@shubh6997 The problem with your code is that we have to find till 100! and long int does not hold upto 100! nor any inbuilt data type in C++ . So the best way is to use the method prescribed in the blog : https://blog.codechef.com/2009/07/02/tutorial-for-small-factorials/
or even simpler use bigint and store the values in an array and just access them . There are many good bigint libraries available.