返回列表 發帖

208 選擇敘述與迴圈 (找質數)

1. 題目說明:
請依下列題意進行作答,使輸出值符合題意要求。

2. 設計說明:
請撰寫一程式,讓使用者輸入一正整數,輸出小於此整數內的所有質數,質數後方請接一個半形空格。

提示:若使用 Java 語言答題,請以「JP」開頭命名包含 main 靜態方法的 class,評測系統才能正確評分。

3. 輸入輸出:
輸入說明
一個正整數

輸出說明
小於此整數內的所有質數(質數後方請接一個半形空格)

範例輸入
47
範例輸出
2 3 5 7 11 13 17 19 23 29 31 37 41 43

本帖隱藏的內容需要回復才可以瀏覽

  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. int main(){
  4.     int a;
  5.     cin>>a;
  6.     bool Prime=true;
  7.     for(int j=2;j<a;j++){
  8.         for(int i=2;i<=sqrt(j);i++)
  9.         {
  10.             if(!(j%i))
  11.             Prime=false;
  12.         }
  13.         if(Prime)
  14.             cout<<j<<" ";
  15.         Prime=true;
  16.     }
  17. }
複製代碼

TOP

  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. int main ()
  4. {

  5.     int n;
  6.     cin >> n ;
  7.     for(int j=2;j<n;j++)
  8.     {
  9.         bool prime=true;
  10.         for(int i=2;i<=sqrt(j);i++)
  11.         {
  12.             if(j%i==0)
  13.             {
  14.                 prime=false;
  15.             }
  16.         }
  17.         if(prime)
  18.             cout<< j <<" ";
  19.     }



  20.     return 0;
  21. }
複製代碼

TOP

  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. int main()
  4. {
  5.     int num;
  6.     cin >> num;
  7.     for(int i=2 ; i<num ; i++)
  8.     {
  9.         bool isPrime = true;
  10.         for(int j=2 ; j<=sqrt(i) ; j++)
  11.         {
  12.             if(!(i%j))
  13.                 isPrime = false;
  14.         }

  15.         if(isPrime)
  16.             cout << i << " ";
  17.     }
  18.     return 0;
  19. }
複製代碼
Vincent

TOP

返回列表