编程之美2.2 不要被阶乘吓倒

//题目1: 求n的阶乘结果中末尾有多少个0
public class Main {

	public static void main(String[] args) {
		System.out.println(getZeroCount1(25));
		System.out.println(getZeroCount2(25));
	}

	// 解法1: 求1~n中能被5求余的数字个数,以及每个数字求余次数的总和,即为结果	O(nlog5n)
	// 因为每有一个5,阶乘的结果就会多一个0(5*2=10)
	public static int getZeroCount1(int n) {
		int result = 0;
		for (int i = 1; i <= n; i++) {
			int j = i;
			while (j % 5 == 0) {
				result++;
				j = j / 5;
			}
		}
		return result;
	}

	// 解法2: 使用n/5的方式,n/5表示不大于n的数中5的倍数贡献一个5的数量,表示不大于n的树中25的倍数再贡献一个5的数量	O(log5n)
	public static int getZeroCount2(int n) {
		int result = 0;
		while (n != 0) {
			result = result+n/5;
			n = n/5;
		}
		return result;
	}

}

//题目2: 求n的阶乘结果的二进制表示中最低一位1的位置
//如n = 3,n! = 6= 110,则最低位1的位置为2
public class Main {

	public static void main(String[] args) {
		System.out.println(getZeroCount1(4));
		System.out.println(getZeroCount2(4));
	}

	// 解法1: 相当于求n!中质因数2的个数	O(nlog2n)
	// 因为每有一个2,阶乘的结果最后的1就会左移一位
	public static int getZeroCount1(int n) {
		int result = 0;
		for (int i = 1; i <= n; i++) {
			int j = i;
			while (j % 2 == 0) {
				result++;
				j = j / 2;
			}
		}
		return result+1;
	}

	// 解法2: 使用n/2的方式,n/2表示不大于n的数中2的倍数贡献一个2的数量,n/4表示不大于n的树中4的倍数再贡献一个4的数量 O(log2n)
	public static int getZeroCount2(int n) {
		int result = 0;
		while (n != 0) {
			result = result + n / 2;
			n = n / 2;
		}
		return result+1;
	}
	
	//解法3: n!中质因数2的个数等于n减去n的二进制表示中1的个数

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值