1. Rename the variables.
Firstly, if this is homework, you will get poor grades (if your teacher is worth the salt) because you have meaningless variable names (yes, even numberOfPrimes is wrong and should be called requiredNumberOfPrimes ). When I see this variable I ask myself: "Is this how much he wants, or how much he found?" )
Secondly, it will help you understand where you are wrong. Variables should be logically named according to what they represent. If you cannot explain what your variables represent (e.g. a and b), you probably cannot explain what you are doing with them.
2. Look at your loops.
for (int x = 0; x < numberOfPrimes; x++)
The for loop structure: (initialise; 'should I continue?'; 'each loop do this') . Therefore in your loop
- You continue until x becomes equal or
numberOfPrimes *. - Each time you go through the loop, you add 1 to
x .
Are you sure this is what you want to do? x seems to represent the number of primes you found. So why not enlarge it when you find the stroke, and not when you start the cycle?
for (int a = 2; a <= x ; ++a) for (int b = 2; b < a; ++b)
You look at every integer from 2 to x inclusive. And for each of these integers a you look at every integer between a and 2, inclusive. What are you going to do with these integers?
Each time you loop the top level loop (loop x ), you start loop a from scratch, and every time you loop a , you start your b loop from scratch.
So, if x is 10, you run once (a = 2), then you run again (a = 2, a = 3), then you run again (a = 2, a = 3, a = 4), then ...
3. Collect the results, not write them to the Console.
var primes = new List<int>();
It is so simple. When you find the bar, primes.Add(a); . Then you know how many primes you found ( primes.Count ), you can use a list of primes to efficiently determine the next prime number, and you can use the list later if necessary.