0

question on lowest term fraction using java

when the numerator is 5 and the denominator is 20 I get the value of 1/4, but when the numerator is 20 and the denominator is 5 I get the value of 0/0 my workbook said, it's supposed to be 4/1. here's my code void determineLowestTerm(){ //code here for(int i = getNum(); 1 > 0; i--){ if((getNum() % i == 0) && (getDen() % i==0)){ System.out.println("\t LOWEST TERM \t\t: " + (getNum()/i) + "/" + (getDen()/i)); break; }else System.out.println("\t LOWEST TERM \t\t: " + "0" + "/" + "0"); break; } } //end lowestterm

3rd Mar 2019, 1:47 PM
Jefferson Villanueva
Jefferson Villanueva - avatar
2 odpowiedzi
+ 18
● seeing your code, I think you should first find whether numerator is having absolute smaller value or denominator ● after that run a loop for i from 1 to (smaller value among numerator & denominator) & in each iteration use condition (numerator%i==0 && denominator%i==0) , if this condition evaluates to true then do {numerator=numerator/i; denominator=denominator/i;} //just need to divide both numerator & denominator by the common factors.
3rd Mar 2019, 4:40 PM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 6
In your for loop you have 1 > 0 instead of i > 0. Maybe a typo. If I'm right? getNum () = 20 getDen () = 5 at the beginning i = 20 20% 20 = 0; 20%5 = 0 true getNum () = 5 getDen () = 20 i = 5 5% 5 = 0 5% 20 = 5 false break; --> you leave the loop so i can not change. I would try this: compare getNum with getDen () --> i = highest num getNum = 5 getDen = 20 i = 20 (getDen > getNum) 20% 5 = 0 20% 20 = 0 true print i/getNum and i/getDen
3rd Mar 2019, 2:10 PM
Denise Roßberg
Denise Roßberg - avatar