Last Updated: 20 Feb, 2021

Complex Number Class

Moderate
Asked in company
Microsoft

Problem statement

A ComplexNumber class contains two data members: one is the real part (R) and the other is imaginary (I) (both integers).

Implement the Complex numbers class that contains the following functions -

1. constructor

You need to create the appropriate constructor.

2. plus -

This function adds two given complex numbers and updates the first complex number.

e.g.

if C1 = 4 + i5 and C2 = 3 +i1
C1.plus(C2) results in: 
C1 = 7 + i6 and C2 = 3 + i1
3. multiply -

This function multiplies two given complex numbers and updates the first complex number.

e.g.

if C1 = 4 + i5 and C2 = 1 + i2
C1.multiply(C2) results in: 
C1 = -6 + i13 and C2 = 1 + i2
4. print -

This function prints the given complex number in the following format :

a + ib

Note: There is space before and after '+' (plus sign) and no space between 'i' (iota symbol) and b.

Input Format :
The first line of the input contains two integers - real and imaginary part of 1st complex number.

The second line of the input contains Two integers - the real and imaginary part of the 2nd complex number.

The first line of the input contains an integer representing choice (1 or 2) (1 represents plus function will be called and 2 represents multiply function will be called)
Output format :
The only line of the output prints the complex number in the following format a + ib

Approaches

01 Approach

In this problem, we have to add or multiply the given complex numbers based on the choice.

 

  • First, create a parameterized constructor which sets the real and imaginary part of the number.
  • Then create a plus function in ComplexNumbers class which adds the two complex numbers: the two complex numbers are added like the real part of both the numbers is added, and the imaginary part of both the numbers is added, and the result will be the output.

e.g.  

   if C1 = 4 + i5 and C2 = 3 +i1

   C1.plus(C2) results in:  

   C1 = 7 + i6 and C2 = 3 + i1

 

  • Next we will create multiply function in ComplexNumbers class this function will multiply the two complex numbers: the two numbers are multiplied like (a+ib)*(c+id)=ac+(ad+cb)i-bd

e.g.  

   if C1 = 4 + i5 and C2 = 1 + i2

   C1.multiply(C2) results in:  

   C1 = -6 + i13 and C2 = 1 + i2

 

And finally, we create a print function that prints the result in the complex number form.