tb90
August 30, 2013, 10:42am
1
Problem Factorial - link to problem
Here is my solution:-
#include<stdio.h>
#include <stdlib.h>
int main()
{
int noofinputs;
int i;
int div= 5;
int zero = 0;
scanf("%d",&noofinputs);
int *no = malloc(noofinputs*sizeof(int));
for(i=0;i<noofinputs;i++)
{
scanf("%d",&no[i]);
}
for(i=0;i<noofinputs;i++)
{
if(no[i]==5)
{
printf("1\n");
}
else if(no[i]<5)
{
printf("0\n");
}
else
{
while(div<no[i])
{
zero = zero + (no[i]/div);
div = 5*div;
}
printf("%d\n",zero);
div = 5;
zero = 0;
}
}
return 0;
}
1)The condition in the loop should be : while(div<=no[i]). i.e less than or equal to.
2)no need to take all inputs in array. take input and output the answer and then proceed to next case.
I guess that should work. Here is accepted code using array and also another version of your code without using array .
1 Like
Hello,
Even If you change the condition while(div<=no[i]), it won’t give the correct output.
I have modified your code as below…
#include<stdio.h>
#include <stdlib.h>
int main()
{
int noofinputs;
int i;
int div= 120;
int zero = 0;
scanf("%d",&noofinputs);
int *no = malloc(noofinputs*sizeof(int));
for(i=0;i<noofinputs;i++)
{
scanf("%d",&no[i]);
}
for(i=0;i<noofinputs;i++)
{
if(no[i]==5)
{
printf("1\n");
}
else if(no[i]<5)
{
printf("0\n");
}
else
{
while(no[i]>5)
{
//zero = zero + (no[i]/div);
div = div*no[i];
no[i]--;
}
printf("%d\n",div);
div = 120;
// zero = 0;
}
}
getch();
return 0;
}
It is compiling and returning the required answer… Thank you…
He is reseting div and zero in loop and int is big enough for numbers up to 10^9.
1 Like
@betlista didnt notice. my bad!!
tb90
August 30, 2013, 4:18pm
6
@kcahdog , @betlista im sure we can do it without storing in an array as u said, but i wanna know why is my code wrong? Like whats the mistake in this code?
And why you skipped 1.) ? Your code for input
1
25
returns 5, but 25! is 15511210043330985984000000
tb90
August 30, 2013, 4:44pm
8
oh Yes it should be <= , thankyou @betlista any thing else u feel is wrong?
just try to submit it It seems fine to me. Maybe those test if(no[i]==5)
, if(no[i]<5)
are useless but it’s not a problem
tb90
August 30, 2013, 4:53pm
10
They finally accepted it.
Congrats, but I didn’t find the bug, @kcahdog did You should up vote and/or accept his answer
@tb90 your code got accepted only by changing the condition to “<=”. that was the only mistake in your code.
@amanachiever Here is the code where “<” is changed to “<=”. it got accepted!! :- CodeChef: Practical coding for everyone
Changing
while(div<no[i])
{
zero = zero + (no[i]/div);
div = 5*div;
}
to
while(no[i]>5)
{
div = div*no[i];
no[i]--;
}
is not the same as changing <
to <=
or you think so?