×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Java
Posted by: Shamir Yona
Added: Sep 23, 2015 3:28 PM
Views: 6
Tags: java gcd fraction
  1. private static void findRatio(double val, double tolerance)
  2. {
  3.    int numerator, denominator;
  4.  
  5.    int tenMult = 1;
  6.    double multRes;
  7.    int intVal;
  8.  
  9.    // Multiply the input value by 10**n until the result is greater than 1:
  10.    while (true)
  11.    {
  12.        multRes = val * tenMult;
  13.        intVal = ((Double) multRes).intValue();
  14.        if (intVal == multRes)
  15.            break;
  16.        if (intVal == Math.ceil(multRes))
  17.            break;
  18.        tenMult *= 10;
  19.    }
  20.    int gcdVal = gcd(intVal, tenMult);
  21.    if (gcdVal > 0)
  22.        System.out.format("Input Value: %f - %d / %d\n", val, intVal/gcdVal, tenMult/gcdVal);
  23. }
  24.  
  25. private static int gcd(int n, int m)
  26. {
  27.     int div, mod;
  28.     if (m == 0)
  29.         return (n);
  30.  
  31.     if (n > m)
  32.     {
  33.         div = m;
  34.         mod = n % m;
  35.     }
  36.     else {
  37.         div = n;
  38.         mod = m % n;
  39.     }
  40.     return (gcd(div, mod));
  41. }
  42.