Reputation: 550
Given a number n, find out the number of zeroes at the end of decimal representation of n!
Input:
First line of input will contain T = number of test cases. Next T lines will each have one number n where 1<=n<=10^9. Find out number of trailing zeroes (zeroes at the end) in factorial of this number n.
Output:
There should be one line for each test case printing the number of trailing zeroes in factorial of the given number.
Sample Input
4
6
12
18
25
Sample Output
1
2
3
6
MyOutput
2
6
1
... //this indicates that the condition of entering input is not terminated and no output is produced.
MyApproach:
To calculate trailing zeros.I checked the number of 5 because if 5 is there 2 would definately be there which will make a zero at the end. So,I wrote the following code and also haven't checked the numbers are less than or equal to 4.
Below is my code:
public static void zerosCount()
{
Scanner sc=new Scanner(System.in);
int T=sc.nextInt();
for(int i=0;i<T;i++)
{
int count5=0;
int p=sc.nextInt();
while(p>=1)
{
int n=p;
while(n>=5)
{
if(n%5==0)
{
count5++;
n=n/5;
}
}
p--;
}
System.out.println(count5);
}
sc.close();
}
Why I am not able to get the correct output:
Can anyone guide me why?
Upvotes: 1
Views: 256
Reputation: 550
This is how I solved the problem with the help of Narendra and radoh
I counted the no of 5 of whatever the input comes and check the number till it is greater than or equal to 5. Took the sum if a number has more than one zero or I say more than 1 5.
Upvotes: 0
Reputation: 1338
The approach mentioned by @radoh is incomplete and will result in wrong answer for number like 100 which has 24 zeros but n/5 will get only 20.
the number of zeros depends on 5s. so if the
N = 5 then divide it by 5 which gives 1
N= 10 then divide it by 5 gives 2
N=25 then divide it by 5 and 25
N = 50 then divide it by 5 and 25 will give you 12
N = 100 then divide it by 5 25 will give you 24
so the bottom line is after every divide , do the multiply the 5 with 5 and if the result of multiplication is less than the equals to N then divide the N with result and add the zeros counter variable.
Upvotes: 2