Last active
December 15, 2015 20:58
-
-
Save KodeSeeker/5321888 to your computer and use it in GitHub Desktop.
Obtain the rational number from a decimal number . E.g .125 is expressed as 1/8
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public static String GetRational(double a) | |
| { //.125 | |
| boolean isNegative; | |
| if(a<0){// if a is negative then set flag | |
| isNegative=true; | |
| a=-a; | |
| } | |
| int tenPoly=1; | |
| // compute the largest power of 10 that divides 'a' completely | |
| while(a*tenPoly-(int)(a*tenPoly)!=0) | |
| tenPoly*=10; | |
| } | |
| // compute the dividend and the divisor | |
| int dividend= a*tenPoly; | |
| int divisor=tenPoly; | |
| int gcd; | |
| if(dividend>divisor) | |
| gcd= GCD(dividend,divisor) | |
| else | |
| gcd=GCD(divisor,dividend); | |
| // make the dividend and divisor pretty | |
| dividend/=gcd; | |
| divisor/=gcd; | |
| String output=dividend+"/"+divisor; | |
| if(isNegative) | |
| output="-"+output; | |
| return (" the rational number is "+output); | |
| } | |
| //defined as private method for supporting method only, define as public for out of class invokation | |
| //let's assume a>=b | |
| private static int GCD(int a, int b) | |
| { | |
| int remainder= a%b; | |
| if(remainder==0) | |
| return b; | |
| else | |
| return GCD(b,remainder); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment