我正在尋找一些關於我的算法實現的反饋。我該如何改進它?當計算由於整數溢出而產生的大質數> 46349時遇到了問題,但通過使用sqrt而不是pow解決了這個問題。我昨天讀了關於Eratosthenes的Sieve並想實現它
#include<iostream>
#include<math.h>
using namespace std;
int main(){
int number;
cin >> number;
const int CAP = number;
bool * prime = new bool[CAP];
for(int i = 0; i <= CAP; i++){ //sets all to true for the marking
prime[i] = true;
}
for(int i = 2; i <= number; i++){
if(i <= sqrt(number) && prime[i] == true){
for(int j = i*i; j <=number; j++){ //if %i == 0 mark false
if(j % i == 0){ //haven't tried another way
prime[j] = false;
}
}
}
}
for(int i = 2; i <= number; i++){
if(prime[i] == true){
cout << i << endl;
}
}
return 0;
}
這個問題似乎是題外話題,因爲它是關於審查(工作?)的代碼。 – user2864740
stackoverflow適用於有錯誤的代碼,但一定要解釋你得到的問題,因爲人們不喜歡只編碼並且不得不猜測。 –
嘗試在codereview.SE,他們更偏向於這樣的問題。 – Sinkingpoint