Your basic mistake is that you do not reset your variable y
to zero after each iteration of the while
. It can only grow, and when the number 3 is tested, it already is big enough not to let any number pass, thus it passes only the number 2.
Quick fix: after
if (y < 3)
{
cout << a << ", " << endl;
x = x - 1;
}
a = a + 1;
insert
y = 0;
Another bug is that you only check for numbers smaller than 11, which means that for example 121 (11*11) will be a false positive, your program will think it is prime when it isn't.
That said, you should learn how to write code that is easier to debug by yourself, especially using a debugger. If you never have used a debugger, don't worry, you'll easily find tutorials for that. In your case, the debugger would have showed you the state of y and you'd have seen that it reaches numbers it shouldn't be able to.
Two general hints for future code:
Use descriptive variable names. x and y sound to me like coordinates, but they are not. Give them proper names, like number_dividers
instead of y, for example.
Break your code into parts. For example, have a function like this:
#include <cmath>
bool is_prime(int number)
{
if(i <= 1) return false;
for(int i = 2; i <= std::sqrt(number); i++)
{
if(number % i == 0) return false;
}
return true;
}
Having such functions makes your code more tidy, allows you to reuse parts of the code, and, especially in your case, allows you to test this unit of code in isolation, that is testing if for a given input it has the right output (essentially a unit test).
Your code would now be:
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
//(insert code from above here)
int main()
{
int required_primes = 0;
cout << "State the amount of prime numbers to be found: ";
cin >> required_primes;
int found_primes = 0;
int current_number = 2;
while(found_primes < required_primes)
{
if(is_prime(current_number))
{
cout << "Found prime: " << current_number << endl;
found_primes++;
}
current_number++;
}
}
(The descriptive variable names make it far easier to understand for somebody looking at the code for a first time, wouldn't you agree?)