2011-12-16 109 views
0

我試圖解決project euler的第30個問題。歐拉項目練習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如果我的理論是準確的。

+0

你是否試圖用long替換int?我懷疑你的計算溢出了int的容量... – 2011-12-16 13:03:25

+0

另外,你確定你的循環的上限?你是怎麼想出這個價值的? – 2011-12-16 13:05:16

回答

2

你的代碼只是將它正在檢查的數字的前5位數相加。

而不是

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

你應該使用while循環,而不是

while (tempi > 0) 

這會產生你所需要的缺號。 (提示它的長度是6位數。)