To simplify this question, I’m looking for php to suggest the nearest triangular number from an array to the number that has returned false.
For example if the value of the original number is 54 (which is not triangular), I’d like php to select the nearest two variables from an array that would fit this: 55 is and so is 45. Then echo them as suggestions.
How can I achieve this?
To give some background information, here is my current code:
<?php
$x = 54;
$area = $x * 8;
$ans1 = sqrt(1 + $area) -1;
$ans2 = sqrt(1 + $area) +1;
$answer1 = $ans1 / 2;
$answer2 = -$ans2 / 2;
$answer3 = $answer1 + $answer2;
if ( is_numeric( $answer2 ) && strpos( $answer2, '.' ) === false ){
echo "$x is Triangular <br /> <br />";
if ($answer2 > $answer1) {echo "Total number of glasses per side: ".$answer2."<br />";}
if ($answer2 < $answer1) {echo "Total number of glasses per side: ".$answer1."<br />";}
}
else {
echo "$x is not Triangular <br /> <br />";}
?>
A naïve way would be to calculate the difference to each number in your array and then pick the index with the smallest difference.
A better approach is to use the formula for the sequence of triangular numbers ((n²+n)/2 = t).
Solve for n and you get:
You can then calculate n, round it (up or down), and put it into the formula for the sequence. Voilà, you have your closest triangular number.
e.g.
to pick both surrounding values,
floorandceil, respectively: