Read the Samples

Sample #247

Original Problem

Two integers x and y are given. The sum of the two is even. What is the largest possible value of x-y?

Example

Given x = 1 and y = 2 we have x + y = 3. So the answer is x - y = -1.

Note: This problem has appeared at several sites. The only known correct solution is in the book How to Solve It, by Polya. The problem is there posed as one of 1000 math problems, and I’m not sure about the original source of the problem.

Previous Solution

JavaScript

function largest(x, y) { if (x < 0 && y < 0) { throw new Error('x or y is negative'); } else if (x < y) { x = x - y; } else { y = y - x; } if (x == 0 || y == 0) { return x; } else { return largest(x, y - 1); } } largest(1, 2); // = -1 largest(-1, 1); // = -1 largest(1, -2); // = 1 largest(-1, -2); // = 1 largest(0, 0); // = 0 largest(2, -1); // = 2 largest(1, 1); // = 1

Code

/** * Given two integers x and y, compute the largest possible value of x - y * * @param {number} x The larger of"