n! 多少个0

本文介绍了一种计算阶乘中尾随零数量的方法。通过三种不同的算法实现,分别是逐个数字检查、逐减计数以及高效递归除法。这些方法能够帮助理解如何有效地找出阶乘结果中末尾零的数量。
/**
 * n! 多少个0
 * 实际就是5的个数
 */
public class Zero {
	
	public static int count(int n){
		if(n < 1){
			return -1;
		}
		int count = 0;
		for(int i=1; i<=n; i++){
			int m = i;
			while(m%5 == 0){
				count++;
				m = m/5;
			}
		}
		return count;
	}
	
	public static int count2(int n){
		if(n < 1){
			return -1;
		}
		int count = 0;
		
		while(n>0){
			int m = n;
			while(m%5 == 0){
				count++;
				m = m/5;
			}
			n--;
		}
		return count;
	}
	
	public static int count3(int n){
		if(n < 1){
			return -1;
		}
		int count = 0;
		while(n > 0){
			count += n/5;
			n = n/5;
		}
		return count;
	}
	
	public static long by(int n){
		long m = 1;
		while(n>0){
			n--;
			m *= (n+1)*n;
			n--;
		}
		
		return m;
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		int count = Zero.count(10);
		int count2 = Zero.count2(10);
		int count3 = Zero.count2(10);
		long number = Zero.by(10);
		System.out.println(number);
		System.out.println(count);
		System.out.println(count2);
		System.out.println(count3);

	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值