gpt4 book ai didi

java - 大整数输入超时

转载 作者:行者123 更新时间:2023-11-30 05:43:04 25 4
gpt4 key购买 nike

考虑写在纸上的数字 1 到 n 的排列。我们将其元素的乘积表示为 p,将其元素的和表示为 s。给定一个正整数 n,您的任务是确定 p 是否可以被 s 整除。

我尝试使用 bigInteger 概念,但 50 个测试用例中有 30 个成功通过,但其余的则显示超时,这可能是由于递归所致。

import java.util.*;
import java.math.BigInteger;

public class TestClass {
static BigInteger factorial(int n){

if(n==0||n==1)
return new BigInteger("1");

return BigInteger.valueOf(n).multiply(factorial(n-1));
}

public static void main(String args[] ) throws Exception {
Scanner s=new Scanner(System.in);
int n=s.nextInt();
int nn=n*(n+1)/2;
BigInteger sum=BigInteger.valueOf(nn);
BigInteger p=factorial(n);

if((p.mod(sum)).equals(BigInteger.valueOf(0)))
System.out.println("YES");
else
System.out.println("NO");
}
}

示例测试用例就像输入为 3,其输出应为“YES”。因为 (1+2+3) 除 (1*2*3)。

最佳答案

尝试删除递归并使用for循环来计算阶乘。

import java.util.*;
import java.math.BigInteger;
public class TestClass {
static void factorial(long n, long nn){

BigInteger answer=new BigInteger("1");
BigInteger sum=BigInteger.valueOf(nn);
int foundMatch =0;
for(long i=n;i>0;i--){
answer=answer.multiply(new BigInteger(String.valueOf(i)));
if((answer.mod(sum)).equals(BigInteger.valueOf(0)))
{
System.out.println("YES");
foundMatch = 1;
break;
}
}
if(foundMatch!=1)
System.out.println("NO");
}

public static void main(String args[] ) throws Exception {
Scanner s=new Scanner(System.in);
long n=s.nextLong();
long nn=n*(n+1)/2;

factorial(n, nn);
}

}

关于java - 大整数输入超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55334861/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com