PRIME NUMBERS SERIES

#include "std_lib_facilities.h" // authors header file i am using for library access

int main (){
constexpr int MAX = 100;
vector<int> prime(MAX,1);// To include 1 in the prime series
for (int i = 2; i <= (int)sqrt (MAX); i++ ){ // factors should not morethan sqrt of number
for (int j = 2; j<= MAX/i; j++ ){// all multipliers should be covered
if (prime[i*j-1])
prime[i*j-1] = 0; // since index starts from 0


}


}
for (int k = 0; k < prime.size(); k++){
if(prime[k])
cout <<k+1 << " ";
}
return 0;
}
Please evaluate this code. Any improvements please comment??

Please add the code tags into your post. See http://www.cplusplus.com/articles/jEywvCM9/
The line-numbering, syntax-highlight and systematic indentation really help reading and commenting.
#include "std_lib_facilities.h" // authors header file i am using for library access

int main (){
constexpr int MAX = 100;
vector<int> prime(MAX,1);// To include 1 in the prime series
for (int i = 2; i <= (int)sqrt (MAX); i++ ){ // factors should not morethan sqrt of number
for (int j = 2; j<= MAX/i; j++ ){// all multipliers should be covered
if (prime[i*j-1])
prime[i*j-1] = 0; // since index starts from 0


}


}
for (int k = 0; k < prime.size(); k++){
if(prime[k])
cout <<k+1 << " ";
}
return 0;
}

What is that j loop supposed to do? I think you should remove it.

I'd expect prime to hold numbers that are prime in sequence, but it doesn't.
kbw: It's just your typical sieve of Eratosthenes.

The code looks approximately correct to me. I haven't checked if there are any off-by-1 errors. I would reduce the chances of that by making prime[k] contain the primality of k, not of k + 1.
I ran the code and it does something reasonable, so I am wrong about the loop.

There's some weird character printed at the end.
Last edited on
Topic archived. No new replies allowed.