How to divide an unknown integer into a given number of even parts using JavaScript?


For this, you can use the concept of modular operator along with divide. Following is the code −

Example

var divideInteger = function(value, divide) {
   var num;
   var modular = value % divide;
   if(modular == 0){
      num = value/divide;
      sumOfDivideParts = Array(divide).fill(num);
   } else {
      num = (value-modular)/divide;
      sumOfDivideParts = Array(divide).fill(num);
      for(i=0;i<modular;i++){
         sumOfDivideParts[i] = sumOfDivideParts[i] + 1;
      }
      sumOfDivideParts.reverse()
   }
   return sumOfDivideParts;
}
var arrayValues = divideInteger(50, 8)
console.log(arrayValues);

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo169.js.

Output

This will produce the following output −

PS C:\Users\Amit\javascript-code> node demo169.js
[
   6, 6, 6, 6,
   6, 6, 7, 7
]

Updated on: 12-Sep-2020

295 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements