Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Info
- // Info
- public class Main {
- public static void main(String[] args) {
- Rational a = new Rational(8,-7);
- Rational b = new Rational(4,6);
- System.out.println(a + " + " + b + " = " + a.addition(b));
- System.out.println(a + " - " + b + " = " + a.subtraction(b));
- System.out.println(a + " * " + b + " = " + a.multiplication(b));
- System.out.println(a + " / " + b + " = " + a.division(b));
- }
- }
- class Rational {
- private int num;
- private int denu;
- public Rational(int x, int y) {
- // Now there will never be a fraction with denominator 0
- if(y == 0){
- y = 1;
- }
- // if it is 3/-4; make it -3/4
- if(y < 0){
- y *= -1; // same thing as y = y * -1;
- x = x * -1;
- }
- num = x;
- denu = y;
- // Now reduce fractions so that 4/8 is stored as 1/2 instead
- reduce();
- }
- public int getNumerator(){
- return num;
- }
- public int getDenominator(){
- return denu;
- }
- public void setNumerator(int n){
- num = n;
- }
- public void setDenominator(int d){
- denu = d;
- }
- public Rational addition(Rational f) {
- Rational result;
- result = new Rational (num*f.denu + f.num*denu, denu*f.denu );
- return result;
- }
- public Rational division(Rational f) {
- Rational result;
- result = new Rational (num*f.denu, denu*f.num);
- return result;
- }
- public Rational multiplication(Rational f) {
- Rational result;
- result = new Rational (num*f.num,denu*f.denu);
- return result;
- }
- public Rational subtraction(Rational f) {
- Rational result;
- result = new Rational (num*f.denu - f.num*denu, denu*f.denu );
- return result;
- }
- public String toString() {
- return "(" + num + "/" + denu + ")";
- }
- private void reduce(){
- int x = num;
- if(x < 0){
- x *= -1;
- }
- int y = denu;
- int gcd = gcd(x, y);
- num /= gcd;
- denu /= gcd;
- }
- private int gcd(int x, int y){
- for(; x != y;){
- if(x > y){
- x -= y;
- }
- else{
- y -= x;
- }
- }
- return x;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement