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 (updated based the well-meaning comments but still not perfect):
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);
You are almost there - you got how to get how many 2 you need - now just need to add the remaining num onto it - and maybe remember the total:
let solution = Array(i).fill(2).join(' * ') + " * " + num;
Full solution:
let num = Number(prompt('The number: '));
let total = num; // remember for later
let i = 0;
while(!(num % 2)) {
num /= 2;
i++;
}
let solution = total + " = " + Array(i).fill(2).join(' * ') + " * " + num;
console.log(solution);