Complex numbers are numbers that consist of two parts — a real number and an imaginary number. Complex numbers are the building blocks of more intricate math, such as algebra. The standard format for complex numbers is a + bi, with the real number first and the imaginary number last.
General form for any complex number is:
a+ib
Where "a" is real number and "b" is Imaginary number.
Construction of Complex number
For creating a complex numbers, we will pass imaginary numbers and real numbers as parameters for constructors.
Java
class ComplexNumber {
int real, image;
public ComplexNumber( int r, int i)
{
this .real = r;
this .image = i;
}
public void showC()
{
System.out.println( this .real + " +i " + this .image);
}
public complex add(ComplexNumber, ComplexNumber);
}
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Add function
- Basically, addition of two complex numbers is done by adding real part of the first complex number with real part of the second complex number.
- And adding imaginary part of the first complex number with the second which results into the third complex number.
- So that means our add() will return another complex number.
Ex. addition of two complex numbers
(a1) + (b1)i —–(1)
(a2)+ (b2)i —–(2)
adding (1) and (2) will look like
(a1+a2) + (b1+b2)i
Function Definition:
ComplexNumber add(ComplexNumber n1, ComplexNumber n2){
ComplexNumber res = new ComplexNumber(0,0); //creating blank complex number
// adding real parts of both complex numbers
res.real = n1.real + n2.real;
// adding imaginary parts
res.image = n1.image + n2.image;
// returning result
return res;
}
Code:
Java
class ComplexNumber {
int real, image;
public ComplexNumber( int r, int i)
{
this .real = r;
this .image = i;
}
public void showC()
{
System.out.print( this .real + " +i" + this .image);
}
public static ComplexNumber add(ComplexNumber n1,
ComplexNumber n2)
{
ComplexNumber res = new ComplexNumber( 0 , 0 );
res.real = n1.real + n2.real;
res.image = n1.image + n2.image;
return res;
}
public static void main(String arg[])
{
ComplexNumber c1 = new ComplexNumber( 4 , 5 );
ComplexNumber c2 = new ComplexNumber( 10 , 5 );
System.out.print( "first Complex number: " );
c1.showC();
System.out.print( "\nSecond Complex number: " );
c2.showC();
ComplexNumber res = add(c1, c2);
System.out.println( "\nAddition is :" );
res.showC();
}
}
|
Output
first Complex number: 4 +i5
Second Complex number: 10 +i5
Addition is :
14 +i10
Time Complexity: O(1)
Auxiliary Space: O(1)
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
13 Jul, 2022
Like Article
Save Article