-
Notifications
You must be signed in to change notification settings - Fork 2
/
Rational.scala
52 lines (36 loc) · 1.51 KB
/
Rational.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package rationalOperations
import integerOperations.IntegerProperties._
/**
* Contains operations in a field of rational numbers.
*
* Purity project by Daniil Tekunov.
*/
class Rational(numerator: Int, denominator: Int) {
require(denominator != 0)
private val gcd = numerator.abs gcdWith denominator.abs
private val num: Int = numerator / gcd
private val denom: Int = denominator / gcd
override def toString: String = num + "/" + denom
def this(firstInt: Int) = this(firstInt, 1)
def +(secondRational: Rational) = new Rational(
num * secondRational.denom + secondRational.num * denom,
denom * secondRational.denom)
def *(secondRational: Rational) = new Rational(
num * secondRational.num,
denom * secondRational.denom)
def /(secondRational: Rational) = new Rational(
num * secondRational.denom,
denom * secondRational.num)
def -(secondRational: Rational) = new Rational(
num * secondRational.denom - secondRational.num * denom,
denom * secondRational.denom)
def >(secondRational: Rational): Boolean =
this.num * secondRational.denom > this.denom * secondRational.num
def <(secondRational: Rational): Boolean =
this.num * secondRational.denom < this.denom * secondRational.num
def >=(secondRational: Rational): Boolean =
this.num * secondRational.denom >= this.denom * secondRational.num
def <=(secondRational: Rational): Boolean =
this.num * secondRational.denom =< this.denom * secondRational.num
def sqr = new Rational(num * num, denom * denom)
}