Ich muss alle Primzahlen von 2 bis n mit dem Sieb von Eratosthenes finden. Ich schaute auf Wikipedia (Sieve of Eratosthenes), um herauszufinden, was das Sieb des Eratosthenes war, und es gab mir diese Pseudo-Code:Fehler beim Versuch, alle Primzahlen von 2 bis n unter Verwendung von Sieat von Eratosthenes in C++ zu finden
Input: an integer n > 1
Let A be an array of Boolean values, indexed by integers 2 to n,
initially all set to true.
for i = 2, 3, 4, ..., not exceeding √n:
if A[i] is true:
for j = i2, i2+i, i2+2i, i2+3i, ..., not exceeding n :
A[j] := false
Output: all i such that A[i] is true.
So habe ich diese und übersetzt es in C++. Es sieht gut aus für mich, aber ich habe ein paar Fehler. Erstens, wenn ich Eingang 2 oder 3 in n, heißt es:
terminate called after throwing an instance of 'Range_error'
what(): Range_error: 2
Auch wenn ich 100 oder irgendetwas anderes (4, 234, 149, 22, alles) eingeben, ist es der Eingang für n annimmt, und tut nichts. Hier ist meine C++ Übersetzung:
#include "std_lib_facilities.h"
int main()
{
/* this program will take in an input 'n' as the maximum value. Then it will calculate
all the prime numbers between 2 and n. It follows the Sieve of Eratosthenes with
the algorithms from Wikipedia's pseudocode translated by me into C++*/
int n;
cin >> n;
vector<string>A;
for(int i = 2; i <= n; ++i) // fills the whole table with "true" from 0 to n-2
A.push_back("true");
for(int i = 2; i <= sqrt(n); ++i)
{
i -= 2; // because I built the vector from 0 to n-2, i need to reflect that here.
if(A[i] == "true")
{
for(int j = pow(i, 2); j <= n; j += i)
{
A[j] = "false";
}
}
}
//print the prime numbers
for(int i = 2; i <= n; ++i)
{
if(A[i] == "true")
cout << i << '\n';
}
return 0;
}
was wollten Sie damit machen i - = 2? – Martze
Sie müssen auch "i" in dieser letzten Schleife anpassen. –
Was sagt Ihnen der Debugger, wenn Sie den Code durchgehen? –