Skip to content

Instantly share code, notes, and snippets.

@nort3x
Forked from Ninayd/Complex Numbers
Last active February 3, 2022 18:07
Show Gist options
  • Select an option

  • Save nort3x/1d1b3698d6fc09b679c6b3269a192cd5 to your computer and use it in GitHub Desktop.

Select an option

Save nort3x/1d1b3698d6fc09b679c6b3269a192cd5 to your computer and use it in GitHub Desktop.
naming the file the right way
class Complex(private var real: Double, private var image: Double) {
// empty constructor
constructor() : this(0.0, 0.0);
operator fun plus(C: Complex): Complex {
return Complex(this.real + C.real, this.image + C.image)
}
operator fun minus(C: Complex): Complex {
return Complex(this.real - C.real, this.image - C.image)
}
operator fun times(C: Complex): Complex {
val newReal = (this.real * C.real) - (this.image * C.image)
val newImage = (this.image * C.real) + (this.real * C.image)
return Complex(newReal, newImage)
}
operator fun times(c: Double): Complex {
return Complex(this.real * c, this.image * c);
}
override fun toString(): String {
return "${this.real}+${this.image}i"
}
operator fun unaryMinus(): Complex {
return Complex(-real, -image)
}
// conjugate
operator fun not(): Complex {
return Complex(this.real, -this.image);
}
}
fun main(args: Array<String>) {
val c1 = Complex(2.0, 3.0)
val c2 = Complex(4.0, 5.0)
println("Complex plus operator used on C1,C2:${c1 + c2}")
println("Complex minus operator used on C1,C2:${c1 - c2}")
println("Complex times operator used on C1,C2:${c1 * c2}")
println("Complex times constant(3) overloaded operator used on C1:${c1 * 3.0}")
println("Complex not operator used on C1 (conjugate):${!c1}")
println("Complex minusUnary operator used on C1 (minus):${-c1}")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment