//题目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的个数
}