Separate an integer into two (nearly) equal parts

Viewed 5224

I need to separate an integer into two numbers. Something like dividing by two but I only want integer components as a result, such as:

6 = 3 and 3
7 = 4 and 3

I tried the following, but I'm not sure its the best solution.

var number = 7;
var part1 = 0;
var part2 = 0;

if((number % 2) == 0) {
    part1 = number / 2;
    part2 = number / 2;
}
else {
    part1 = parseInt((number / 2) + 1);
    part2 = parseInt(number / 2);
}

This does what I want, but I don't think this code is clean.

Are there better ways of doing this?

10 Answers

Another way to do this is using bitwise operators. It doesn't work for very big numbers

function splitter(number){
  part1 = (number>>1) + (number&1);
  part2 = number>>1;
  console.log(number + ":", part1 + "+" + part2);
}

splitter(7);
splitter(6);
splitter(2**30+1); // Breaks for values greater than 2**31
splitter(2**31+1); 

If in-case you don't want your outputs to be consecutive or exact identical and yet want to 'separate an integer into two numbers', this is the solution for you:

function printSeparatedInts(num) {
  let smallerNum = Math.floor(Math.random() * Math.floor(num));
  if (num && smallerNum === (num/2)) {    // checking if input != 0 & output is not consecutive
    printSeparatedInts(num)
   } else {
    console.log(smallerNum, (num - smallerNum))
  }
}

printSeparatedInts(22)
printSeparatedInts(22)     // will likely print different output from above
printSeparatedInts(7)

Feeling lazy ? No problem !

I proudly present to you a generator object !

Initialize it and just use it! It will automatically change value every other use, even in the same line!!

Usage: a = new splitter(n) then console.log(a+" and "+a)

function splitter(n){
    this.p1 = Math.floor(n/2);
    this.p2 = n-this.p1;
    this.cnt=0;
    this.valueOf= ()=> (++this.cnt%2)? this.p1:this.p2;
    return n;
}

a = new splitter(5);
console.log(a + " and " +a);
console.log(a + " and " +a);
console.log(a + " and " +a);

b = new splitter(11);
console.log(b + " and " +b);

var number = 7;
var part1 = 0;
var part2 = 0;

if(number == 0) {
    part1 = (part2 = 0);
    console.log(part1, part2);
}
else if(number == 1) {
    part1 = 1;
    part2 = 0;
    console.log(part1, part2);
}
else if((number % 2) == 0) {
    part1 = part2 = number / 2;
    console.log(part1, part2);
}
else {
    part1 = (number + 1) / 2;
    part2 = number - part1;
    console.log(part1, part2);
}

Only other solution, I think performance is OK.

Related