Sum even numbers from $a to $b - PHP Online
Form of PHP Sandbox
Enter Your PHP code here for testing/debugging in the Online PHP Sandbox. As in the usual PHP files, you can also add HTML, but do not forget to add the tag <?php
in the places where the PHP script should be executed.
Result of php executing
Full code of Sum even numbers from $a to $b.php
- <?php
- $a = 11; // Replace with your desired lower limit
- $b = 111; // Replace with your desired upper limit
- $sum = 0;
- # simple solution (inefficient)
- for ($i = $a; $i <= $b; $i++) {
- if ($i % 2 == 0) {
- $sum += $i;
- }
- }
- echo "The sum of even numbers from $a to $b is: $sum", "\n";
- # Good solutuion = Formula
- $a += $a & 1;
- $b -= $b & 1;
- echo ($b/2 * ($b/2 + 1)) - (($a-2)/2 * (($a-2)/2 + 1));