精華區beta NTUCH-HW 關於我們 聯絡資訊
功能 用到的觀念 CODE /*DESCRIPTION:find the prime number*/ #include"iostream"//標頭檔 #include"iomanip" #include"cmath" using namespace std; using std::setw; using std::fixed; using std::setprecision; int main() { unsigned n;//n save the number of the end, int i,j,m=0;//declare the number for the loop cout<<"find the number form 1 to n, enter the n"<<endl;//顯示內容 cin>>n;//輸入存到n system("cls");//clean the screen cout<<"the prime number are:"<<"between 1 to "<<n<<endl;//顯示內容 if(n==2)//check whether n is equal to 2 { cout<<"2";//顯示內容 } if(n==3)//check whether n is equal to 3 { cout<<"2"<<endl;//顯示內容 cout<<"3"<<endl;//顯示內容 } if(n>3) { cout<<"2 "<<endl;//顯示內容 cout<<"3 "<<endl;//顯示內容 for(i = 2; i<= n;i++)//從2檢查到n判斷是否為質數 { for(j = 2; j <=sqrt(double(i)); j++)//extract a root for i. this makes the calculation quicker { if(i%j==0)//if i is divided with no remainder { m=1;//save 1 to m break;//jump from this loop } else//i is divided with remainder m=2; } if(m==2)//if m=2 it proves that i is a prime number { cout<<i<<endl;///show the prime numbers } } } system("pause"); return 0; } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.112.7.59