I’m trying to solve the 30th problem of project euler.
My implementation of this problem produces the good result for 4th power, but the answer for 5th power is not accepted by the site.
Can someone explains what’s wrong in my code ?
Also, I’m not sure if my formula for upper bound to check is ok. If it’s not, I’d appreciate to know to good solution.
Here’s my code :
class P30
{
static void Main(string[] args)
{
Console.WriteLine(" " + GetMatchingNumbers(4).Sum());
Console.WriteLine(" " + GetMatchingNumbers(5).Sum());
Console.ReadLine();
}
static IEnumerable<int> GetMatchingNumbers(int power)
{
for (int i = 2; i <(power + 1)*(Math.Pow(9,power)); i++)
{
var sumOfPowers = 0;
var tempi = i;
for (int x = 0; x < power; x++)
{
sumOfPowers += (int)Math.Pow( tempi % 10, power);
tempi /= 10;
}
if (sumOfPowers == i)
{
yield return i;
Console.WriteLine("With Power {0}, {1} matches", power, i);
}
}
}
}
[Edit] I’ve asked if my theory is exact.
Your code is only summing the first 5 digits of the number it’s checking.
Instead of
you should use a while loop instead
This produces the missing number you need. (hint it’s 6 digits long.)