C# Add 2 Complex Numbers

complex number is a number that can be expressed in the form a + bi, where a and b are real numbers, and i is a solution of the equation x2 = −1. Because no real number satisfies this equation, i is called an imaginary number. For the complex number a + bia is called the real part, and b is called the imaginary part. Despite the historical nomenclature “imaginary”, complex numbers are regarded in the mathematical sciences as just as “real” as the real numbers, and are fundamental in many aspects of the scientific description of the natural world. (wiki)

Complex numbers allow solutions to certain equations that have no solutions in real numbers.

For example, the equation

{\displaystyle (x+1)^{2}=-9}

has no real solution, since the square of a real number cannot be negative.

Complex numbers provide a solution to this problem. The idea is to extend the real numbers with an indeterminate i (sometimes called the imaginary unit) that is taken to satisfy the relation i2 = −1, so that solutions to equations like the preceding one can be found.

In this case the solutions are −1 + 3i and −1 − 3i, as can be verified using the fact that i2 = −1:

{\displaystyle ((-1+3i)+1)^{2}=(3i)^{2}=\left(3^{2}\right)\left(i^{2}\right)=9(-1)=-9,}
{\displaystyle ((-1-3i)+1)^{2}=(-3i)^{2}=(-3)^{2}\left(i^{2}\right)=9(-1)=-9.}

 

using System;

public struct Complex
{
    public int real;
    public int imaginary;

    public Complex(int real, int imaginary)
    {
        this.real = real;
        this.imaginary = imaginary;
    }


    public static Complex operator +(Complex c1, Complex c2)
    {
        return new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary);
    }


    public override string ToString()
    {
        return (String.Format("{0} + {1}i", real, imaginary));
    }
}

class TestComplex
{
    static void Main()
    {
        Complex num1 = new Complex(2, 3);
        Complex num2 = new Complex(3, 4);
        Complex sum = num1 + num2;

        Console.WriteLine("First Complex Number:  {0}", num1);
        Console.WriteLine("Second Complex Number: {0}", num2);
        Console.WriteLine("The Sum of the Two Numbers: {0}", sum);

        Console.ReadLine();
    }
}

 

Output