I was doing this JavaScript problem called "Minimum steps to 1." You can find the problem here.
Given a positive integer - num, Following is a list of possible operations which can be performed on it:
- num / 2, If number is divisible by 2
- num / 3, If number is divisible by 3
- num - 1
With these 3 available operations, find out the minimum number of steps required to reduce the number to 1.
For example:
- For num = 1, no. of steps needed - 0
- For num = 2, no. of steps needed - 1 (num/2)
- For num = 6, no. of steps needed - 2 (num/3 followed by num/2)
- For num = 9, no. of steps needed - 2 (num/3 followed by num/3)
function minStepstoOne(n) {
let steps = [];
steps[0] = 0;
steps[1] = 0;
for(let i = 2; i <= n; i ++) {
let minChoice = steps[i - 1];
if(i % 2 == 0) {
let divideByTwo = steps[i/2]
minChoice = Math.min(divideByTwo, minChoice);
}
if(i % 3 == 0) {
let divideByThree = steps[i/3]
minChoice = Math.min(divideByThree, minChoice);
}
steps[i] = minChoice + 1;
}
return steps[n];
}
//console.log(minStepstoOne(9));