# PHP program to find the sum of first n natural numbers that are divisible by a number ‘x’ or a number ‘y’

PHPServer Side ProgrammingProgramming

To find the sum of first n natural numbers that are divisible by a number ‘x’ or a number ‘y’, the code is as follows −

## Example

Live Demo

<?php
function sum_of_nums($n_val,$x_val, $y_val) {$val_1; $val_2;$val_3;
$val_1 = floor(((int)$n_val / $x_val)) * (2 *$x_val + (int)((int)$n_val /$x_val - 1) * $X) / 2;$val_2 = floor(((int)$n_val /$y_val)) * (2 * $y_val + (int)((int)$n_val / $y_val - 1) *$y_val) / 2;
$val_3 = floor(((int)$n_val / ($x_val *$y_val))) * (2 * ($x_val *$y_val) + ((int)$n_val / ($x_val * $y_val) - 1) * (int)($x_val * $y_val))/ 2; return ceil($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 15

A function named ‘sum_of_nums’ is defined that computes three values by checking if they can be divided by two specific values or not. Outside the function, the number and the two specific values are defined, and the function is called by passing these values as parameters. Relevant output is displayed on the console

Published on 02-Jul-2020 10:41:13