项目欧拉演习30

时间:2011-12-16 12:51:47

标签: c#

我正在尝试解决project euler的第30个问题。

My implementation of this problem产生了4次方的良好效果,但网站不接受5次方的答案。

有人能解释我代码中的错误吗?

另外,我不确定我的检查上限的公式是否正常。如果不是,我会很高兴知道好的解决方案。

这是我的代码:

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);
            }
        }
    }
}

[编辑] 如果我的理论准确,我asked

1 个答案:

答案 0 :(得分:2)

您的代码只汇总了它正在检查的数字的前5位数。

而不是

for (int x = 0; x < power; x++)

你应该使用while循环

while (tempi > 0)

这会产生您需要的缺失数字。 (提示它长6位数。)

相关问题