programming-examples/php/Basics/PHP program to check a sequence of numbers is a geometric progression or not..php

28 lines
655 B
PHP
Raw Permalink Normal View History

2019-11-18 14:44:36 +01:00
<?php
function is_geometric($arr)
{
if (sizeof($arr) <= 1)
return True;
# Calculate ratio
$ratio = $arr[1]/$arr[0];
# Check the ratio of the remaining
for($i=1; $i<sizeof($arr); $i++)
{
if (($arr[$i]/($arr[$i-1])) != $ratio)
{
return "Not an geometric sequence";
}
}
return "Geometric sequence";
}
$my_arr1 = array(2, 6, 18, 54);
$my_arr2 = array(10, 5, 2.5, 1.20);
print_r(is_geometric($my_arr1)."\n");
print_r(is_geometric($my_arr2)."\n");
?>
Output:
Geometric sequence
Not an geometric sequence