can any1 pls help me wth a logic to use in java pgm to reduce a fraction...???? for example...if the input is 5/10...the output must be 1/2...
Use their greatest common factor. If you want logic, it should be like this: For x/y, find out if the GCF of x and y is greater than 1. If it is, then divide both x and y with the GCF.
you can use the euclidean algorithm for calculating the gcd/gcf... look it up on wikipedia http://en.wikipedia.org/wiki/Euclidean_algorithm
You could also use modular arithmetic. Mods return the remainder of some operation. The operator for this in Java is the "%" sign. For example, 10 % 2 would be 0 because 2 evenly divides into 10. What you could do is save the numerator and denominator as ints and then use some "if-else" statements incorporating mods to reduce the fraction to its smallest parts.
//concept is to take numerator and denominator in two seperate variables and then // loop from 2 to numerator/2 or denominator/2 and check for each value which divides both numerator and denominator // if we find it then we divide it and update the new denominator and numerator import java.util.Scanner; class nd { public static void main(String arg[]) { Scanner sc=new Scanner(System.in); System.out.print("Enter the numerator :"); int num=sc.nextInt(); System.out.print("Enter the Denominator"); int den=sc.nextInt(); if(num>den) { for(int i=2;i<num/2;i++) { if(num%i==0 && den%i==0) { num=num/i; den=den/i; } } System.out.print("The result is :"+num+"/"+den); } if(den>num) { for(int i=2;i<den/2;i++) { if(num%i==0 && den%i==0) { num=num/i; den=den/i; } } System.out.print("The result is :"+num+"/"+den); } } }
this is the most simple logic and remember tools are the same, u can use any language and always avoid complex programs, just logically think of a problem
Join our real-time social learning platform and learn together with your friends!