gpt4 book ai didi

java - java中的返回问题

转载 作者:行者123 更新时间:2023-11-29 10:10:26 25 4
gpt4 key购买 nike

所以我正在用 Java 为 codeeval 编写一个 mersense 脚本来练习这门语言(我对它还很陌生)。有一次我检查数字是否为质数,在我的方法中我进行了正常检查,一切看起来都很好

public static boolean isPrime (int testValue){
if (testValue < 4){
return true;
} else if (testValue % 2 == 0){
return false;
} else {
for (int I = 1; I < Math.sqrt (testValue); I++){
if (testValue % I == 0 ){
return false;
}
}
return true;
}
}

然而,唯一通过的似乎是 1 和 3。我可以在 for 循环之后不做那个 return 吗?这是怎么回事?有什么想法吗?

编辑:

完整代码如下:

import java.io.*;
import java.lang.Math;

public class Main{
public static void main(String[] args) throws IOException {
File file = new File(args[0]);
BufferedReader buffer = new BufferedReader(new FileReader(file));
String line;
int n;
StringBuilder result = new StringBuilder();
int candidate;
while((line = buffer.readLine()) != null){
n = Integer.parseInt(line.trim());
for(int i = 1; i < n; i++){
candidate = mersenne(i);
if(isPrime(candidate)){
System.out.println(candidate + " "+ isPrime(candidate));
if((i+1) >= n){
result.append(candidate);
}else{
result.append(candidate + ", ");
}
}
}
System.out.println(result.toString());
result = new StringBuilder();
}
}

public static int mersenne (int testValue){
return (int)Math.pow(2,testValue) - 1;
}
public static boolean isPrime(int testValue){
if(testValue < 4 && testValue > 1){
return true;
}else if(testValue % 2 == 0){
return false;
}else{
for(int i = 3; i <= Math.sqrt(testValue); i++){
if(testValue % i == 0){
return false;
}
}
return true;
}
}
}

最佳答案

你从 1 开始循环。所有 % 1 都是 0。从 3 开始。

关于java - java中的返回问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38938455/

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