1. Rename your variables.
Firstly, if this is homework you will get bad marks (if your teacher is worth his salt) because you have meaningless variable names (yes, even numberOfPrimes
is wrong and should be named requiredNumberOfPrimes
. When I see this variable I am asking myself 'Is this how many he wants, or how many he has found?').
Secondly, it will help you understand where you are going wrong. Variables should be logically named according to what they represent. If you can't explain what your variables represent (e.g. a & b) then you probably can't explain what you are doing with them.
2. Look at your loops.
for (int x = 0; x < numberOfPrimes; x++)
The structure of a for loop is (initialise; 'should I continue?'; 'each loop do this')
. Therefore in your loop
- You are continuing until x is equal to or great than
numberOfPrimes
*.
- Each time you go through the loop you are adding 1 to
x
.
Are you sure this is what you want to do? x
appears to represent the number of primes you have found. So why not increment it when you find a prime, rather than when you start a loop?
for (int a = 2; a <= x ; ++a)
for (int b = 2; b < a; ++b)
You are looking at each integer between 2 and x
, inclusive. And for each of those integers a
, you are looking at every integer between a
and 2 inclusive. What are you going to do with these integers?
Every time you loop through your top-level loop (the x
loop), you are going to start your a
loop from scratch, and every time you loop through your a
loop you will start your b
loop from scratch.
So if x
is 10, you run through a once (a=2), then you run through a again (a=2, a=3), then you run through a again (a=2, a=3, a=4), then...
3. Collect your results rather than writing them to Console.
var primes = new List<int>();
It's so easy. When you find a prime, primes.Add(a);
. Then you know how many primes you have found (primes.Count
), you can use the list of primes to efficiently determine the next prime, and you can use the list later on if required.