Answered step by step
Verified Expert Solution
Question
1 Approved Answer
//GCD.java import java.util.Scanner; public class GCD { public static int gcd(int a, int b){ if (b != 0) return gcd(b, a%b); else return a; }
//GCD.java import java.util.Scanner; public class GCD { public static int gcd(int a, int b){ if (b != 0) return gcd(b, a%b); else return a; } public static void main(String args[]) { int num1, num2; Scanner in = new Scanner(System.in); System.out.print("Enter number1: "); num1 = in.nextInt(); System.out.print("Enter number2: "); num2 = in.nextInt(); System.out.println("gcd = "+gcd(num1,num2)); } }
Add this method to your Rational class below and call it at appropriate times to simplify your fractions.
public class Rational { private int num; private int denom; public Rational() { num = 0; denom = 1; } public Rational(int num, int denom) { this.num = num; this.denom = denom; } int getNum() { return num; } int getDenom() { return denom; } public Rational add(Rational rhs) { return new Rational(num * rhs.denom + rhs.num * denom, denom * rhs.denom); } public Rational subtract(Rational rhs) { return new Rational(num * rhs.denom - rhs.num * denom, denom * rhs.denom); } public Rational multiply(Rational rhs) { return new Rational(num * rhs.num, denom * rhs.denom); } public Rational divide(Rational rhs) { return new Rational(num * rhs.denom, rhs.num * denom); } public String toString() { return num + "/" + denom; } public static void main(String[] args) { Rational r1 = new Rational(1, 2); // 1/2 Rational r2 = new Rational(3, 4); // 3/4 Rational result = new Rational(); result = r1.add(r2); System.out.println(result); // etc } }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started