algorithm - Euler Project 5 in java, why is there a different result? -


/* smallest multiple */ /*  * 2520 smallest number can divided each  *  of numbers 1 10 without remainder.what   *  smallest positive number evenly divisible   *  of numbers 1 20?  */ public class smallestmultiple {     public static int gcd(int m, int n){         if(n>m){             int temp = m;             m = n;             n = temp;         }         int gcdnum = m;         while(m != 0){             m = gcdnum%n;             gcdnum = n;             n = m;         }         return gcdnum;     }     private static int lcm(int m, int n){         return m*n/gcd(m,n);     }     static int multiple(int start, int end){         if(start > end){             int temp = end;             end = start;             start = temp;         }         else if(start == end)             return start;         else             return lcm(end, multiple(start, end-1));         return multiple(start, end);     }     public static void main(string[] args) {         system.out.println(multiple(11,19)); // line a--which equal multiple(1,19)          system.out.println(multiple(11,20)); // line b--which equal multiple(1,20)     } } 

i think answer multiple(1,19) , multiple(1,20) same result. code, different, multiple(1,19)=232792560(the right answer)and multiple(1,20)=18044195 wrong answer!!! know there many more simple algorithms, want know problem... can tell me problem?

you have int overflow when compute

prelude> 232792560 * 20 4655851200 prelude> `quotrem` (2^32) (1,360883904) 

thus obtain 360883904 / 20 = 18044195.

you can

  • use long or
  • compute m * (n/gcd(n,m))

to avoid overflow (the second method won't take farther, if upper limit 23, int small hold result).


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -