很简单的素数测试 - 我想我不理解for循环 [英] Very simple prime number test - I think I'm not understanding the for loop
问题描述
我正在练习基础java考试过去的考卷,而且我发现很难做一个for循环的工作来测试一个数字是否为素数。我不希望通过增加更大数字的效率措施来使其复杂化,只是至少可以用于2位数字。
目前它总是返回false即使n是一个素数。
我认为我的问题是我在for循环本身出现问题,以及在哪里放置返回true。和return false;...我敢肯定,这是一个非常基本的错误,我正在做...
public boolean isPrime(int n){
int i;
for(i = 2; i <= n; i ++){
if(n%i == 0){
return false;
}
}
返回true;
$ b 我在其他地方找不到帮助的原因是因为类似的问题要求一个更复杂的实现方法来获得更高效的方法。
/ code>循环有一个小问题。它应该是: - $ /
pre $ for(i = 2; i $ / code>
当然你不想在 n时检查余数
除以 n
。它总会给你 0
。
事实上,你甚至可以通过改变条件来减少迭代次数到: i <= n / 2
。由于 n
不能被大于 n / 2
的数字除,当我们考虑 n
,我们根本不用考虑。
所以,你可以改变你的为
循环到:
pre $ for(i = 2; i <= n / 2; i ++ )
I am practicing past exam papers for a basic java exam, and I am finding it difficult to make a for loop work for testing whether a number is prime. I don't want to complicate it by adding efficiency measures for larger numbers, just something that would at least work for 2 digit numbers.
At the moment it always returns false even if n IS a prime number.
I think my problem is that I am getting something wrong with the for loop itself and where to put the "return true;" and "return false;"... I'm sure it's a really basic mistake I'm making...
public boolean isPrime(int n) {
int i;
for (i = 2; i <= n; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
The reason I couldn't find help elsewhere on stackoverflow is because similar questions were asking for a more complicated implementation to have a more efficient way of doing it.
Your for
loop has a little problem. It should be: -
for (i = 2; i < n; i++) // replace `i <= n` with `i < n`
Of course you don't want to check the remainder when n
is divided by n
. It will always give you 0
.
In fact, you can even reduce the number of iterations by changing the condition to: - i <= n / 2
. Since n
can't be divided by a number greater than n / 2
, except when we consider n
, which we don't have to consider at all.
So, you can change your for
loop to: -
for (i = 2; i <= n / 2; i++)
这篇关于很简单的素数测试 - 我想我不理解for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!