math - What is the name for this, and how to calculate in Java? -


i'm not mathematical terminology.

what called?

say have number 48, need find 2 factors make 48. in 48 8,6 in 72 9,8

i don't want 12,4 48, or 12,6

there no particular name pair of factors smallest distance. it's easy calculate if that's want. (at least easy factoring in general goes small numbers it's trivial.)

here's 1 way (which fastest when 2 factors close together.) it's based on fermat's factoring algorithm.

static int sqrroot(int n){     //find largest square <= n     int sqr = 0;      (int i=15; >= 0; --i){         int newsqr = sqr + (1<<i);         if (newsqr * newsqr <= n) {sqr = newsqr;}     }      return sqr; }  static int[] closestfactors(int n){     if (n <= 0) {throw new illegalargumentexception();}      int s = sqrroot(n);     if (s*s == n){         int[] ans = {s,s};         return ans;     }      int = s * s - n;           while(s < n){         if (a > 0){ //may not true on first iteration             int sa = sqrroot(a);             //whole number case             if (sa*sa == a){    //we found factorization                 int[] ans = {s-sa, s+sa};                 return ans;             }         }          //half number case         int sa2 = sqrroot(a+s);         if (sa2 * (sa2+1) == a+s){             int[] ans = {s-sa2, s+sa2+1};             return ans;         }          += s + s + 1;         s++;     }      int[] ans = {1, n};     return ans; } 

Comments

Popular posts from this blog

c# - SVN Error : "svnadmin: E205000: Too many arguments" -

c# - Copy ObservableCollection to another ObservableCollection -

All overlapping substrings matching a java regex -