Challenge - Factorial Challenge Solution

Factorial Challenge Solution

The trick here is to realize that the limiting case is the number of times five will be a factor of X!, as 5*2 = 10, and any time the number is multiplied by 10, there will be an additional trailing zero. Due to the abundance of even numbers, there are plenty of spare twos that are factors of any number. The trick is that the number of trailing zeros in X! is the number of times five divides into the number, plus the number of times 25 divides into the number, plus the number of times 125 divides into the number, and so forth. (25 is 5*5, so when five is divided into the number, that still leaves a single 5 remaining as a factor.)

Here is one way to code it:

#include <iostream>

using namespace std;

int main()
	int factorialnumber = 0;
	cout<<"Please enter a number: ";
	int zero_count = 0;
	for(int five_factor=5; 
		zero_count += factorialnumber/five_factor;
	cout<<"Trailing zeros of "<<factorialnumber;
	cout<<"! is "<<zero_count<<endl;

Download Source

Many other solutions exist! If yours doesn't match the key, but it still works, let us know and we'll upload it as an alternative answer.

Alternate Methods

A slightly cleaner solution submitted by James Rouzier