-2

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
    Is this a school assignment? Anyway, the min number for 4 is 2, 6 is 3 and 10 is 5? You probably see the pattern here. All you need is to find out if the user input is odd, using modulus (%). – Rickard Elimää Dec 27 '20 at 21:50
  • 1
    [How do I ask and answer homework questions?](https://meta.stackoverflow.com/questions/334822/how-do-i-ask-and-answer-homework-questions) – charlietfl Dec 27 '20 at 21:52
  • 1
    Thank you for your input. I swear this is no homework but rather part of my very first web app. I'm learning Javascript on my own so... – user14898198 Dec 27 '20 at 21:53
  • But how do I make my function return 3 and 2 instead of 4 and 1 (as in my example with a user input of 5 above)? The modulus doesn't solve that. – user14898198 Dec 27 '20 at 21:56
  • I mean, how can I tell Javascript to return the num1 and num2 combination with the smallest modulus possible? – user14898198 Dec 27 '20 at 21:57
  • You will always receive smallest possible number if you take almost equal parts of the `userInput`. For exaple, 5/2 = 2.5 => round it to 3(first part), then do 5-3 = 2(second part). – Jay Nyxed Dec 27 '20 at 22:00
  • 1
    Wow this looks like it should do what I want. Thank you so much Jay! – user14898198 Dec 27 '20 at 22:03
  • This may have some caveats when the input is a subnorm. – ASDFGerte Dec 27 '20 at 22:05

1 Answers1

0

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)
Rickard Elimää
  • 7,107
  • 3
  • 14
  • 30