Advanced Java, 1819T3

Surd.java

What is a surd? It is a real number of the form \(a + b\sqrt{n}\), where \(a\) and \(b\) are integers. The value \(n\) is called the surd value. This value must be a square-free number and we must have \(n > 2\). Surds with the same surd value are closed under multiplication and addition; to wit, the sum or product of two surds of wiht the same surd value is another surd with the same surd value. We show this for addition

$$a + b\sqrt{n} + c + d\sqrt{n} = (a + c) + (b + d)\sqrt{n}.$$

and for multiplication

$$(a + b\sqrt{n})(c + d\sqrt{n}) = (ac + bdn) + (ad + bc)\sqrt{n}. $$

If \(n\) is not square-free or if \(n < 2\), you will throw an IllegalArgumentException. If you attempt to add or multiply surds with diffent surd values, throw an IllegalArgumentException.

If $\(a + b\sqrt{n}\)$ is a surd, we define its conjugate to be $\(a - b\sqrt{n}\)$. You will also create a negate() method that computes the additive inverse of a surd.

You will create standard equals and toString() methods as well.

You will write a private static method to check to see if an integer \(n \ge 2\) is square-free.

A Spin in jshell

jshell> /open Surd.java
  
jshell> Surd s = new Surd(1,1, 2);
s ==> 1 + 1\sqrt{2}

jshell> Surd t = new Surd(2,3, 2);
t ==> 2 + 3\sqrt{2}

jshell> System.out.println(s.add(t));
3 + 4\sqrt{2}

jshell> System.out.println(s.subtract(t));
-1 - 2\sqrt{2}

jshell> System.out.println(s.multiply(t));
8 + 5\sqrt{2}

jshell> System.out.println(s.pow(10));
3363 + 2378\sqrt{2}

jshell> s.negate()
$8 ==> -1 - 1\sqrt{2}

jshell> s.conjugate()
$9 ==> 1 - 1\sqrt{2}

jshell> s.equals("Ham Sandwich")
$10 ==> false

jshell> Surd u = new Surd(2,3,2);
u ==> 2 + 3\sqrt{2}

jshell> t.equals(u)
$12 ==> true

jshell> s.equals(u)
$12 ==> false

API Specs The Javadoc for this class can be found here.

Amusing Question for the Adventurous For surds with surd value \(n = 2\), can you find a surd that is not equal to \(1 + 0\sqrt{2}\) that has a multiplicative inverse? Can you find an infinitude of these?