Separate an integer into two (nearly) equal parts
Let javascript do Math for you.
var x = 7;
var p1 = Math.ceil(x / 2);
var p2 = Math.floor(x / 2);
console.log(p1, p2);
Your code can be simplified a bit:
var num = 7;
var p1 = Math.floor(num / 2);
var p2 = p1;
if (num % 2 != 0) {
p1++;
}
console.log(p1, p2);
Just find the first part and subtract it from the original number.
var x = 7;
var p1 = Math.floor(x / 2);
var p2 = x - p1;
console.log(p1, p2);
In the case of x
being odd, p1
will receive the smaller of the two addends. You can switch this around by calling Math.ceil
instead.