1
int limit = 100;
IEnumerable<int> primes = Enumerable.Range(2, limit - 2 + 1);

for (int i = 2; i*i <= limit; i++)
{
    primes = (from item in primes where (item % i != 0) || (item == i) select item);
}

foreach (int prime in primes) Console.WriteLine(prime);

Console.ReadKey();

This is my code to get prime numbers from 2 to 100. Why doesn't it work? Help, please.

  • 1
    You need to capture the local `i` otherwise when you iterate the query it's going to have a value of 11. – juharr May 12 '18 at 17:54

1 Answers1

1

You just need to change it to capture the current value of i.

for (int i = 2; i*i <= limit; i++)
{
    int curr = i;
    primes = (from item in primes 
              where (item % curr != 0) || (item == curr) 
              select item);
}

Otherwise when you iterate the query at the end i will be 11 for all of the comparisons.

juharr
  • 31,741
  • 4
  • 58
  • 93