Search code examples
javascriptdivisionmodulo

How to divide a number by 2 as many times as possible, and then print it out in Javascript?


I would like to write a program that reads an integer and then divides it by 2 as many times as possible while writing the number as a product of two numbers multiplied by a number that is no longer divisible by 2.

For example:

I would like an integer: 120

120 = 2 * 2 * 2 * 15

Here is as far as I have gotten (part of it is already good in my opinion, but I got stuck here unfortunately):

let num = Number(prompt('The number: '));

let i = 0;
while(!(num % 2)) { 
    num /= 2; 
    i++; 
}

let solution = Array(i).fill(2).join(' * ');

console.log(solution);


Solution

  • There's a few steps I would take to get to your desired result:

    • Keep the original value if you want to display it in the output (See the constant initialNum and editable remainder)
    • If there is a remainder, push it into the array before you turn it into a string.

    // Keep a copy of the original
    const initialNum = Number(prompt('The number: '));
    let remainder = initialNum
    
    // This is working fine and doesn't need any changes
    let i = 0;
    while (!(remainder % 2)) {
      remainder /= 2;
      i++;
    }
    
    // Add the required "2"s
    const values = Array(i).fill(2)
    // If the total isn't completely divisible by 2, add the final multiplier
    if (remainder !== 1) {
      values.push(remainder)
    }
    // Build the output string
    const solution = `${initialNum} = ${values.join(' * ')}`;
    
    console.log(solution);