Open In App

PHP Program to Find Sum of Geometric Series

Last Updated : 27 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a number n, the task is to find the sum of the geometric series in PHP. A Geometric series is a series with a constant ratio between successive terms. The first term of the series is denoted by a and the common ratio is denoted by r.

PHP Program to Sum of Geometric Series using for Loop

A Simple solution to calculate the sum of geometric series. Here, we use a for loop to find the sum of the Geometric Series.

Example: PHP Program to find the sum of geometric series using a for loop.

PHP




<?php
  
function geometricSum($a, $r, $n) {
    $sum = 0; 
    for ($i = 0; $i < $n; $i++){
        $sum = $sum + $a;
        $a = $a * $r;
    }
      
    return $sum;
}
  
// Driver code
$a = 2; // First term
$r = 3; // Common ratio
$n = 4; // Number of terms
  
echo "Sum of Geometric Series: " 
    . geometricSum($a, $r, $n);
  
?>


Output

Sum of Geometric Series: 80

PHP Program to Sum of Geometric Series using Mathematical Formula

The series looks like this :- a, ar, ar2, ar3, ar4, . . .

Sum of series Sn = a×(1−rn)1−rSn​=1−ra×(1−rn)​

Where:

  • Sn: The sum of the geometric series up to the nth term.
  • a: The first term of the series.
  • r: The common ratio of the series.
  • n: The number of terms in the series.

Example: PHP Program to find the sum of geometric series using a mathematical formula.

PHP




<?php
  
function geometricSum($a, $r, $n) {
  
    if ($r == 1) {
        return $a * $n;
    }
  
    // Calculate the sum of geometric series
    $sum = $a * (1 - pow($r, $n)) / (1 - $r);
  
    return $sum;
}
  
// Driver code
$a = 2; // First term
$r = 3; // Common ratio
$n = 4; // Number of terms
  
echo "Sum of Geometric Series: " 
    . geometricSum($a, $r, $n);
  
?>


Output

Sum of Geometric Series: 80


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads