天天看點

C#基礎程式設計---素數

using System;

namespace TestApp

{   

       class Test

       {

              public void calculate(int n)

              {

                    int count, j, k;

                    if(n>=2)

                    {

                         Console.Write("2"+ "/t");

                    }

                    if(n>=3)

                    {

                         count = 1; //目前有一個素數, 即2

                         k = 3;     //從奇數3開始測試, 偶數不需要測試

                         do

                         {

                               j=3;

                               while((j <= (Math.Sqrt(k)))&&(k%j!=0))

                               {

                                    j +=2;

                               }

                               if(j > Math.Sqrt(k))

                               {

                                    count ++;

                                    Console.Write(k +"/t");

                                    if(count%5 == 0)

                                       Console.WriteLine();//每行輸出5個數

                               }

                               k += 2;//測試下一個奇數是否是素數

                       }while(k <= n);

                       Console.WriteLine("/n共有{0}個素數!", count);

                    }

              }

           static void Main(string[] args)

           {

                  Test test = new Test();

                  int i = 1;

                  while(i > 0)

                  {

                        Console.Write("輸入一個整數: ");

                        i = Int32.Parse(Console.ReadLine());

                      test.calculate(i);

                  }

           }   

       }

}