快速幂函数优化1~n 的阶乘java实现
时间: 2023-10-28 21:05:04 浏览: 86
java代码-n的阶乘用n!表示
public class Factorial {
public static int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
}
int result = 1;
for (int i = 2; i <= n; i++) {
result *= i;
}
return result;
}
public static int factorialWithQuickPower(int n) {
if (n == 0 || n == 1) {
return 1;
}
int result = 1;
int base = 2;
while (n > 1) {
if (n % 2 == 1) {
result = result * base;
}
base = base * base;
n = n / 2;
}
return result * base;
}
public static void main(String[] args) {
int n = 10;
System.out.println(factorial(n)); // 3628800
System.out.println(factorialWithQuickPower(n)); // 3628800
}
}
阅读全文