检查int是否为主要Java [英] Check if an int is prime Java
问题描述
抱歉修复我的代码"帖子
与质数相比,与 for
循环的语法更多相关,现在也已解决.
related more to syntax of a for
loop than prime numbers, also solved now.
我的任务是从控制台获取一个int并打印(在单独的行上)从1到n(含)的所有质数.我的方法从n开始,检查其素数,然后将n递减1并循环直到n = 2.为了检查数字是否为素数,我运行了一个循环,检查将数字除以x的余数等于零,其中x从2开始并在root(n)处停止.现在,所有这些都在理论上可行,并且阅读我的代码后,我看不出它出了什么问题.
My task is to take an int from the console and print out (on separate lines) all the prime numbers from 1 to n inclusive. My method starts at n, checks if its prime, then increments n down by one and loops until n=2. To check if a number is prime I run a loop, checking is the remainder of diving the number by x is equal to zero, with x starting at 2 and stopping at root(n). Now this all works in theory, and reading my code I don't see where it goes wrong.
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--;
}
}
}
}
例如,输入is 10将返回10(以及9,8,7,6,5,3),即使isPrime()检查10%2 == 0,然后设置 result
为false.我在这里想念什么?
For example an input of 10 will return 10 (along with 9,8,7,6,5,3), even though isPrime() checks if 10 % 2 == 0, then sets result
to false.
What am I missing here??
我再次为烦人的问题(略有重复)道歉.
Again I apologise for the annoying (slightly duplicate) question.
推荐答案
for
循环中的条件是继续的条件,而不是停止.您需要将> =
替换为< =
:
The condition in the for
loop is the condition to continue the loop, not the condition to stop it. You need to replace >=
with <=
:
for (int x = 2; x<=sqrt(n); x++) {
// Here -----^
这篇关于检查int是否为主要Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!