Open In App

PHP Program to Add Two Complex Numbers

Last Updated : 27 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Complex numbers are those numbers that contain a real part and an imaginary part. In mathematics, complex numbers are often represented as a + bi, where a is the real part, b is the imaginary part, and i is the imaginary unit (sqrt(-1)). Adding two complex numbers involves adding their real parts and their imaginary parts separately.

Add Two Complex Numbers using a Class

Define a class to represent a complex number and implement a method to add two complex numbers. Create two objects of this class and use the addition method to get the desired result.

Example: Illustration of adding two complex numbers in PHP using a class.

PHP




<?php
  
class ComplexNumber {
    public $real;
    public $imaginary;
  
    public function __construct($real, $imaginary) {
        $this->real = $real;
        $this->imaginary = $imaginary;
    }
  
      // For doing addition of two complex numbers
    public function add(ComplexNumber $other) {
        $newReal = $this->real + $other->real;
        $newImaginary = $this->imaginary + $other->imaginary;
        return new ComplexNumber($newReal, $newImaginary);
    }
  
      // to provide a string representation of the complex number.
    public function __toString() {
        return "{$this->real} + {$this->imaginary}i";
    }
}
  
// Driver code
$complex1 = new ComplexNumber(3, 2);
$complex2 = new ComplexNumber(1, 7);
  
$result = $complex1->add($complex2);
  
echo "Sum: $result";
  
?>


Output

Sum: 4 + 9i

Time Complexity: O(1)

Auxiliary Space: O(1)

Add Two Complex Numbers using Associative Arrays

Define two associative arrays to represent two complex numbers. Then, define a function that will be used to add them and give the desired output.

Example: Illustration of adding two complex numbers in PHP using an associative array.

PHP




<?php
  
// For addition of two complex numbers
function addComplexNumbers($complex1, $complex2) {
    $sum = [
        'real' => $complex1['real'] + $complex2['real'],
        'imaginary' => $complex1['imaginary'] + $complex2['imaginary']
    ];
    return $sum;
}
  
// To format the complex number as a string for output
function formatComplexNumber($complex) {
    return "{$complex['real']} + {$complex['imaginary']}i";
}
  
// Driver code
$complex1 = ['real' => 3, 'imaginary' => 2];
$complex2 = ['real' => 1, 'imaginary' => 7];
  
$result = addComplexNumbers($complex1, $complex2);
  
echo "Sum: " . formatComplexNumber($result);
  
?>


Output

Sum: 4 + 9i

Time Complexity: O(1)

Auxiliary Space: O(1)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads