首页 > 试题广场 >

阶乘尾零

[编程题]阶乘尾零
  • 热度指数:7527 时间限制:C/C++ 3秒,其他语言6秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解

给定一个int n,返回n的阶乘的末尾连续的零的个数。保证n为正整数。

测试样例:
5
返回:1
推荐
1、把n! 分解成若干个素数相乘,只有 2*5 才可能产生尾随零,而2 的数量多于5,所以问题转化为计算有多少个5.

2、先数一数1到n之间有几个5的倍数(数量为n/5),然后数有几个25的倍数(数量为n/25),依次类推。

 publicintgetFactorSuffixZero(intn) {      if(n<5)        return0;    intcount =0;    for(inti=5;n/i>0;i*=5)        count+=n/i;    returncount;    }

编辑于 2015-08-18 18:24:44 回复(3)
import java.util.*;

public class Factor {
    public int getFactorSuffixZero(int n) {
        // write code here
    	int count = 0;
    	int j = 0;
    	
    	for (int i = 1; i <= n; i++) {
    		j = i;
    		while (j != 0 &&j % 5 == 0) {
    			count++;
    			j = j / 5;
    		}
    	}
    	
    	return count;
    }
}

发表于 2019-12-13 19:25:14 回复(0)

//有多少对因子2和5的积就有多少0
//2多于5 求因子5的个数
import java.util.*;

public class Factor {
    public int getFactorSuffixZero(int n) {
        // write code here
        int count=0;
        for(int i=1; i<=n; i++){
            int j = i;
            while(j%5 == 0){
                count+=1;
                j/=5;
            }
        }
        return count;
    }
}

发表于 2018-03-29 17:02:17 回复(0)