求n的阶乘中尾数有多少个0

给出一个数n,求1*2*3*...*n的结果中,尾数有多少个0

这道题是一个老友跟我说是面试的题目,现在认真想一下,好像挺简单的^_^

分析:求几个数的乘积,如果尾数为零,那么这几个数要满足的条件是:1)这几个数中有偶数;2)这几个数中包含5(包括可以分解出来的,比如整十, 2n*5)

e.g:

10的阶乘,1-10这几个数,里面包含偶数,也包含了两个5(5,2*5),尾数有两个0;1-15中,包含偶数和3个5(5, 2*5, 3*5),尾数有3个0

======>这一堆数中,包含了多少个5,尾数就有多少个0(因为是连续的,5的前面必定有2、4这两个偶数,所以乘积的末尾肯定有一个0)

-----------------------------------------

所以求解就变得很简单了。

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n ;
        while((n =sc.nextInt() ) != 0) {
            int res = countOfZero(n);
            System.out.println(res);
        }    
    }
    
    public static int countOfZero(int k) {
        int count = 0;
        for(int i = 1; i <= k; i++) {
            if(i % 5 == 0) {
                int temp = i;
                while(temp % 5 == 0) {
                    count++;
                    temp /= 5;
                }
            }
        }
        return count;
    }
}

 

posted on 2020-07-24 09:05  Jain_Shaw  阅读(304)  评论(0编辑  收藏  举报

导航