返回列表 發帖

303 函式與陣列 (質數判斷)

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

2. 設計說明:
請撰寫一程式,包含名為compute()的函式,接收主程式傳遞的一個整數n(n>1),compute()判斷是否為質數,若為質數請回傳「1」,否則回傳「0」至主程式,並輸出該數是否為質數。

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

3. 輸入輸出:
輸入說明
大於1的整數

輸出說明
該數是否為質數

範例輸入1
2
範例輸出1
2 is a prime number

範例輸入2
6
範例輸出2
6 is not a prime number

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

  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. int compute(int n){
  4.     for(int i=2;i<n;i++){
  5.         if(n%i==0)
  6.             return 0;
  7.     }
  8.         return 1;
  9. }

  10. int main(){
  11.     int n;
  12.     cin>>n;

  13.     if(compute(n)){
  14.         cout<<n<<" is a prime number"<<endl;
  15.     }
  16.     else
  17.         cout<<n<<" is not a prime number"<<endl;
  18.      return 0;
  19. }
複製代碼

TOP

  1. #include<bits/stdc++.h>
  2. using namespace std;

  3. int compute(int a)
  4. {
  5.     for(int i=2 ; i<=sqrt(a) ; i++)
  6.         if(a%i==0)
  7.             return 0;
  8.     return 1;
  9. }
  10. int main()
  11. {
  12.     int n;
  13.     cin>>n;
  14.     if(compute(n))
  15.         cout<<n<<" is a prime number\n";
  16.     else
  17.         cout<<n<<" is not a prime number\n";
  18.     return 0;
  19. }
複製代碼
Vincent

TOP

  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. int compute(int n)
  4. {
  5.     for(int i=2;i<=sqrt(n);i++)
  6.     {
  7.         if(n%i==0)
  8.         return 0;
  9.     }
  10.     return 1;

  11. }
  12. int main()
  13. {
  14.     int n;
  15.     cin>> n;
  16.     if(compute(n))
  17.         cout<<n<<" is a prime number\n";
  18.     else
  19.         cout<<n<<" is not a prime number\n";


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

TOP

返回列表