求N之内的所有质数

时间:2022-08-08 11:02:51

一刷选法:
 public static  void PrimeNum(int maxNum)
        {
            for (int i = 3; i <= maxNum; i++)
            {
                bool IsPrime = true;
                for (int j = 2; j <= Math.Sqrt(i); j++)
                {
                    if (i % j == 0)
                    {
                        IsPrime = false;
                        break;//有因子证明是合数,马上退出循环。
                    }
                }
                if (IsPrime)
                {
                    Console.Write(i.ToString()+" ");
                }
            }
        }

二递归法:
public static void PrimeNum(int maxNum)
{
       if (maxNum == 2) 
          {
             Console.Write("2 ");
         }
        else
        { 
             bool isPrime = true;
             isPrime = IsPrime(maxNum, Convert.ToInt32(Math.Sqrt(maxNum)));
             if (isPrime)
                 {
                     Console.Write(maxNum.ToString() + " ");
                 }
            PrimeNum(maxNum - 1);
        } 
}

//递归检查number是否能被比i小的数整除
public static bool IsPrime(int number,int i)
{
      if (number == 2) 
          {
              return true;
          }
      else if (number % i == 0)
          {
              return false;
          }
      else
        {
            i--;
            if (i == 1)
               {
                   return true;
               }
            else
              {
                  return IsPrime(number, i);
             }
        }

三Sieve of Eratosthenes筛法:
引入布尔类型数组a[i],如果i是质数,a[i]=true,否则a[i]=false。那么划掉i可以表示成a[i]=false。
 //找出n以内质数
public static void Sieve(int n)
        {
            bool[] a = new bool[n+1];
            for (int i = 2; i <= n; i++) 
                  {
                     a[i] = true; 
                  }
            for (int i = 2; i <= Math.Sqrt(n); i++)
            {
                if (a[i]== true)
                   {
                       for (int j = i; j*i <= n; j++) 
                           {
                              a[j * i] = false;
                           }
                   }
            }
            for (int i = 0; i <= n; i++)
            {
                if (a[i] == true)
                     {
                        Console.Write("{0},",i.ToString());
                     }
            }
        }