PHP Program to Add Two Complex Numbers
Last Updated :
27 Feb, 2024
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 ;
}
public function add(ComplexNumber $other ) {
$newReal = $this ->real + $other ->real;
$newImaginary = $this ->imaginary + $other ->imaginary;
return new ComplexNumber( $newReal , $newImaginary );
}
public function __toString() {
return "{$this->real} + {$this->imaginary}i" ;
}
}
$complex1 = new ComplexNumber(3, 2);
$complex2 = new ComplexNumber(1, 7);
$result = $complex1 ->add( $complex2 );
echo "Sum: $result" ;
?>
|
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
function addComplexNumbers( $complex1 , $complex2 ) {
$sum = [
'real' => $complex1 [ 'real' ] + $complex2 [ 'real' ],
'imaginary' => $complex1 [ 'imaginary' ] + $complex2 [ 'imaginary' ]
];
return $sum ;
}
function formatComplexNumber( $complex ) {
return "{$complex['real']} + {$complex['imaginary']}i" ;
}
$complex1 = [ 'real' => 3, 'imaginary' => 2];
$complex2 = [ 'real' => 1, 'imaginary' => 7];
$result = addComplexNumbers( $complex1 , $complex2 );
echo "Sum: " . formatComplexNumber( $result );
?>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...