Skip to main content
 首页 » 编程设计

c#之寻找下一个质数

2024年02月13日16hnrainll

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

这是我目前的代码:

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