29

I'm having a mental block here, and algebra not really being my thing, can you tell me how to re-write the JavaScript code below to derive the variable, c, in terms of a and b?:

a = Math.pow(b, c);
c = ?

Thanks!

Premasagar
  • 14,223
  • 11
  • 27
  • 34
  • 1
    Slightly related question: http://stackoverflow.com/questions/9309084/what-is-the-reverse-of-x-powy-5 – wip Feb 06 '14 at 03:52

2 Answers2

62
c = Math.log(a)/Math.log(b)
dusan
  • 8,524
  • 2
  • 31
  • 54
  • 3
    Might be worth mentioning that JavaScript is horrible at Math when dealing with precise numbers. var c = 3; var b = 10; var a = Math.pow(b,c) var d = Math.log(a)/Math.log(b); // d should equal 3 // d actually equals 2.9999999999999996 – tbh__ Mar 02 '17 at 21:14
  • @tbh__ is it safe to assume that if I'm working with integers and use Math.round() on the result it'll be accurate? Specifically I know my value is a power of 2, so `let power = Math.round( Math.log(value) / Math.log(2) );` should be accurate in my case? – Jake T. Mar 14 '18 at 21:04
  • Ahh, it appears for my specific case Math has me covered with Math.log2(num)! – Jake T. Mar 14 '18 at 21:13
  • how do you obtain b if you have a & c? – TatiOverflow Dec 06 '18 at 01:02
7

Logarithms. You want the logarithm of a. B is the base, c is the exponent, so

logb a = c

Charlie Martin
  • 103,438
  • 22
  • 180
  • 253