java - Why is this program running so slowly? -


this project euler problem 14.

when number even, you're supposed divide number two, when odd multiply 3 , add one. should reach one.

my task find number takes largest amount of steps 1.

here's code:

    int currentnum = 0;     int iterator = 0;     int[] largestchain = new int[]{0,0};     for(int = 10;i<=1000000;i++)     {         currentnum = i;         iterator = 0;         while(currentnum!=1)         {             iterator++;             if(currentnum%2==0)             {                 currentnum/=2;             }             else             {                 currentnum = (currentnum*3)+1;             }         }         if(iterator>largestchain[1])         {             largestchain[0] = i;             largestchain[1] = iterator;         }     }      system.out.println("largest iterator:"+largestchain[1]+"for num:"+largestchain[0]); 

can please me out telling me what's slowing down? (it's taking >30 minutes right , still hasn't come answer).

use long variables instead of int. currentnum goes high values wrap around negatives!

once change, algorithm works fine. (i tested it)


Comments

Popular posts from this blog

php - render data via PDO::FETCH_FUNC vs loop -

c++ - OpenCV Error: Assertion failed <scn == 3 ::scn == 4> in unknown function, -

The canvas has been tainted by cross-origin data in chrome only -