HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Number of zeroes at the end of a factorial

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
factorialnumbertheendzeroes

Problem

I was working with this problem, which is to find the number of zeros at the end of any factorial.

Here's my solution:

#include
using namespace std;
int main(){

    int numCases,num,zeroCount=0,mulFive,temp,i=0;
    cout::max()-1000000000>numCases;
    int solutionArray[numCases];
    temp=numCases;
    while(numCases--)
    {
         zeroCount=0;
         cin>>num;
         mulFive=5;
         while(num/mulFive!=0)
         {
             zeroCount=zeroCount+ (num/mulFive);
             mulFive=mulFive*5;
         }
         solutionArray[i]=zeroCount;
         i++;
         //cout<<zeroCount;
    }
    for(int k=0;k<temp;k++)
        cout<<solutionArray[k]<<endl;

    return 0;
}


This is the most basic code that I could come up with. How should I make it more efficient using the same logic? Perhaps I should use different logic?

Solution

There is a problem with your solution for large numbers ( >= 5^13 to be exact) because mulFive=mulFive*5; will go negative as the int overflows.

To protect against this, you could do

while(num/5!=0)
 {
     zeroCount=zeroCount+ (num/5);
     num = num/5;
 }


i.e. divide the number rather than multiply the divisor, then only the size of num is a limit (2^31-1)

Code Snippets

while(num/5!=0)
 {
     zeroCount=zeroCount+ (num/5);
     num = num/5;
 }

Context

StackExchange Code Review Q#42582, answer score: 3

Revisions (0)

No revisions yet.