Javascript function determining number combination with smallest possible difference

56 Views Asked by At

I'm struggling to formulate a Javascript function that would allow me to create 2 numbers out of a user input, according to 2 rules.

let userInput;
let num1;
let num2;

Rules: num1 + num2 = userInput and num1 - num2 must be the smallest positive number possible.

So with a user input of 5 the function should return 3 and 2 for num1 and num2 and not 4 and 1.

Could you please help me formulate such a Javascript function?

Thanks in advance for your help :)

1

There are 1 best solutions below

1
Rickard Elimää On

Didn't get a notification when you responded. There are numerous ways to solve this, but I would use Math.ceil(), that automatically rounds up any decimals, and Math.floor() that rounds down.

let userInput = 5;
let num1 = Math.ceil(userInput/2);
let num2 = Math.floor(userInput/2);

console.log(userInput, num1, num2)

Another way could be to divide userInput by 2 and use parseInt() to cut off all decimals, and then add userInput%2 to that result, resulting in 1 if userInput is odd and 0 if even. Subtract num1 from userInput to get num2.

let userInput = 5;
let remainder = userInput%2 // 1
let num1 = parseInt(userInput/2) + remainder;
let num2 = userInput - num1;

console.log(userInput, num1, num2)