Separate an integer into two (nearly) equal parts

后端 未结 11 891
囚心锁ツ
囚心锁ツ 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:44

    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)

提交回复
热议问题