+ 2
can someone explain me the logic behind the formula
const GetSum = (a, b) => { let min = Math.min(a, b), max = Math.max(a, b); return (max - min + 1) * (min + max) / 2; }
1 Antwort
+ 2
sum is a weird name for it.
GetSum(2, 5) returns 14 instead of 7. GetSum(2,2) returns 2 instead of 4.
The Math.max and Math.min lines are pretty obvious so I'll assume you get them.
The average of a and b = (min + max) / 2.
This doesn't have a simple word description: (max - min + 1)
It will always be at least 1. max - min is the positive difference between a and b.
You could simplify as: (max - min + 1) = (difference + 1)
The result is the average of a and b if a === b because (difference + 1) simplifies to 1 when a === b.
The most concise expression that uses a couple clear words to accurately describe the result is:
(difference + 1) * average