java simplify fraction code example

Example: simplify fractions in java

//only works with even fractions 
//definitly a more efficant way but its working for me 
//fraction must be split into numerator and denominator
float numerator = 4;
float denominator = 8;
while(1==1){
//devides the numerator and the denomenator by 2 (or whatever number you put)
  numerator = numerator/2; 
  denominator = denominator/2;
  
  //if after deviding by 2 both the numerator and the denominator are whole numbers it will loop and devide and check them again
  if(numerator == (int)numerator && denominator ==(int)denominator){
    println("good"); 
  }
 //if after being devided by 2 either the numerator or the denomerator are not whole numbers
  else{ 
    //both are multiplied by 2 to make them go back to being their simplest  whole number
    numerator = numerator*2;  
    denominator = denominator*2;
    
 //the fraction is simplifies and saved to the ints Simple_numerator and Simple_denominator and the loop stops
    int Simple_numerator = int(numerator);
    int Simple_denominator = int(denominator);
    println(Simple_numerator + "/" + Simple_denominator);
   break; 
  }
 }

Tags:

Java Example