patternjavascriptMinor
SICP Exercise 1.3: Sum of squares of two largest numbers out of three
Viewed 0 times
threenumbersexercisesquaressicplargesttwosumout
Problem
The exercise 1.3 of the book Structure and Interpretation of Computer Programs asks the following:
Exercise 1.3. Define a procedure that takes three numbers as arguments and returns the sum of the squares of the two larger numbers.
My answer is this:
Am I doing unnecessary work here? How could I improve this answer, even if only stylistically-speaking?
Exercise 1.3. Define a procedure that takes three numbers as arguments and returns the sum of the squares of the two larger numbers.
My answer is this:
var sumSquareLargest = function (x, y, z) {
var numbers = [x, y, z];
numbers.sort();
return numbers[1] * numbers[1] + numbers[2] * numbers[2];
};Am I doing unnecessary work here? How could I improve this answer, even if only stylistically-speaking?
Solution
Finding the minimum of three numbers is easier than sorting three numbers, and it doesn't require creating a temporary array.
This runs about 10 times faster.
As @Corbin mentioned, floating-point arithmetic is tricky. I've arranged the negative term first, which should cope better with overflow. However, in extremely unusual cases (such as when dealing with a mix of tiny and huge numbers), the result could differ from the original.
This runs about 10 times faster.
var sumSquareNotMin = function(x, y, z) {
var min = Math.min(x, y, z);
return -min * min + x * x + y * y + z * z;
};As @Corbin mentioned, floating-point arithmetic is tricky. I've arranged the negative term first, which should cope better with overflow. However, in extremely unusual cases (such as when dealing with a mix of tiny and huge numbers), the result could differ from the original.
Code Snippets
var sumSquareNotMin = function(x, y, z) {
var min = Math.min(x, y, z);
return -min * min + x * x + y * y + z * z;
};Context
StackExchange Code Review Q#86086, answer score: 6
Revisions (0)
No revisions yet.