早教吧 育儿知识 作业答案 考试题库 百科 知识分享

关于C#中一个方法的使用问题staticboolIsPrime(intnum)如果num是素数便返回true,不然返回false并且使用一个while循环,利用以上method来展示0到1000之间的素数原题:Assumethefollowingmethodisavailab

题目详情
关于C#中一个方法的使用问题
static bool IsPrime (int num)
如果num是素数便返回true,不然返回false
并且使用一个while循环,利用以上method来展示0到1000之间的素数


原题:

Assume the following method is available for use:
static bool IsPrime (int num)
IsPrime takes a number and returns true if the number is prime, otherwise it returns false. (A number is said to be prime if it is only divisible by 1 and by itself).
Write a
while loop to display every prime number between 0 and 1000 using the above method. (That is, do NOT implement IsPrime)
▼优质解答
答案和解析
//此处只计算正整数的质数
public static bool IsPrime(int num)
{
    if(num<2)
    {
        return false;
    }
    if(num==2)
    {
        return true;
    }
    for(int i=2;i<num;i++)
    {
        if(num%i==0)//如果能整除 就返回false
        {
            return false;
        }
    }
    return true;

}

//展示0-1000之间的素数
public void Main()
{
    int n = 0;
    while(true)
    {
        if(n>=1000)break;
        if(IsPrime) Console.WriteLine(n);
    }
}