32. The number of trailing zeros in N! – solution
The algorithm – description
- In the first part of the task, read N and then calculate N! in a loop.
- N!=N*(N-1)*(N-2)*...*1
- Form the product with the factor T, which is set to N before the loop and then decreased by 1 in each following step.
- In the second part of the task, the starting number is the previously calculated value of the factorial F
- This value is divided by 10 in a while loop as long as F is divisible by 10
- The number of loop steps is the number of trailing zeros
The algorithm – flowchart
Figure 1: The number of trailing zeros in N! – flowchart. The labels are in Serbian: „Zadatak 47“ = Task 47, „Početak“ = Start, „Kraj“ = End; br is the counter of zeros.
The solution in the C programming language
#include <stdio.h>
#include <stdlib.h>
/*
Write a program that finds the number of trailing zeros in N!
*/
int main()
{
int N, count = 0, F = 1, T;
printf("N=?\n");
scanf("%d", &N);
T = N; // T = N = 5
while (T > 0) {
F = F * T; // F = 1*5, F = 5*4, ...
T--;
}
printf("N!=%d\n", F); // F = 120
while (F % 10 == 0) {
F = F / 10;
count++;
}
printf("The number of trailing zeros is %d\n", count);
return 0;
}
N=?
5
N!=120
The number of trailing zeros is 1
Figure 2: The number of trailing zeros in N! – solution
After reading the number N, the factorial of that number is calculated in a while loop by forming a product whose first factor is T = N, and each following factor is smaller by 1 (T--). The last factor is 1.The number of trailing zeros is found with another while loop, which checks whether the starting number, equal to the factorial F calculated in the previous part, is divisible by 10. Inside the loop one zero is "removed" from the current number by dividing it by 10. The number of loop steps is the number of trailing zeros.
Note:
- The type
intstores N! exactly only up to N = 12. For N = 13 the program prints 0 zeros instead of 2, and for N = 34 the value of F becomes 0, so the second loop never ends. - A better way, without calculating N!: there are as many trailing zeros as there are factors of 5 in the numbers from 1 to N:
count = N/5 + N/25 + N/125 + ...
| Previous |< Loops – basic examples |
Next Nested loops – examples>| |
