如何找到一个非常大的数字的阶乘
how to find factorial of a really big number
我试图找出这个问题的输出,但它不起作用,当 n 达到 10^6 时,因为它需要很多时间
有什么办法可以更快找到它吗?
找到 n 的阶乘的尾随零
在哪里
1<= n <=10^6
这是我的代码:
public static void main(String[] args) {
test t=new test();
Scanner input =new Scanner(System.in);
int m=input.nextInt();
String x=t.factorial(m).toString();
int count=0;
for(int i=x.length()-1;i>0;i--){
if(x.charAt(i)=='0')
count++;
else{
i=0;
}
}
System.out.println(count);
}
BigInteger factorial(int num){
BigInteger temp = BigInteger.ONE;
for(int i=1;i<=num;i++)
temp = temp.multiply(new BigInteger(i + ""));
return temp;
}
Find the trailing zeros of factorial of n
where 1 <= n <= 10^6
结尾的零被5的因子限制。5
的倍数最多是n
是n/5
(整数除法),但这不' 以 25, 125, ....
的倍数计算重复因子。要获得这些,请将 n
除以 5 并进行递归调用。
source
这里是 Java 中的示例实现:
int trailingZerosOfFactorial(int number){
if(number == 0){
return 0;
}
int nrIntegerDividedByFive = number/5;
return nrIntegerDividedByFive + trailingZerosOfFactorial(nrIntegerDividedByFive);
}
通过这个实现,我们避免了阶乘的实际计算,这是主要的瓶颈。因此,这会在大约 1.5 秒内计算出 n = 1_000_000
(导致 249998
)。
我试图找出这个问题的输出,但它不起作用,当 n 达到 10^6 时,因为它需要很多时间 有什么办法可以更快找到它吗?
找到 n 的阶乘的尾随零 在哪里 1<= n <=10^6
这是我的代码:
public static void main(String[] args) {
test t=new test();
Scanner input =new Scanner(System.in);
int m=input.nextInt();
String x=t.factorial(m).toString();
int count=0;
for(int i=x.length()-1;i>0;i--){
if(x.charAt(i)=='0')
count++;
else{
i=0;
}
}
System.out.println(count);
}
BigInteger factorial(int num){
BigInteger temp = BigInteger.ONE;
for(int i=1;i<=num;i++)
temp = temp.multiply(new BigInteger(i + ""));
return temp;
}
Find the trailing zeros of factorial of
n
where1 <= n <= 10^6
结尾的零被5的因子限制。5
的倍数最多是n
是n/5
(整数除法),但这不' 以 25, 125, ....
的倍数计算重复因子。要获得这些,请将 n
除以 5 并进行递归调用。
source
这里是 Java 中的示例实现:
int trailingZerosOfFactorial(int number){
if(number == 0){
return 0;
}
int nrIntegerDividedByFive = number/5;
return nrIntegerDividedByFive + trailingZerosOfFactorial(nrIntegerDividedByFive);
}
通过这个实现,我们避免了阶乘的实际计算,这是主要的瓶颈。因此,这会在大约 1.5 秒内计算出 n = 1_000_000
(导致 249998
)。