Skip to content

Commit 5a4a28a

Browse files
committed
added complex number multiplication code in the string folder
1 parent 3519a91 commit 5a4a28a

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
package com.thealgorithms.strings;
2+
3+
import java.util.Scanner;
4+
5+
/**
6+
* Implementation of complex number multiplication.
7+
*
8+
* Given two strings representing complex numbers in the form "a+bi" and "c+di",
9+
* this class provides a method to multiply them and return the result
10+
* as a string in the same format.
11+
*
12+
* Example:
13+
* Input: "1+1i", "1+1i"
14+
* Output: "0+2i"
15+
*
16+
*
17+
* Formula used:
18+
* (a + bi) × (c + di) = (ac - bd) + (ad + bc)i
19+
**/
20+
21+
public final class ComplexNumberMultiplication {
22+
23+
// Private constructor to prevent instantiation
24+
private ComplexNumberMultiplication() {
25+
}
26+
27+
/**
28+
* Multiplies two complex numbers represented as strings.
29+
*
30+
* @param num1 The first complex number in the form "a+bi".
31+
* @param num2 The second complex number in the form "c+di".
32+
* @return The product of the two complex numbers as a string in the form "x+yi".
33+
*/
34+
public static String complexNumberMultiply(String num1, String num2) {
35+
// Split real and imaginary parts
36+
String[] parts1 = num1.split("\\+");
37+
String[] parts2 = num2.split("\\+");
38+
39+
int a = Integer.parseInt(parts1[0]);
40+
int b = Integer.parseInt(parts1[1].replace("i", ""));
41+
int c = Integer.parseInt(parts2[0]);
42+
int d = Integer.parseInt(parts2[1].replace("i", ""));
43+
44+
// Apply the formula: (a+bi)*(c+di) = (ac - bd) + (ad + bc)i
45+
int real = a * c - b * d;
46+
int imag = a * d + b * c;
47+
48+
return real + "+" + imag + "i";
49+
}
50+
51+
public static void main(String[] args) {
52+
Scanner sc = new Scanner(System.in);
53+
54+
System.out.print("Enter first complex number (a+bi): ");
55+
String num1 = sc.nextLine();
56+
57+
System.out.print("Enter second complex number (c+di): ");
58+
String num2 = sc.nextLine();
59+
60+
String result = complexNumberMultiply(num1, num2);
61+
System.out.println("Result: " + result);
62+
63+
sc.close();
64+
}
65+
}

0 commit comments

Comments
 (0)