Question: Write a program to read a number N from the user and then find the first N primes. A prime number is a number that only has two divisors, one and itself.
Instead of my code printing out a sequence of prime numbers, it repeats some of the prime numbers.
int main(){
int N;
cin >> N;
for (int i = 2; i < N; i++){
for (int j = 2; j < N; j++){
if (i%j ==0){
break;
}
else
cout << i << " " << "is a prime number\n";
}
}
}
First of all, that code doesn't output anything.
You can fix it by changing N to i in the second for loop and also in the if(j==N).
Then that code will only print the prime numbers up to (but not including) N.
The OP wants the first N primes.
So instead, use another variable to keep track of how many primes have been found so far, and use that instead of i < N as the condition in the outer for loop.
Here is a very basic example that isn't fully optimized which you may need if you want a verrry large range of primes within a timely manner and with restricted memory.
unsignedconst primes = 100;
std::vector<bool> sieve(primes+1, true);
for(int i = 2; i < std::sqrt(primes); ++i)
{
if(primes.at(i))
{
for(int j = i*i; j <= primes; j += i)
{
sieve.at(j) = false;
}
}
}
std::cout << "The primes less than or equal to " << primes << " are: " << std::endl;
std::cout << 2 << ' ';
for(int i = 3; i <= primes; i += 2)
{
if(sieve.at(i))
{
std::cout << i << ' ';
}
}
std::cout << std::endl;
*edit I misread it wants the first n primes not primes up to n. Basically you want to use a modified version of the prime number theorem to find the number that has the n number of primes less than it. Then sieve up to that number and output all the primes (You can use a counter to double check but the theorem should be pretty accurate).
if (i%j ==0){
break;
}
else
cout << i << " " << "is a prime number\n";
This outputs after the first iteration in j. You should assign a variable to false if it breaks. Then outside the inner loop if it is still prime (true) output.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
bool prime = true;
for (int i = 2; i < N; i++){
prime = true;
for (int j = 2; j < N; j++){
if (i%j ==0){
break;
prime = false;
}
}
if(prime)
cout << i << " " << "is a prime number\n";
}
Your indentation is kind of hard for me to read. I tried to match yours.