非常简单的素数测试 - 我想我不理解 for 循环 [英] Very simple prime number test - I think I'm not understanding the for loop

查看:18
本文介绍了非常简单的素数测试 - 我想我不理解 for 循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为基本的 Java 考试练习过去的试卷,我发现很难用 for 循环来测试一个数字是否为质数.我不想通过为更大的数字添加效率措施来使它复杂化,只是一些至少适用于 2 位数字的东西.

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.

目前,即使 n 是素数,它也总是返回 false.

At the moment it always returns false even if n IS a prime number.

我认为我的问题是我的 for 循环本身有问题,以及将return true"放在哪里;和返回错误;"......我确定这是我犯的一个非常基本的错误......

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;
}

我无法在 stackoverflow 的其他地方找到帮助的原因是,类似的问题要求更复杂的实现以更有效的方式进行.

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.

推荐答案

你的 for 循环有一个小问题.应该是:-

Your for loop has a little problem. It should be: -

for (i = 2; i < n; i++)  // replace `i <= n` with `i < n`

当然你不想检查n除以n的余数.它总是会给你 1.

Of course you don't want to check the remainder when n is divided by n. It will always give you 1.

实际上,您甚至可以通过将条件更改为:- i <= n/2 来减少迭代次数.由于n 不能被一个大于n/2 的数整除,除非我们考虑n,我们不必考虑完全考虑.

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.

因此,您可以将 for 循环更改为:-

So, you can change your for loop to: -

for (i = 2; i <= n / 2; i++)  

这篇关于非常简单的素数测试 - 我想我不理解 for 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆