Sponsored
Sponsored
This approach involves parsing the given strings to separate the real and imaginary components of each complex number. Once separated, apply the distributive property of multiplication for complex numbers: (a+bi)(c+di) = ac + adi + bci + bdi^2. Substitute i^2 with -1 and then combine the real and imaginary parts for the final output string.
Time Complexity: O(1) because the operations are constant-time.
Space Complexity: O(1) since it only uses a fixed amount of space for the variables and a small dynamic allocation for the output string.
1using System;
2
3class ComplexNumber {
4 public int Real { get; }
5 public int Imaginary { get; }
6
7 public ComplexNumber(string complex) {
8 var parts = complex.Split('+');
9 Real = int.Parse(parts[0]);
10 Imaginary = int.Parse(parts[1].TrimEnd('i'));
11 }
12
13 public static string ComplexNumberMultiply(string num1, string num2) {
14 var c1 = new ComplexNumber(num1);
15 var c2 = new ComplexNumber(num2);
16
17 int realPart = c1.Real * c2.Real - c1.Imaginary * c2.Imaginary;
18 int imagPart = c1.Real * c2.Imaginary + c1.Imaginary * c2.Real;
19
20 return $"{realPart}+{imagPart}i";
21 }
22
23 static void Main() {
24 string num1 = "1+1i";
25 string num2 = "1+1i";
26 Console.WriteLine(ComplexNumberMultiply(num1, num2));
27 }
28}
This C# solution uses the Split
method to parse the input complex number and int.Parse
to convert string parts into integers. The method ComplexNumberMultiply
calculates the product using standard complex number multiplication rules and outputs a correctly formatted string using string interpolation.
In this approach, regular expressions are used to parse the complex number strings. This involves defining a regex pattern to capture the real and imaginary components. After extracting these components, multiplication is performed using the same algebraic rules, and the result is formatted for output.
Time Complexity: O(1) since the regex operation is effectively constant time for fixed-size strings.
Space Complexity: O(1) involving fixed-size auxiliary storage for components and result.
1function parseComplexRegex(complex) {
2
The JavaScript solution applies the String.match
method with a regex pattern to efficiently extract real and imaginary parts from the input complex number strings before multiplying them and formatting the result with a template literal.