Ich habe ein Problem in der Website CodeFights, die ich mit zwei Schleifen gelöst. Während ich auf eine andere Antwort schaute, fand ich eine, die es ohne Schleifen löste und es ließ mich mit offenem Mund zurück. Der Programmierer hat Math.min/max angewendet, und obwohl ich verstehe, was der Code tut, verstehe ich nicht, warum er funktioniert.Math Erklärung, warum dieser Code funktioniert
Ich liebe es zu lernen, denn hey, Math.max/min schlägt sicher die Bytes aus meinen Loops.
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.
Der erstaunliche Antwort des Coder:
function countSumOfTwoRepresentations2(n, l, r) {
return Math.max(Math.min(Math.floor(n/2) - l, r - Math.ceil(n/2)) + 1, 0);
}
Mein Mist im Vergleich:
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;
}
Ich schätze die Mühe, danke zu erläutern. – Chayemor