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