[05.12.22] Coding test

Juyeon.it·2022년 5월 12일
0

Coding test

목록 보기
31/32

Number of trailing zeros of N!

Description

Write a program that will calculate the number of trailing zeros in a factorial of a given number.
N! = 1 2 3 ... N
Be careful 1000! has 2568 digits...
For more info, see: http://mathworld.wolfram.com/Factorial.html
Examples
zeros(6) = 1
// 6! = 1 2 3 4 5 * 6 = 720 --> 1 trailing zero
zeros(12) = 2
// 12! = 479001600 --> 2 trailing zeros
Hint: You're not meant to calculate the factorial. Find another way to find the number of zeros.

Other Solution

function zeros (n) {
  let result = 0;
  
  while(n > 0){
    n = Math.floor(n/5);
    result += n
  }
  
  return result;
}

Comments

5 comes from the prime dividers To have a trailing zero, the number have to be divided by 10. Same as divided by 2 and 5.
In a factorial computation, there will be a lot more of 2 that 5, so we count how many times the final number can be divided by 5 and we have the number of times it's dividable by 10.

source: wikipedia_Trailing zero

0개의 댓글

관련 채용 정보