Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
PHP program to check if a given number is present in an infinite series or not
To check if a given number is present in an infinite arithmetic series, we need to determine if the number can be reached by starting from a base value and adding a common difference repeatedly. The PHP code below demonstrates this logic −
Example
<?php
function contains_val($start, $target, $diff){
if ($start == $target)
return true;
if (($target - $start) * $diff > 0 && ($target - $start) % $diff == 0)
return true;
return false;
}
$start = 3;
$target = 5;
$diff = 9;
if (contains_val($start, $target, $diff))
echo "The number is present in the infinite series";
else
echo "The number is not present in the infinite series";
?>
Output
The number is not present in the infinite series
How It Works
The function contains_val takes three parameters −
- $start − The starting number of the series
- $target − The number we want to check
- $diff − The common difference in the arithmetic series
The logic works as follows −
function contains_val($start, $target, $diff){
if ($start == $target)
return true;
if (($target - $start) * $diff > 0 && ($target - $start) % $diff == 0)
return true;
return false;
}
First, it checks if the target equals the starting number. If not, it verifies two conditions: the difference must be in the correct direction (positive or negative) and the target must be reachable by adding the common difference a whole number of times.
Another Example
<?php
function contains_val($start, $target, $diff){
if ($start == $target)
return true;
if (($target - $start) * $diff > 0 && ($target - $start) % $diff == 0)
return true;
return false;
}
$start = 2;
$target = 8;
$diff = 3;
if (contains_val($start, $target, $diff))
echo "The number $target is present in the series starting from $start with difference $diff";
else
echo "The number $target is not present in the series starting from $start with difference $diff";
?>
The number 8 is present in the series starting from 2 with difference 3
Conclusion
This function efficiently determines if a number exists in an infinite arithmetic series by checking if the target can be reached from the starting point using the given common difference. The key is ensuring the direction is correct and the difference is divisible.
