# 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.

Your result can be seen below.

## 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.
20. # solution formula 1:
21.
22.  \$n = ((\$b - \$a) >> 1) + 1;  # Calculate the number of even numbers in the range.
23.  echo ((\$a + \$b) * \$n) >> 1, "\n";   # Sum of an arithmetic progression.
24.
25. # solution formula 2:
26.
27. 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
• 610 Bytes
You can Share it:
Latest PHP Pastes