java - How can I reduce run time Q12 Project Euler -
my code takes way long run. i've tried loop way large number , loop ip find it's sum loop check divisors.how optimise it?
public class q12 { public static void main(string[] args) { int answer=5; boolean check=false; int sum=0; int counter=0; int kk=0; while(check==false) { loop: for(int i=1;i<50000000;i++) { sum=0; counter=0; for(int j=0;j<i;j++) { sum=j+sum; } for(int k=1;k<sum;k++) { if(sum%k==0) { counter=counter+1; } } if(counter>=501) { check=true; break loop; } } } } }
thanks
it's not obvious yours code supposed do, i'm doubt can optimize there...
this portion:
check=true; break loop;
breaks execution , jumps to
loop: for(int i=1;i<50000000;i++)
which run inner loop 50000000 iterations again, after
check
evaluated. intended behaviour?here:
sum=0; counter=0; for(int j=0;j<i;j++) { sum=j+sum; }
you can use caching. like:
long[] precalc = new long[50000000]; int answer=5; boolean check=false; int sum=0; int counter=0; int kk=0; while(check==false) { loop: for(int i=1;i<50000000;i++) { sum = precalc [i]; if (sum == 0) { precalc[i] = sum = (precalc[i - 1] + i); } counter=0; ...
also suggest use
long
-s instead ofint
-s, there possible arithmetic overflow.
Comments
Post a Comment