Separate an integer into two (nearly) equal parts

后端 未结 11 899
囚心锁ツ
囚心锁ツ 2020-12-06 04:09

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         


        
11条回答
  •  隐瞒了意图╮
    2020-12-06 04:39

    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.

提交回复
热议问题