Jeff Lauder
Jeff Lauder

Reputation: 1247

Why doesn't LINQ work as expected?

I have created a simple program to calculate primes as follows:

        var db = new HighScoreEntities();
        List<Int64> primes = new List<Int64>(){1};
        for (Int64 x = 2; x < Int64.MaxValue; x++)
        {
            if (primes.FirstOrDefault(y=> x%y == 0) == 0){
                primes.Add(x);
                db.Primes.AddObject(Prime.CreatePrime(x));
                db.SaveChanges();
            }
        }

My issue is that y is coming out with 225 on the first go through and what seems like random numbers afterwards. Why isn't it iterating through the 'primes' list? I also tried using the Exists function with the same result.

Upvotes: 1

Views: 165

Answers (3)

Tod
Tod

Reputation: 8232

I think you want the .Any operator

if (!primes.Any(y=> x%y == 0) )

Also there are many examples of using LINQ and PLINQ for calculating primes. Here's just one.

Upvotes: 3

Jarek
Jarek

Reputation: 3379

First issue I see with this code is that primes list is initialized with 1. There are two problems with that number - 1 is not prime number, and 1 will always meet requirements presented in FirstOrDefault lambda, because any number modulo one will give 0 in result.

Apart from that, everything seems to be rather ok.

Upvotes: 2

Andrew
Andrew

Reputation: 5083

1 isn't a prime, so adding it to primes is probably a bad start. It looks like on every loop iteration you are finding the first element in primes such that the remainder of x / 1 is 0, which will always be true.

I didn't try the program out myself so I could be wrong, but that should be a good place to start.

Upvotes: 5

Related Questions