Getting the smallest possible integer ratio between two numbers I wrote this code to find the smallest possible integer ratio between two numbers:

void ratio(int a, int b) {
    int min = Math.min(a, b);
    int max = Math.max(a, b);
    if(max % min == 0) {
               System.out.println("1" + " " + max / min);
               return;
        }
    for (int i = 2; i &lt;= min; i++) {
        while(max % i == 0 &amp;&amp; min % i == 0) {
            max /= i;
            min /= i;
        }
    }
    System.out.println(max + " " + min);
}


Is there any better/efficient way to do this? Am I missing any good algorithm?
You need to find the GCD and then divide both numbers by that.

Euclid's algorithm is the classic way to do this.

int gcd(int p, int q) {
    if (q == 0) return p;
    else return gcd(q, p % q);
}

void ratio(int a, int b) {
   final int gcd = gcd(a,b);
   System.out.println(a/gcd + " " + b/gcd);
}


If you want to swap a and b to have the biggest first then that's easy too

void ratio(int a, int b) {
   final int gcd = gcd(a,b);
   if(a &gt; b) {
       showAnswer(a/gcd, b/gcd);
   } else {
       showAnswer(b/gcd, a/gcd);
   }
}

void showAnswer(int a, int b) {
   System.out.println(a + " " + b);
}