Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading