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 find if a number is present in a given sequence of numbers
In PHP, you can check if a specific number exists in an arithmetic sequence by comparing the target number with the sequence parameters. This involves checking if the number can be reached by adding a common difference repeatedly to a starting number.
Example
The following code demonstrates how to find if a number is present in a given arithmetic sequence −
<?php
function contains_in_sequence($start, $target, $step)
{
if ($start == $target)
return true;
if (($target - $start) * $step > 0 &&
($target - $start) % $step == 0)
return true;
return false;
}
$start = 11;
$target = 99;
$step = 2;
print_r("Is the number present in the sequence? ");
if (contains_in_sequence($start, $target, $step))
echo "Yes, it is present in the sequence";
else
echo "No, it is not present in the sequence";
?>
Is the number present in the sequence? Yes, it is present in the sequence
How It Works
The contains_in_sequence() function checks if a target number exists in an arithmetic sequence by:
- First checking if the target equals the starting number
- Then verifying if the difference between target and start is divisible by the step size
- Ensuring the step direction matches (positive or negative difference)
In this example, the sequence starts at 11 with a step of 2, generating: 11, 13, 15, 17, ..., 97, 99. Since 99 can be reached from 11 by adding 2 repeatedly (44 times), the function returns true.
Conclusion
This method efficiently determines if a number exists in an arithmetic sequence using mathematical properties rather than iterating through all sequence values. It works for both increasing and decreasing sequences.
