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
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)
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);
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 x = 11;
var a = Math.ceil(x/2);
var b = x-a;
console.log("x = " + x + " , a = " + a + " , b = " + 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.