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.

Name: Sum even numbers from $a to $b fullscreencopydownloadembedprint


Your result can be seen below.

Result of php executing





Full code of Sum even numbers from $a to $b.php

  1. <?php
  2. $a = 11; // Replace with your desired lower limit
  3. $b = 111; // Replace with your desired upper limit
  4. $sum = 0;
  5.  
  6. # simple solution (inefficient)
  7. for ($i = $a; $i <= $b; $i++) {
  8.     if ($i % 2 == 0) {
  9.         $sum += $i;
  10.     }
  11. }
  12.  
  13. echo "The sum of even numbers from $a to $b is: $sum", "\n";
  14.  
  15.  
  16. # Good solutuion = Formula
  17. $a += $a & 1;
  18. $b -= $b & 1;
  19. echo ($b/2 * ($b/2 + 1)) - (($a-2)/2 * (($a-2)/2 + 1));
File Description
  • Sum even numbers from $a to $b
  • PHP Code
  • 25 Sep-2023
  • 407 Bytes
You can Share it: