// Arup Guha
// 3/8/2026
// Solution to COP 3330 Quiz #3 Questions 1 - 6.
/*** Modified to show the use of an user made Exception ***/

public class ComplexNumber {

    private double a;
    private double b;

    public ComplexNumber(double real) {
        a = real;
        b = 0;
    }

    public ComplexNumber(double real, double img) {
        a = real;
        b = img;
    }
	
	// Returns the magnitude squared of this complext number.
	public double magSq() {
		return a*a + b*b;
	}
	
    // Returns the sum of this and other.
	public ComplexNumber add(ComplexNumber other) {
		return new ComplexNumber(a+other.a, b+other.b);
	}
	
    // Returns the difference between this and other
	public ComplexNumber subtract(ComplexNumber other) {
		return new ComplexNumber(a-other.a, b-other.b);
	}
	
	// Returns the product of this and other.
	public ComplexNumber multiply(ComplexNumber other) {

		// Real component is product of a's, imaginary component is
		// negated since i squared is -1.
		double real = a*other.a - b*other.b;
		
		// This is just what happens when you FOIL.
		double img = a*other.b + b*other.a;

		// Here is our result.
		return new ComplexNumber(real, img);
	}
	
	// Returns the complex conjugate of this object.
	public ComplexNumber conjugate() {
		return new ComplexNumber(a, -b);
	}

	// Returns the result of dividing this by other.
	public ComplexNumber divide(ComplexNumber other) throws DivideByZeroException {
	
		// This helps make the denominator real.
		ComplexNumber term = other.conjugate();
		
		// The numerator of our answer.
		ComplexNumber num = this.multiply(term);
		
		// Compute the denominator.
		double den = term.magSq();
		
		// This would cause a problem.
		if (Math.abs(den) < 1e-9)
			throw new DivideByZeroException("You can not divide by 0+0i.");
		
		// This is the way we're forced to do this.
		return new ComplexNumber(num.a/den, num.b/den);
	}
	
	// Answer to question #6, returns this raised to the power exp.
	public ComplexNumber pow(int exp) {
	
		// Start with the identity.
		ComplexNumber res = new ComplexNumber(1, 0);
		
		// Multiply this in the correct number of times.
		for (int i=0; i<exp; i++)
			res = res.multiply(this);
		return res;
	}
	
	// For testing.
	public String toString() {
		return "("+a+ " + "+b+"i)";
	}
}
