c# - Own code noticeably slower than others -


the code wrote slower (max time exceeded) code found online, if online code looks more bloated.

so trap did step code looks cleaner slowed down somehow?

slow (mine):

using system;  public class program {        public static void main()     {         int countmax = 0;         int num = 0;          (int = 2; <= 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);     } } 

fast (online):

using system;  public class program {        public static void main()     {         const int number = 1000000;          long sequencelength = 0;         long startingnumber = 0;         long sequence;          (int = 2; <= 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 best solution             if (length > sequencelength)              {                 sequencelength = length;                 startingnumber = i;             }         }          console.writeline("num: " + startingnumber + " count: " + sequencelength);     } } 

i tested on .net fiddle, my solution following error

fatal error: execution time limit exceeded

and other solution print correct result

num: 837799 count: 525

they should doing same thing 1:1. has idea?

the thing makes difference seems int vs long. wonder if slow code using int suffering overflow bug making loop far far longer, , using long makes not overflow. specifically, long sequence (fast version) vs int temp = i; (slow version). if use long temp = i; works fast code.

sure enough, if wrap code in checked block, throws overflowexception on line else temp = temp * 3 + 1;


Comments

Popular posts from this blog

account - Script error login visual studio DefaultLogin_PCore.js -

xcode - CocoaPod Storyboard error: -