c# - 寻找下一个质数

标签 c# primes

我试图在用户输入的数字之后找到下一个素数。

这是我目前的代码:

public int Calculation(int number)
{
    //set the isPrime to false
    bool isPrime = false;

    //do this while isPrime is still false
    do
    {
        //increment the number by 1 each time
        number = number + 1;

        int squaredNumber = (int)Math.Sqrt(number);

        //start at 2 and increment by 1 until it gets to the squared number
        for (int i = 2; i <= squaredNumber; i++)
        {
            //how do I check all i's?
            if (number % i != 0)
            {
                isPrime = true;
            }


        }


    } while (isPrime == false);

    //return the prime number
    return number;
}

我知道缺少某些东西,因为我第一次给出不为 0 的余数,然后它返回该数字作为素数。问题是我无法弄清楚逻辑/语法来查看该循环中的每个 i 是否都不是 0 作为余数。

最佳答案

有更好的方法来查找素数,但为了与您的算法保持一致,您要做的是从 isPrime = true; 开始,然后将其设置为 false 如果有任何 i 余数为 0。您也可以在该点 break 跳出循环。

所以修改后的版本:

public int Calculation(int number)
{    
    while(true)
    {
        bool isPrime = true;
        //increment the number by 1 each time
        number = number + 1;

        int squaredNumber = (int)Math.Sqrt(number);

        //start at 2 and increment by 1 until it gets to the squared number
        for (int i = 2; i <= squaredNumber; i++)
        {
            //how do I check all i's?
            if (number % i == 0)
            {
                isPrime = false;
                break;
            }
        }
        if(isPrime)
            return number;
    }
}

关于c# - 寻找下一个质数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23644479/

相关文章:

c# - 忽略特定操作的 Controller 路由属性

c# - 为什么我的程序在调用 "OpenAsync()"时终止?

c# - 如何保证我的 WPF 应用程序的永久管理员权限

c# - 如何使用 C# 正确创建缩略图?

algorithm - 用于测试确定性素数的 Miller-Rabin 的修改版本?

java - Miller-Rabin 代码对于某些数字运行时间较长。漏洞?

c# - 在 Lambda 语法中绕过 int.TryParse 的 else block

python - 我的主要测试代码有什么问题?

c++ - 如何加快这个素数测试

Go big int 文字溢出 int64