[英]Check if an int is prime Java
對不起“修復我的代碼”帖子
編輯:更多地涉及for
循環的語法而不是素數,現在也解決了。
我的任務是從控制台獲取一個int並打印(在單獨的行上)從1到n的所有素數。 我的方法從n開始,檢查它是否為素數,然后將n遞減1並循環直到n = 2。 為了檢查一個數字是否為素數,我運行一個循環,檢查剩余的潛水數量x等於零,x從2開始並在root(n)處停止。 現在這一切都在理論上有效,並且閱讀我的代碼我看不出它出了什么問題。
public class Prime {
public static boolean isPrime(int n) {
boolean result = true;
for (int x = 2; x>=sqrt(n); x++) {
if ((n % x) == 0) {
result = false;
break;
} else {
x++;
}
}
return result;
}
public static void main(String[] args) {
Scanner intIn = new Scanner(System.in);
int i = intIn.nextInt();
while (i>=2) {
if (isPrime(i)) {
System.out.println(i);
i--;
} else {
i--;
}
}
}
}
例如,輸入10將返回10(以及9,8,7,6,5,3),即使isPrime()檢查10%2 == 0,然后將result
設置為false。 我在這里失蹤了什么?
我再次為煩人(略微重復)的問題道歉。
for
循環中的條件是繼續循環的條件,而不是停止循環的條件。 您需要更換>=
與<=
for (int x = 2; x<=sqrt(n); x++) {
// Here -----^
你正在遞增x兩次,循環的條件應該是x<=sqrt(n)
:
for (int x = 2; x>=sqrt(n); x++) { // here
if ((n % x) == 0) {
result = false;
break;
} else {
x++; // and here
}
}
正確的邏輯應該是:
public static boolean isPrime(int n) {
for (int x = 2; x<=sqrt(n); x++) {
if ((n % x) == 0) {
return false;
}
}
return true;
}
在循環中x必須小於或等於所以將(int x = 2; x> = sqrt(n); x ++)的表達式更改為for(int x = 2; x <= sqrt(n); x ++)
試試這種方式,它更清晰簡潔。
public static boolean isPrime(int candidate) {
int candidateRoot = (int) Math.sqrt((double) candidate);
return IntStream.rangeClosed(2, candidateRoot)
.noneMatch(i -> candidate % i == 0); // return true if the candidate
// isn't divisible for any of the
// numbers in the stream
}
public static void main(String[] args) {
Scanner intIn = new Scanner(System.in);
int i = intIn.nextInt();
List<Integer> primeList = IntStream.rangeClosed(2, i)
.filter(candidate -> isPrime(candidate))
.boxed()
.collect(toList());
System.out.println(primeList);
// Another way
Map<Boolean, List<Integer>> primeAndNotPrimeMap = IntStream.rangeClosed(2, i)
.boxed()
.collect(partitioningBy(candidate -> isPrime(candidate)));
System.out.println(primeAndNotPrimeMap);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.