2016-11-17 12 views
1

我寫的代碼比我在網上找到的一些代碼慢(超過最大時間),即使在線代碼看起來更臃腫。自己的代碼明顯比別人慢

那麼,我陷入了什麼陷阱,我的代碼看起來更乾淨,但以某種方式放緩?

慢(我的):

using System; 

public class Program 
{ 
    public static void Main() 
    { 
     int countMAX = 0; 
     int num = 0; 

     for (int i = 2; i <= 1000000; i++) 
     { 
      int count = 1; 

      int temp = i; 

      while (temp != 1) 
      { 
       if(temp % 2 == 0) temp /= 2; 
       else temp = temp * 3 + 1; 
       count++; 
      } 

      if(count > countMAX) 
      { 
       countMAX = count; 
       num = i; 
      } 
     } 

     Console.WriteLine("Number: " + num + " Hops: " +countMAX); 
    } 
} 

快速(在線):

using System; 

public class Program 
{ 
    public static void Main() 
    { 
     const int number = 1000000; 

     long sequenceLength = 0; 
     long startingNumber = 0; 
     long sequence; 

     for (int i = 2; i <= number; i++) 
     { 
      int length = 1; 
      sequence = i; 
      while (sequence != 1) 
      { 
       if ((sequence % 2) == 0) 
       { 
        sequence = sequence/2; 
       } 
       else 
       { 
        sequence = sequence * 3 + 1; 
       } 

       length++; 
      } 

     //Check if sequence is the best solution 
      if (length > sequenceLength) 
      { 
       sequenceLength = length; 
       startingNumber = i; 
      } 
     } 

     Console.WriteLine("Num: " + startingNumber + " Count: " + sequenceLength); 
    } 
} 

我測試.NET Fiddle,其中my solution收到以下錯誤

Fatal Error: Execution time limit was exceeded

other solution打印正確的結果

Num: 837799 Count: 525

他們應該做同樣的事情1:1。任何人有想法?

+4

看起來更像代碼審查問題的OverflowException。您可以先將變量均等地命名,以便代碼更易於比較。 – CodeCaster

+2

你是如何測試兩者的表現的? –

+2

100000 <1000000 –

回答

5

造成差異的原因似乎是int vs long。我不知道使用int的慢代碼是否正在遭受一個溢出錯誤,使得它的循環時間更長,並且使用long使其不會溢出。具體而言,long sequence(快速版)vs int temp = i;(慢版)。如果你使用long temp = i;它就像快速代碼一樣工作。

果然,如果我們在checked塊包裝代碼,它拋出就行else temp = temp * 3 + 1;

+0

你是對的!!那麼爲什麼要使用int?我的意思是一般其他項目也 – Unfrieden

+0

1:becaus在大多數情況下,'int'綽綽有餘; 2:因爲它速度越來越快(如果你處理量很大,這可能很重要); 3:因爲它保證在x86上是原子的(沒有被破壞)(對於仍然需要32位的人),4:與使用32位整數的系統的二進制兼容性 –

+0

是的,我現在明白了,謝謝! – Unfrieden