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 the sum of first n natural numbers that are divisible by a number 'x' or a number 'y'
To find the sum of first n natural numbers that are divisible by a number 'x' or a number 'y', we use the inclusion-exclusion principle. This mathematical approach counts numbers divisible by x, adds numbers divisible by y, then subtracts numbers divisible by both (LCM of x and y) to avoid double counting.
Example
The following code demonstrates how to calculate this sum −
<?php
function sum_of_nums($n_val, $x_val, $y_val)
{
// Sum of numbers divisible by x_val
$count_x = floor($n_val / $x_val);
$val_1 = $count_x * (2 * $x_val + ($count_x - 1) * $x_val) / 2;
// Sum of numbers divisible by y_val
$count_y = floor($n_val / $y_val);
$val_2 = $count_y * (2 * $y_val + ($count_y - 1) * $y_val) / 2;
// Sum of numbers divisible by both (LCM = x*y for coprime numbers)
$lcm = $x_val * $y_val;
$count_lcm = floor($n_val / $lcm);
$val_3 = $count_lcm * (2 * $lcm + ($count_lcm - 1) * $lcm) / 2;
return $val_1 + $val_2 - $val_3;
}
$n_val = 11;
$x_val = 2;
$y_val = 5;
print_r("The sum of first 11 natural numbers divisible by 2 or 5 is ");
echo sum_of_nums($n_val, $x_val, $y_val);
?>
Output
The sum of first 11 natural numbers divisible by 2 or 5 is 50
How It Works
The function uses the arithmetic progression sum formula: Sum = n/2 × (first_term + last_term). For numbers divisible by x within range 1 to n:
- Count: floor(n/x) gives how many multiples exist
- Sum: count × (2×x + (count-1)×x) / 2
- Inclusion-Exclusion: Add sums for x and y, subtract sum for LCM to avoid double counting
Conclusion
This approach efficiently calculates the sum using mathematical formulas rather than iterating through each number. The inclusion-exclusion principle ensures accurate results by properly handling numbers divisible by both x and y.
