查找下一个质数

mor*_*tey 1 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;
}
Run Code Online (Sandbox Code Playgroud)

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

Ben*_*son 5

有更好的方法来找到素数,但根据你的算法,你想要做的是从 开始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;
    }
}
Run Code Online (Sandbox Code Playgroud)