In this tutorial, we will learn how to multiply two complex numbers in the cpp language. The Complex number consists of the real and imaginary parts. It is expressed in the form of (a+ib).
Complex Number Multiplication
We will solve this problem by using different methods. Some of them are :
Method 1
CODE:
- Include a header file complex that performs the complex number arithmetic on two complex values or more.
- Declare a variable of type
complex
. Thedouble
parameter indicates that the real and imaginary parts are stores in the double data type.
#include <iostream> #include <complex> using namespace std; int main() { complex<double> z1(2.0, 3.0); complex<double> z2(4.0, -1.0); complex<double> z3 = z1 * z2; cout << "Product of two numbers: " << real(z3) << "+" << imag(z3) << "i" <<endl; return 0; }
OUTPUT:
Product of two numbers: 11+10i
Method 2
CODE:
- Create a
function
of data typestring
having two inputsnum1
&num2
. - Two
loops
iterate over the inputstring
to find the positions of the'+'
characters. These positions are stored inp1
&p2
respectively. - Using
substr
andstoi
, the real and imaginary parts of both complex numbers are extracted as integers and stored in variablesa
,b
,c
, andd
. - The real and imaginary parts of the product are calulated and stored in the
real
&imag
.
#include <iostream> using namespace std; string multiply(string num1, string num2) { int p1=0, p2=0; for(int i=0; i<num1.size(); i++){ if(num1[i] == '+'){ p1 = i; break; } } for(int i=0; i<num2.size(); i++){ if(num2[i] == '+'){ p2 = i; break; } } int a = stoi(num1.substr(0,p1)); int b = stoi(num1.substr(p1+1)); int c = stoi(num2.substr(0,p2)); int d = stoi(num2.substr(p2+1)); int real = (a*c) - (b*d); int imag = (b*c) + (a*d); string ans=""; ans += to_string(real); ans += "+"; ans += to_string(imag); ans += "i"; return ans; } int main() { string num1 = "2+3i"; string num2 = "4+5i"; cout << "Product of two numbers is : "<<multiply(num1,num2); return 0; }
OUTPUT:
Product of two numbers is : -7+22i