简体   繁体   中英

trailing zeros in a factorial.when i run it on ideone.com i'm getting runtime error with infinite output. Even SPOJ is also not accepting

 #include <iostream>
    #include <cmath>
    using namespace std;

    int func(int n){
        int count=0;
        float t=log(n)*0.621;
        int k=(int)t;
        int temp;
        for(int i=1;i<=k;i++){
            int power=1;
            for(int j=0;j<i;j++){
                power=power*5;
            }
            temp=(int)(n/power);
            count=count+temp;
        }
        return count;
    }

    int main(){
        int t;
        cin>>t;
        for (int i=0;i<t;i++){
            int n;
            cin>>n;
            cout<<func(n)<<'\n';
        }
    return 0;
    }

I'm getting correct answer for few test cases.The error i'm getting in ideone is Runtime error time: 0 memory: 3100 signal:25

33628713 33628713 33628713 33628713 33628713 33628713

with infinite output when no input is given

I don't know what the logarithm is doing in your code. You somehow use it to determine when to stop dividing by powers of 5. It appears to be an approximation, and if you only get correct answers sometimes, then I expect that the approximation's inaccuracy is working against you.

You don't need the logarithm. You could simply stop the loop when you determine that there are no more factors of powers of 5 remaining. Think about how you could detect that using the values you've already calculated.

You don't need to approximate anything. A page at Purplemath explains and demonstrates how to calculate the number of trailing zeroes in a factorial number. Read the article and see whether you can recognize how the technique described there corresponds to parts of your code, and also notice how there are no logarithms involved on that page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM