簡體   English   中英

你能解決我的問題並簡化我所做的解決方案嗎?

[英]Can you solve my problem and simplify the solution that I have been made?

輸入數字:13

預期輸出:13 是一個質數。

我是這樣試的-> //寫一個程序判斷這個數是不是素數

#include <stdio.h>
int main(){
//Declaring variables for storing information
int number,count=0;
printf("Enter an integer number : ");
scanf("%d",&number);

//Here, I want to divide the number by 1 up to 100
for(int i=1; i<=100; i++){
    if(number%i==0){
            //Here, I count the divisible total number
            count++;

    }
}
//If I found only two
 if(count>=1 && count<=2 && number>1){
            printf("%d is a prime number \n",number);

      }
      else{
        printf("%d is not a prime number \n",number);
      }

  return 0;

}

現在我的問題是:當我的程序運行時它給出了預期的輸出。 但是在這里我無法檢查給定的數字是否不能被除 1 和數字本身以外的任何數字整除。 所以,我在這個程序中做了什么。 正確與否?。 如果保留此解決方案。 會不會有什么問題?

首先,你的解決方案不會總是給你正確的答案,這個解決方案對於輸入 1 會失敗。根據你的解決方案,1 是一個質數,但實際上 1 不是一個質數。

如果您查看素數的定義,您會發現每個素數都恰好有 2 個除數,其中一個是 1,另一個是該數字本身。 因此,您必須進行下面提到的更改。

if(count>=1 && count<=2) // this line has to be removed.

if(count==2)  // this line has to be added.

除上述問題外,如果您的數字小於或等於 100,您的解決方案將正常工作。要解決此問題,您可以進行以下更改。

(int i=1; i<=number; i++)

這是一種尋找素數的幼稚方法,還有其他解決方案可以降低時間復雜度並為更大的價值工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM