Multiply N complex numbers given as strings

Given N Complex Numbers in the form of Strings, the task is to print the multiplication of these N complex numbers.

Examples: 

Input: N = 3, V = { 3 + 1i, 2 + 1i, 5 + -7i } 
Output: 10+-60i 
Explanation: 
Firstly, we will multiply (3+1i) and (2+1i) to yield 5+5i. In the next step, we will multiply 5+5i and -5+-7i to yield the final result 10+-60i.

Input: N = 3, V = { “7+4i”, “-12+1i”, “-16+-7i”, “12+18i” } 
Output: -9444+35442i 

 

Approach 



  • Firstly, start iterating from the beginning and take the first 2 Strings and erase both of them.
  • Next, convert the string into a number with appropriate signs. Store the Real Part and the Imaginary Part of the String in separate variables. Take a as the real part of the first string while b as the imaginary part of the first string. Take c as the real part of the second string while d as the imaginary part of the second string.
  • Next we will calculate the resultant values for the real by calculating the product of a and c and subtracting it with the product of b and subtracting with the product of b and d. For the Imaginary Part, we will calculate the sum of the product of a and d, along with the product of the b and c.
  • We will then generate a temporary string to take the sum of real and imaginary values that has been calculated earlier.
  • We will push the resultant string into the vector. Repeat the above steps until there is only one remaining element in the vector.
  • Return the last remaining element in the vector, which is the desired answer.

Below is the implementation of our above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ Program to multiply
// N complex Numbers
#include <bits/stdc++.h>
using namespace std;
 
#define ll long long
 
// Function which returns the
// string in digit format
vector<long long int> findnum(string s1)
{
    vector<long long int> v;
    // a : real
    // b : imaginary
    int a = 0, b = 0;
    int sa = 0, sb = 0, i = 0;
    // sa : sign of a
    // sb : sign of b
    if (s1[0] == '-') {
        sa = 1;
        i = 1;
    }
    // Extract the real number
    while (isdigit(s1[i])) {
        a = a * 10 + (int(s1[i]) - 48);
        i++;
    }
 
    if (s1[i] == '+') {
        sb = 0;
        i += 1;
    }
 
    if (s1[i] == '-') {
        sb = 1;
        i += 1;
    }
 
    // Extract the imaginary part
    while (i < s1.length() && isdigit(s1[i])) {
        b = b * 10 + (int(s1[i]) - 48);
        i++;
    }
 
    if (sa)
        a *= -1;
 
    if (sb)
        b *= -1;
 
    v.push_back(a);
    v.push_back(b);
 
    return v;
}
 
string complexNumberMultiply(vector<string> v)
{
    // if size==1 means we reached at result
    while (v.size() != 1) {
        // Extract the first two elements
        vector<ll> v1 = findnum(v[0]);
        vector<ll> v2 = findnum(v[1]);
 
        // Remove them
        v.erase(v.begin());
        v.erase(v.begin());
 
        // Calculate and store the real part
        ll r = (v1[0] * v2[0] - v1[1] * v2[1]);
        // Calculate and store the imaginary part
        ll img = v1[0] * v2[1] + v1[1] * v2[0];
 
        string res = "";
        // Append the real part
        res += to_string(r);
        res += '+';
        // Append the imaginary part
        res += to_string(img) + 'i';
 
        // Insert into vector
        v.insert(v.begin(), res);
    }
 
    return v[0];
}
 
// Driver Function
int main()
{
    int n = 3;
    vector<string> v = { "3+1i",
                         "2+1i", "-5+-7i" };
 
    cout << complexNumberMultiply(v) << "\n";
 
    return 0;
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to multiply
# N complex Numbers
 
# Function which returns the
# in digit format
def findnum(s1):
     
    v = []
     
    # a : real
    # b : imaginary
    a = 0
    b = 0
    sa = 0
    sb = 0
    i = 0
     
    # sa : sign of a
    # sb : sign of b
    if (s1[0] == '-'):
        sa = 1
        i = 1
 
    # Extract the real number
    while (s1[i].isdigit()):
        a = a * 10 + (int(s1[i]))
        i += 1
 
    if (s1[i] == '+'):
        sb = 0
        i += 1
 
    if (s1[i] == '-'):
        sb = 1
        i += 1
 
    # Extract the imaginary part
    while (i < len(s1) and s1[i].isdigit()):
        b = b * 10 + (int(s1[i]))
        i += 1
 
    if (sa):
        a *= -1
 
    if (sb):
        b *= -1
 
    v.append(a)
    v.append(b)
 
    return v
 
def complexNumberMultiply(v):
     
    # If size==1 means we reached at result
    while (len(v) != 1):
         
        # Extract the first two elements
        v1 = findnum(v[0])
        v2 = findnum(v[1])
 
        # Remove them
        del v[0]
        del v[0]
 
        # Calculate and store the real part
        r = (v1[0] * v2[0] - v1[1] * v2[1])
         
        # Calculate and store the imaginary part
        img = v1[0] * v2[1] + v1[1] * v2[0]
 
        res = ""
         
        # Append the real part
        res += str(r)
        res += '+'
         
        # Append the imaginary part
        res += str(img) + 'i'
 
        # Insert into vector
        v.insert(0, res)
 
    return v[0]
 
# Driver code
if __name__ == '__main__':
     
    n = 3
    v = [ "3+1i", "2+1i", "-5+-7i" ]
 
    print(complexNumberMultiply(v))
 
# This code is contributed by mohit kumar 29

chevron_right


Output: 

10+-60i


 

Time Complexity: O(N) 
Auxiliary Space: O(N)
 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Still Learner

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : mohit kumar 29

Article Tags :
Practice Tags :


1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.