2894. Divisible and Non-divisible Sums Difference #1734
-
Topics: You are given positive integers Define two integers as follows:
Return the integer Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to find the difference between the sum of integers in the range Approach
Let's implement this solution in PHP: 2894. Divisible and Non-divisible Sums Difference <?php
/**
* @param Integer $n
* @param Integer $m
* @return Integer
*/
function differenceOfSums($n, $m) {
$total = $n * ($n + 1) / 2;
$k = (int)($n / $m);
$sum2 = $m * $k * ($k + 1) / 2;
return $total - 2 * $sum2;
}
// Example cases
echo differenceOfSums(10, 3) . "\n"; // Output: 19
echo differenceOfSums(5, 6) . "\n"; // Output: 15
echo differenceOfSums(5, 1) . "\n"; // Output: -15
?> Explanation:
This approach efficiently computes the required difference using arithmetic progression formulas, ensuring optimal performance with a time complexity of O(1). |
Beta Was this translation helpful? Give feedback.
We need to find the difference between the sum of integers in the range
[1, n]
that are not divisible by a given integer m and the sum of those that are divisible bym
. The solution can be efficiently derived using arithmetic progression formulas.Approach