Count Sum Of Two Representations 2
Description
Given integers n, l and r, find the number of ways to represent n as a sum of two integers A and B such that l ≤ A ≤ B ≤ r.
Example
For n = 6, l = 2, and r = 4, the output should be
countSumOfTwoRepresentations2(n, l, r) = 2.
There are just two ways to write 6 as A + B, where 2 ≤ A ≤ B ≤ 4: 6 = 2 + 4 and 6 = 3 + 3.
Input/Output
-
[execution time limit] 4 seconds (js)
-
[input] integer n
A positive integer.
Guaranteed constraints:
5 \leq n \leq 10^9. -
[input] integer l
A positive integer.
Guaranteed constraints:
1 \leq l \leq r. -
[input] integer r
A positive integer.
Guaranteed constraints:
1 \leq r \leq 10^9,
r-l \leq 10^6. -
[output] integer
[JavaScript (ES6)] Syntax Tips
1
2
3
4
5
6
// Prints help message to the console
// Returns a string
function helloWorld(name) {
console.log("This prints to the console when you Run Tests");
return "Hello, " + name;
}
Solution
1
2
3
4
5
6
7
function countSumOfTwoRepresentations2(n, l, r) {
if (2 * r < n || 2 * l > n) return 0;
var min = Math.max(l, n - r);
var max = Math.min(r, n - l);
var mid = Math.floor((max + min) / 2);
return mid - min + 1;
}