Complex Number Multiplication in C++

C++Server Side ProgrammingProgramming

Suppose we have two strings that are representing complex numbers, we have to parse them and perform complex number multiplication, then return result as a string.

So if the input is like “1+-1i” and “1+-1i”, then the result will be “0+-2i”.

To solve this, we will follow these steps −

  • aa := a pair of real and imaginary of first complex number
  • bb := a pair of real and imaginary of second complex number
  • x := aa.real * bb.real – aa.img*bb.img
  • y := aa.real * bb.img + aa.img*bb.real
  • return the string as “x+yi”

Let us see the following implementation to get better understanding −


 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   string complexNumberMultiply(string a, string b) {
      pair <int, int> aa = parse(a);
      pair <int, int> bb = parse(b);
      int x = aa.first * bb.first - aa.second * bb.second;
      int y = aa.first * bb.second + aa.second * bb.first;
      return to_string(x) + "+" + to_string(y) + "i";
   pair <int, int> parse(string s){
      pair <int, int> ret;
      int plus = find(s.begin(), s.end(), '+') - s.begin();
      int i = find(s.begin(), s.end(), 'i') - s.begin();
      ret.first = stoi(s.substr(0, plus));
      ret.second = stoi(s.substr(plus + 1, i - plus));
      return ret;
   Solution ob;
   cout << (ob.complexNumberMultiply("1+-1i", "1+-1i"));




Published on 04-May-2020 16:25:57