Javascript 这段代码工作原理的数学解释
我在站点代码战中遇到了一个问题,我用两个循环解决了这个问题。当我看另一个答案时,我发现其中一个答案解决了这个问题,没有任何循环,这让我张大了嘴巴。编码器applied Math.min/max,虽然我确实理解代码的功能,但我不理解它为什么会工作 我很喜欢学习,因为见鬼,Math.max/min肯定能把我循环中的字节数去掉Javascript 这段代码工作原理的数学解释,javascript,math,Javascript,Math,我在站点代码战中遇到了一个问题,我用两个循环解决了这个问题。当我看另一个答案时,我发现其中一个答案解决了这个问题,没有任何循环,这让我张大了嘴巴。编码器applied Math.min/max,虽然我确实理解代码的功能,但我不理解它为什么会工作 我很喜欢学习,因为见鬼,Math.max/min肯定能把我循环中的字节数去掉 Given integers n, l and r, find the number of ways to represent n as a sum of two intege
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
[time limit] 4000ms (js)
[input] integer n
A positive integer.
Constraints:
5 ≤ n ≤ 109.
[input] integer l
A positive integer.
Constraints:
1 ≤ l ≤ r.
[input] integer r
A positive integer.
Constraints:
l ≤ r ≤ 109,
r - l ≤ 106.
编码员惊人的回答:
function countSumOfTwoRepresentations2(n, l, r) {
return Math.max(Math.min(Math.floor(n / 2) - l, r - Math.ceil(n / 2)) + 1, 0);
}
相比之下,我的废话:
function countSumOfTwoRepresentations2(n, l, r) {
var representations = 0;
//Only travel the loop until n/2 , because l+r will never equal n
// if l or r > n/2
var limit = Math.floor(n/2);
for(var i=l; i<=r && i<=limit; ++i){
for(var j=i;j<=r;++j){
if(i+j == n){
++representations;
break;
}
}
}
return representations;
}
函数countSumOfTwoRepresentations2(n,l,r){
var表示=0;
//仅在n/2之前循环,因为l+r永远不等于n
//如果l或r>n/2
风险限额=数学下限(n/2);
对于(var i=l;i
给定整数n
、l
和r
,找出将n表示为两个整数之和a
和B
的方法,以便l≤ A.≤ B≤ r
首先,考虑如果<代码> N< /代码>是偶数,并且允许<代码> x= n/2 ,我们至少有一个解决方案(<代码> x+x< /代码>),如果只有,<>代码>≤ x≤ r
。如果x
不在该范围内,则没有解决方案,因为x
和l+l>n
或r
和r+r
这可以推广到偶数或奇数n
:有一个解决方案,当且仅当:l≤ 楼层(x)≤ ceil(x)≤ r
。如果我们让A=floor(x)
和B=ceil(x)
,那么这个解决方案就是A+B
。每一个其他解决方案都可以通过沿着数字线在每个方向上从该点开始走一步来找到。(A-1)+(B+1)=A+B=n
,因此(A-1)+(B+1)
就是一个解决方案,只要(A-1)
没有跨越l
边界,(B+1)
没有跨越r
边界。因此,如果您想要一个只有一个循环的解决方案,可以这样做:
function countSumOfTwoRepresentations2(n, l, r) {
var x = n/2;
var A = Math.floor( x );
var B = Math.ceil( x );
for ( var count = 0; l <= A && B <= r; count++) {
A--;
B++;
}
return count;
}
function countSumOfTwoRepresentations2(n, l, r) {
var x = n/2;
var A = Math.floor( x );
var B = Math.ceil( x );
// Every solution is of the form (A - i) + (B + i), where i is an integer >= 0
// How many values of i are valid for l <= (A - i)
var stepsA = A - l + 1;
// How many values of i are valid for (B + i) <= r
var stepsB = r - B + 1;
// If the formulas gave a negative amount of valid steps,
// there is no solution, so return 0
if ( stepsA < 0 || stepsB < 0 )
return 0;
// Otherwise, return the smaller valid amount of steps,
// that is the number of steps that are valid for both A and B
return Math.min(stepsA, stepsB);
}