2013-07-23 43 views
-4

如何計算所有「素數」數字而不是顯示它們?在C++中計算素數

例子:

cout << "there are 125 prime numbers"; 

我使用的是1000號,因爲我想看看有多少素數有。

我不想顯示找到的素數,但我想知道有多少個被發現。

#include <iostream> 
#include <iomanip> 
#include <string> 
#include <sstream> 
#include <fstream> 
#include <math.h> 
#include <stdio.h> 

using namespace std; 

int main() 
{ 
    for (int a=2 ; a < 1000 ; a++) 
    { 
     bool prime = true; 

     for(int c=2 ; c*c <= a ; c++) 
     { 
      if(a % c == 0) 
      { 
       prime = false; 
       break; 
      } 
     } 

     if(prime) cout << a << " "; 
    } 

    return 0; 
} 
+0

你格式化的人..它..漂亮壞。 – Rapptz

+1

你知道這是所見即所得,當你寫下你的問題時,右邊有一盒格式化幫助,對吧? – chris

+0

你爲什麼不真正以正確的方式提問這個問題。此外,您的問題可以用簡單的谷歌搜索來回答。是的,看看Eratosthenes的篩子。 – darxsys

回答

2

重新格式化您的代碼:

#include <iostream> 
#include <iomanip> 
#include <string> 
#include <sstream> 
#include <fstream> 
#include <math.h> 
#include <stdio.h> 

using namespace std; 

int main() { 
    for (int a = 2; a < 1000; a++) { 
     bool prime = true; 

     for (int c = 2; c*c <= a; c++) { 
      if(a % c == 0) { 
       prime = false; 
       break; 
      } 
     } 

     if(prime) cout << a << " "; 
    } 

    return 0; 
} 

不是每次都打印出來,通過循環,你需要一個變量每次數是素數。

int main() { 
    int num_primes = 0; 
    for (int a = 2; a < 1000; a++) { 

下,而不是印刷,每當一個數是素數,只是增加計數器:通過添加外的變量之外循環開始

if(prime) { 
    num_primes += 1; 
} 

最後,從主返回之前(),打印出素數:

cout << num_primes << endl; 
return 0; 

雖然這看起來像你的功課,但我希望你從中學到了一些東西。

+0

我做了感謝...大多數代碼是由我佈局的只是當它涉及到細節我傾向於鬆散指南..沒有很多指南解釋C++ ...感謝澄清我的代碼.. – Cris

+0

我可以問你「+ =」是什麼嗎? – Cris

+0

它是「num_primes = num_primes + 1」的簡稱。這不是最好的方式,但我試圖儘可能少地改變你的代碼。 –

0

簡單,只需增加計數器而不是打印值。您還可以得到歐拉函數的一個相當體面的近似利用公式N /(日誌(N)-1)...

+0

那麼我該如何準確地實現一個計數器......我是C++和詞彙的新手...... – Cris

+0

請參閱上面的RadhaKrishna的文章。 – SeaBass

0

試試這個,

#include < iostream> 
#include < iomanip> 
#include < string> 
#include < sstream> 
#include < fstream> 
#include < math.h> 
#include < stdio.h> 

using namespace std; 
int main() 
{ 
    int count=0; 
    for (int a=2 ; a < 1000 ; a++) 
    { 
     bool prime = true; 
     for (int c=2 ; c*c <= a ; c++) 
     { 
      if(a % c == 0) 
      { 
       prime = false; 
       break; 
      } 
     } 
     if(prime) count++; 
    } 

    cout <<"No of prime numbers : "<< count; 
    return 0; 
} 
+0

感謝它的工作......我永遠不會猜到這種細節...... – Cris

+0

請避免使用**「試試[在此插入代碼片段]」**答案。提供一些解釋。如果不這樣做,OP建議只複製粘貼答案,而不理解和思考。 – Manu343726