2つのループで解決したCodeFightサイトで問題が発生しました。他の答えを見ている間、私はループなしでそれを解決し、私の口を開いて私を残しました。コーダーは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 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;
}
私は努力に感謝し、説明していただきありがとうございます。 – Chayemor