user1194497
user1194497

Reputation: 45

Trailing zeroes of Factorial, Runtime error in C?

#include<stdio.h>

int main()
{
    long ctr[100000],i;
    float j;
    long d[100000],T,h,o;

    scanf("%ld",T);
    printf("\n");

    for(i=0; i<T; i++)
    {
        scanf("%ld",d[i]);
        printf("\n");

        for(h=d[i]; h<=0; h--)
        {
            j=h%10;
            if(j==5)
            {
                ctr[i]++;
            }
        }
    }
    for(o=0; o<=i; o++)
    {
        printf("%ld\n",o);
    }
    return 0;
}

It's a program to find the number of trailing zeros of a factorial of a group of "T" numbers, input by the user.

What I have done is to divide each number by 10 and test if the number is 5. Then I decrement the number by 1 until it reaches 0. Each pair of 5*4 contributes one trailing 0.

Is the program consuming too much memory or is there another runtime error? This program is giving a runtime error, can anyone help?

Upvotes: 0

Views: 385

Answers (3)

Alex Lockwood
Alex Lockwood

Reputation: 83311

The loop is going infinity. Ensure that the count is not going negative or else you'll have a runtime error.

Upvotes: 0

ChinoCarloSedilla
ChinoCarloSedilla

Reputation: 90

Hmm... This loop looks like the loop is going infinity.

for(h=d[i]; h<=0; h--)

Thus giving you a runtime error... Because the count is going negative, and your loops condition says continue until the value reaches less than or equal to zero, but it seems like, your value would never reach zero.

And for the scanf function, don't forget to use the & sign. Like this:

scanf("%ld", &sampleVariable);

That's the solution for your runtime error. :)


And also maybe you should use High Precision Variables, I think you need a higher precision more than the double datatype because you'll be dealing with huge amount of numbers.

See here for added info: http://www.nongnu.org/hpalib/

Upvotes: 0

unwind
unwind

Reputation: 400109

A couple of observations:

  • long[100000] requires 400,000 bytes of stack assuming long is plain old 32 bits, 800,000 bytes if long is 64-bit. You have two such arrays, which might make your program hit operating system stack size limits.
  • The scanf() function requires pointers to where to store values it's reading in. You're not giving it pointers. As Paul R said in a comment.
  • Assuming positive numbers are input, the loop for(h=d[i]; h<=0; h--) will never run its body.

Upvotes: 3

Related Questions