Hi
I have this following IEnumerable LINQ query:
var query = from p in Enumerable.Range(2, 1000000)
let sumofPowers = from ch in p.ToString()
let sumOfPowers = Math.Pow(Convert.ToDouble(ch.ToString()), 5)
select sumOfPowers
where p == sumofPowers.Sum()
select p;
It finds the sum of all the numbers that can be written as the sum of fifth powers of their digits. (Google Project Euler Problem 30 for a more thorough explanation).
It works fine as it is. I know it is nitpick, but the range annoys me. I have basically guessed that it has found the correct result at 1,000,000, so I let it stop there. In this scenario, the number was sufficient.
But it is just a hardcoded "random" number...
If you look at the code, you find that as soon as where p == sumofPowers.Sum()
is true, you don't really need to run through the loop anymore.
I know yield
can do it in under other situations and break
works in normal loops - so is there anything you can do in this situation?