-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathComplex.java
More file actions
44 lines (37 loc) · 989 Bytes
/
Complex.java
File metadata and controls
44 lines (37 loc) · 989 Bytes
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
public class Complex {
private final int re;
private final int im;
public Complex(int real, int imag) {
re = real;
im = imag;
}
public Complex plus(Complex b) {
int real = re + b.re;
int imag = im + b.im;
return new Complex(real, imag);
}
public Complex times (Complex b) {
int real = re * b.re - im * b.im;
int imag = re * b.im + im * b.re;
return new Complex(real, imag);
}
public String toString () {
if (im == 1) {
return re + " + i";
} else {
return re + " + " + im + "i";
}
}
public static void main(String[] args) {
Complex a = new Complex(1, 1);
Complex z = a;
StdOut.println(a);
StdOut.println(z);
z = z.times(z).plus(a);
StdOut.println(a);
StdOut.println(z);
z = z.times(z).plus(a);
StdOut.println(a);
StdOut.println(z);
}
}