3 回答

TA貢獻1865條經驗 獲得超7個贊
嘗試刪除遞歸并使用 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);
}
}

TA貢獻1936條經驗 獲得超7個贊
import java.util.*;
class TestClass {
public static int prime(int n)
{
int count=0,flag=0;
if(n==1)
flag=1;
if(n==2)
flag=0;
else {
for(int i=2;i<=Math.sqrt(n);i++) {
if(n%i==0)
{
flag=1;
break;
}
}}
if(flag==1)
return 1;
return 0;
}
public static void main(String args[] ) throws Exception {
Scanner s=new Scanner(System.in);
int t=s.nextInt();
while(t-->0)
{
int flag=0;
int n=s.nextInt();
if(n%2==0)
{
flag=prime(n+1);
}
else
{
flag=1;
}
if(flag==1)
System.out.println("YES");
else
System.out.println("NO");
}
}
}

TA貢獻2039條經驗 獲得超8個贊
您可以使用這樣的邏輯:如果階乘的中間乘積可被總和整除,則整個階乘也可以被和整除。
import java.math.BigInteger;
import java.util.Scanner;
public class TestClass {
static boolean isFactorialDivisible(int n, BigInteger sum) {
BigInteger p = BigInteger.ONE;
for (int i = n; i > 0; i--) {
p = p.multiply(BigInteger.valueOf(n));
if (p.mod(sum).equals(BigInteger.ZERO)) {
return true;
}
BigInteger gcd = p.gcd(sum);
if (!gcd.equals(BigInteger.ONE)) {
p = p.divide(gcd);
sum = sum.divide(gcd);
}
}
return false;
}
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);
boolean p = isFactorialDivisible(n, sum);
if (p)
System.out.println("YES");
else
System.out.println("NO");
}
}
添加回答
舉報