I am trying to multiply a number a with b until it reaches a number given c, and store into a variable how many times it has been multiplied
let's say
a = 1000 b = 0.75 c = 500
I need to multiply the number and its result at least 3 times to get 500 or less.
I have seen about Math.log() but I am not sure that is the right method here
Any help please?
Say the number of times to multiply by b is x. Simplifying the equation to solve for that x, and you get:
a * (b ** x) <= c
b ** x <= c / a
log_base_b(b ** x) <= log_base_b(c / a)
x <= log_base_b(c / a)
x <= Math.log(c / a) / Math.log(b) -- see https://stackoverflow.com/q/3019278
x = Math.ceil(Math.log(c / a) / Math.log(b))
Which looks correct:
const a = 1000;
const b = 0.75;
const c = 500;
console.log(Math.ceil(Math.log(c / a) / Math.log(b)));
Even if you didn't know math, you could do
let a = 1000;
const b = 0.75;
const c = 500;
let count = 0;
while (a > c) {
count++;
a *= b;
}
console.log(count);