Hi I'm new here. I'm trying to learn c++ on my own so I need all the help I can get! :) I'm having trouble figuring out what's wrong with my code. I'm trying to output the first N primes that the user inputs, but I get an error when N>1.
Thank you
// Prime Numbers
#include <iostream>
usingnamespace std;
int main(){
// Get input N from user and output first N prime numbers
int N;
int x = 2;
int counter = 0;
int m = 0;
cout << "Enter how many prime numbers you would like?\n";
cin >> N;
if (N == 1)
cout << "\n" << "2\n";
else{
for (x; x< 100000; x = x +1)
for (m; m<10; m = m +1)
if ((x%m==0)&&(x!=m))
continue;
elsewhile (counter<N){
counter = counter +1;
cout << x << ", ";
}
}
return 0;
}
Thanks for the replies. The error was simply that the program would crash so I wasn't sure where the problem was. I changed the code to int m = 1; and now the program runs, but now I just keep getting 2's. Now, I think I have something to work with so I will try now to see what I can do. Thanks, and if you have any further suggestions as to what to do, let me know!
// Prime Numbers
#include <iostream>
usingnamespace std;
int main(){
// Get input N from user and output first N prime numbers
int N;
int x = 2;
int counter = 0;
int m = 1;
cout << "Enter how many prime numbers you would like?\n";
cin >> N;
for (x; x< 100000; x = x +1) // Enumerate to 100000
for (m; m<10; m = m +1)
if ((x%m==0)&&(x!=m)) // Check x number from 1 to 9 to check if prime, ex: 4%2 == 0 is true an 4 != 0 so the number is not prime
continue; // continue until a prime number is found
elsewhile (counter<N){ // Keep giving out prime numbers until counter reaches user N
counter = counter +1;
cout << x << ", ";
}
return 0;
}
Lines 24,25: The usual for loop idiom is to initialize the starting value in the first term and to use the increment operator: for (x=2; x< 100000; x++)
Line 29: Your while loop will keep putting out the same number until counter reaches N. What you really want to do here is to exit both for loops.
The biggest problem that I see is that you are trying to do too much in your main function. Programming problems are better solved by breaking the code up into functions. write a function that takes a single integer and determines whether or not that integer is prime. then just have a for loop that feeds that function integers.
also there are many posts about prime numbers so you might want to look some of them up to get ideas.
Thanks for the advice Yanson and Anon. Btw, what do you mean exit both for loops? Would I put a break; in the while loop? I feel like that would break out of the loop before all the prime numbers were outputted. If you coul clarify that a little more, I would appreciate it. Thanks
When counter (number of primes found) reaches N (number of primes requested), what is the point of continuing? My point was that you whould exit the program at that point.