Multiplication of two complex numbers given as strings
Last Updated :
28 Oct, 2023
Given two complex numbers in the form of strings. Our task is to print the multiplication of these two complex numbers.
Examples:
Input : str1 = "1+1i"
str2 = "1+1i"
Output : "0+2i"
Here, (1 + i) * (1 + i) =
1 + i2 + 2 * i = 2i or "0+2i"
Input : str1 = "1+-1i"
str2 = "1+-1i"
Output : "0+-2i"
Here, (1 - i) * (1 - i) =
1 + i2 - 2 * i = -2i or "0+-2i"
Multiplication of two complex numbers can be done as:
(a+ib) \times (x+iy)=ax+i^2by+i(bx+ay)=ax-by+i(bx+ay)
We simply split up the real and the imaginary parts of the given complex strings based on the '+' and the 'i' symbols. We store the real parts of the two strings a and b as x[0] and y[0] respectively and the imaginary parts as x[1] and y[1] respectively. Then, we multiply the real and the imaginary parts as required after converting the extracted parts into integers. Then, we again form the return string in the required format and return the result.
C++
// C++ Implementation of the above approach
#include <bits/stdc++.h>
using namespace std;
string complexNumberMultiply(string a, string b)
{
int i;
string x1;
int temp = 1;
// Traverse both strings, and
// check for negative numbers
for (i = 0; i < a.length(); i++)
{
if (a[i] == '+')
break;
if (a[i] == '-')
{
temp = -1;
continue;
}
x1.push_back(a[i]);
}
// String to int
int t1 = stoi(x1) * temp;
x1.clear();
temp = 1;
for (; i < a.length() - 1; i++)
{
if (a[i] == '-')
{
temp = -1;
continue;
}
x1.push_back(a[i]);
}
int t2 = stoi(x1) * temp;
x1.clear();
temp = 1;
for (i = 0; i < b.length(); i++)
{
if (b[i] == '+')
break;
if (b[i] == '-')
{
temp = -1;
continue;
}
x1.push_back(b[i]);
}
int t3 = stoi(x1) * temp;
x1.clear();
temp = 1;
for (; i < b.length() - 1; i++)
{
if (b[i] == '-')
{
temp = -1;
continue;
}
x1.push_back(b[i]);
}
int t4 = stoi(x1) * temp;
// Real Part
int ans = t1 * t3 - t2 * t4;
string s;
s += to_string(ans);
s += '+';
// Imaginary part
ans = t1 * t4 + t2 * t3;
s += to_string(ans);
s += 'i';
// Return the result
return s;
}
// Driver Code
int main()
{
string str1 = "1+1i";
string str2 = "1+1i";
cout << complexNumberMultiply(str1, str2);
return 0;
// Contributed By Bhavneet Singh
}
Java
// Java program to multiply two complex numbers
// given as strings.
import java.util.*;
import java.lang.*;
public class GfG{
public static String complexNumberMultiply(String a, String b) {
// Spiting the real and imaginary parts
// of the given complex strings based on '+'
// and 'i' symbols.
String x[] = a.split("\\+|i");
String y[] = b.split("\\+|i");
// Storing the real part of complex string a
int a_real = Integer.parseInt(x[0]);
// Storing the imaginary part of complex string a
int a_img = Integer.parseInt(x[1]);
// Storing the real part of complex string b
int b_real = Integer.parseInt(y[0]);
// Storing the imaginary part of complex string b
int b_img = Integer.parseInt(y[1]);
// Returns the product.
return (a_real * b_real - a_img * b_img) + "+" +
(a_real * b_img + a_img * b_real) + "i";
}
// Driver function
public static void main(String argc[]){
String str1 = "1+1i";
String str2 = "1+1i";
System.out.println(complexNumberMultiply(str1, str2));
}
}
Python3
# Python 3 program to multiply two complex numbers
# given as strings.
def complexNumberMultiply(a, b):
# Spiting the real and imaginary parts
# of the given complex strings based on '+'
# and 'i' symbols.
x = a.split('+')
x[1] = x[1][:-1] # for removing 'i'
y = b.split("+")
y[1] = y[1][:-1] # for removing 'i'
# Storing the real part of complex string a
a_real = int(x[0])
# Storing the imaginary part of complex string a
a_img = int(x[1])
# Storing the real part of complex string b
b_real = int(y[0])
# Storing the imaginary part of complex string b
b_img = int(y[1])
return str(a_real * b_real - a_img * b_img) \
+ "+" + str(a_real * b_img + a_img * b_real) + "i";
# Driver function
str1 = "1 + 1i"
str2 = "1 + 1i"
print(complexNumberMultiply(str1, str2))
# This code is contributed by ANKITKUMAR34
C#
// C# program to multiply two complex
// numbers given as strings.
using System;
using System.Text.RegularExpressions;
class GfG{
public static String complexNumberMultiply(String a,
String b)
{
// Spiting the real and imaginary parts
// of the given complex strings based on '+'
// and 'i' symbols.
String []x = Regex.Split(a, @"\+|i");
String []y = Regex.Split(b, @"\+|i");
// Storing the real part of complex string a
int a_real = Int32.Parse(x[0]);
// Storing the imaginary part of complex string a
int a_img = Int32.Parse(x[1]);
// Storing the real part of complex string b
int b_real = Int32.Parse(y[0]);
// Storing the imaginary part of complex string b
int b_img = Int32.Parse(y[1]);
// Returns the product.
return(a_real * b_real - a_img * b_img) + "+" +
(a_real * b_img + a_img * b_real) + "i";
}
// Driver code
public static void Main(String []argc)
{
String str1 = "1+1i";
String str2 = "1+1i";
Console.WriteLine(complexNumberMultiply(str1, str2));
}
}
// This code is contributed by shikhasingrajput
JavaScript
<script>
// javascript program to multiply two complex numbers
// given as strings.
function complexNumberMultiply(a, b) {
// Spiting the real and imaginary parts
// of the given complex strings based on '+'
// and 'i' symbols.
var x = a.split('+');
var y = b.split('+');
// Storing the real part of complex string a
var a_real = parseInt(x[0]);
// Storing the imaginary part of complex string a
var a_img = parseInt(x[1]);
// Storing the real part of complex string b
var b_real = parseInt(y[0]);
// Storing the imaginary part of complex string b
var b_img = parseInt(y[1]);
// Returns the product.
return (a_real * b_real - a_img * b_img) + "+" +
(a_real * b_img + a_img * b_real) + "i";
}
// Driver function
var str1 = "1+1i";
var str2 = "1+1i";
document.write(complexNumberMultiply(str1, str2));
// This code contributed by shikhasingrajput
</script>
PHP
<?php
// PHP program to multiply
// two complex numbers
// given as strings.
function complexNumberMultiply($a, $b)
{
// Spiting the real and
// imaginary parts of the
// given complex strings
// based on '+' and 'i' symbols.
$x = preg_split("/[\s+]+|i/" , $a);
$y = preg_split("/[\s+]+|i/" , $b);
// Storing the real part
// of complex string a
$a_real = intval($x[0]);
// Storing the imaginary
// part of complex string a
$a_img = intval($x[1]);
// Storing the real part
// of complex string b
$b_real = intval($y[0]);
// Storing the imaginary
// part of complex string b
$b_img = intval($y[1]);
// Returns the product.
return ($a_real * $b_real -
$a_img * $b_img) . "+" .
($a_real * $b_img +
$a_img * $b_real) . "i";
}
// Driver Code
$str1 = "1+1i";
$str2 = "1+1i";
echo complexNumberMultiply($str1, $str2);
// This code is contributed by mits
?>
Time Complexity: O(len(a+b)), where len(x) is the length of strings x
Auxiliary Space: O(len(a+b)), The extras space is used to store the strings.
Approach 2: Using custom functions to parse and multiply the complex numbers
- Read the two complex numbers as strings from input.
- Parse each complex number string into its real and imaginary parts using the following steps:
- a. Find the position of the '+' symbol in the string using the find function.
- Extract the real part of the complex number from the start of the string to the position of the '+' symbol using the substr function and convert it to a double using the stod function.
- Extract the imaginary part of the complex number from the position of the '+' symbol to the end of the string using the substr function and convert it to a double using the stod function. Note that the imaginary part also includes the 'i' symbol, which needs to be excluded from the conversion by extracting a substring from the position of the '+' symbol + 1 to the position of the 'i' symbol - 1.
- Multiply the two complex numbers using the following formula:
(a + bi) * (c + di) = (ac - bd) + (ad + bc)i - where a and b are the real and imaginary parts of the first complex number, and c and d are the real and imaginary parts of the second complex number.
- Print the result of the multiplication in the form a+bi, where a and b are the real and imaginary parts of the product, respectively.
C++
#include <iostream>
#include <string>
using namespace std;
struct Complex {
double real, imag;
};
// Function to parse a string into a Complex number
Complex parse_complex(string str) {
Complex c;
// Get the real and imaginary parts from the string
int pos = str.find('+');
c.real = stod(str.substr(0, pos));
c.imag = stod(str.substr(pos+1, str.size()-pos-2));
return c;
}
// Function to multiply two Complex numbers
Complex multiply_complex(Complex c1, Complex c2) {
Complex result;
result.real = c1.real * c2.real - c1.imag * c2.imag;
result.imag = c1.real * c2.imag + c1.imag * c2.real;
return result;
}
int main() {
// Input two complex numbers as strings
string str1 = "1+1i";
string str2 = "1+1i";
// Parse the strings into Complex numbers
Complex c1 = parse_complex(str1);
Complex c2 = parse_complex(str2);
// Multiply the Complex numbers
Complex result = multiply_complex(c1, c2);
// Print the result
cout << result.real << "+" << result.imag << "i" << endl;
return 0;
}
Java
public class ComplexNumber {
static class Complex {
double real, imag;
}
// Function to parse a string into a Complex number
static Complex parseComplex(String str) {
Complex c = new Complex();
// Get the real and imaginary parts from the string
int pos = str.indexOf('+');
c.real = Double.parseDouble(str.substring(0, pos));
c.imag = Double.parseDouble(str.substring(pos + 1, str.length() - 1));
return c;
}
// Function to multiply two Complex numbers
static Complex multiplyComplex(Complex c1, Complex c2) {
Complex result = new Complex();
result.real = c1.real * c2.real - c1.imag * c2.imag;
result.imag = c1.real * c2.imag + c1.imag * c2.real;
return result;
}
public static void main(String[] args) {
// Input two complex numbers as strings
String str1 = "1+1i";
String str2 = "1+1i";
// Parse the strings into Complex numbers
Complex c1 = parseComplex(str1);
Complex c2 = parseComplex(str2);
// Multiply the Complex numbers
Complex result = multiplyComplex(c1, c2);
// Print the result
System.out.println(result.real + "+" + result.imag + "i");
}
}
Python3
class Complex:
def __init__(self, real, imag):
self.real = real
self.imag = imag
# Function to parse a string into a Complex number
def parse_complex(s):
# Split the string at '+' to separate real and imaginary parts
parts = s.split('+')
real = float(parts[0])
# Extract the imaginary part and remove 'i' character
imag = float(parts[1].rstrip('i'))
return Complex(real, imag)
# Function to multiply two Complex numbers
def multiply_complex(c1, c2):
result_real = c1.real * c2.real - c1.imag * c2.imag
result_imag = c1.real * c2.imag + c1.imag * c2.real
return Complex(result_real, result_imag)
# Main function
if __name__ == "__main__":
# Input two complex numbers as strings
str1 = "1+1i"
str2 = "1+1i"
# Parse the strings into Complex numbers
c1 = parse_complex(str1)
c2 = parse_complex(str2)
# Multiply the Complex numbers
result = multiply_complex(c1, c2)
# Print the result
print(f"{result.real}+{result.imag}i")
C#
using System;
namespace ComplexNumberMultiplication
{
struct Complex
{
public double real;
public double imag;
}
class Program
{
// Function to parse a string into a Complex number
static Complex ParseComplex(string str)
{
Complex c;
// Get the real and imaginary parts from the string
int pos = str.IndexOf('+');
c.real = double.Parse(str.Substring(0, pos));
c.imag = double.Parse(str.Substring(pos + 1, str.Length - pos - 2));
return c;
}
// Function to multiply two Complex numbers
static Complex MultiplyComplex(Complex c1, Complex c2)
{
Complex result;
result.real = c1.real * c2.real - c1.imag * c2.imag;
result.imag = c1.real * c2.imag + c1.imag * c2.real;
return result;
}
static void Main(string[] args)
{
// Input two complex numbers as strings
string str1 = "1+1i";
string str2 = "1+1i";
// Parse the strings into Complex numbers
Complex c1 = ParseComplex(str1);
Complex c2 = ParseComplex(str2);
// Multiply the Complex numbers
Complex result = MultiplyComplex(c1, c2);
// Print the result
Console.WriteLine($"{result.real}+{result.imag}i");
}
}
}
JavaScript
// Define a complex number structure
class Complex {
constructor(real, imag) {
this.real = real;
this.imag = imag;
}
}
// Function to parse a string into a Complex number
function parseComplex(str) {
const c = new Complex(0.0, 0.0);
// Find the position of '+'
const pos = str.indexOf('+');
// Extract real and imaginary parts from the string
c.real = parseFloat(str.substring(0, pos));
c.imag = parseFloat(str.substring(pos + 1, str.length - 1));
return c;
}
// Function to multiply two Complex numbers
function multiplyComplex(c1, c2) {
const result = new Complex(0.0, 0.0);
result.real = c1.real * c2.real - c1.imag * c2.imag;
result.imag = c1.real * c2.imag + c1.imag * c2.real;
return result;
}
// Main function
function main() {
// Input two complex numbers as strings
const str1 = "1+1i";
const str2 = "1+1i";
// Parse the strings into Complex numbers
const c1 = parseComplex(str1);
const c2 = parseComplex(str2);
// Multiply the Complex numbers
const result = multiplyComplex(c1, c2);
// Print the result
console.log(result.real + "+" + result.imag + "i");
}
// Run the main function
main();
Time complexity: O(n), where n is the length of the input strings. This is because the parse_complex function needs to parse the input strings, which has a time complexity of O(n), and the multiply_complex function performs the multiplication of the complex numbers using basic arithmetic operations, which have a time complexity of O(1).
Space complexity: O(1). This is because we only need to store the two complex numbers, the intermediate products, and the result, all of which can be stored in constant space. The only additional space used is for the Complex struct, which has a fixed size and does not depend on the length of the input strings.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem