I have a linq query for project euler problem 243:
var y = from n in factors
from m in factors where m != n
select n * m;
The problem is, for prime factors 2 and 3, it produces the y = {6, 6} where it needs to just be {6}.
Is there a way to do this without calling y.Distinct() or y.Contains() multiple times?
I also thought about using two foreach loops, but the problem is - I can't use indexing so it'd just be cumbersome and awkward.
You can do a distinct call on the resulting values. This way you don't have to do it on the inner loop.
var y = factors.SelectMany(n => factors.Where(m => n < m).Select(m => n * m)).Distinct();
If factors = new[] { 2,3 }
you get { 6 }
as the result. Also if factors = new[] { 2,3,4,6 }
you get { 6,8,12,18,24 }
instead of { 6,8,12,12,18,24 }
. Notice without the extra 12
in the result.
As stated by Rick Sladkey, changing
from m in factors where m != n
to
from m in factors where m < n
produces the correct result without having to use .Distinct()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With