views:

145

answers:

2

I tried to use the standard iterative algorithm to compute nth roots.

For instance (111^123)^(1/123).

The standard algorithm computes high powers of the base (in this case 111^123) which takes a lot of time. The algorithm is given here http://en.wikipedia.org/wiki/Nth_root_algorithm

However, I noticed that the same thing using double takes less than a millisecond. So obviously they use some smart ideas. Any hints on this?

A: 

Try using binary exponentiation. What I mean is do:

111 * 111 = 111^2, now you know what 111^2 is, you can now calculate 111^4 by doing (111^2) * (111^2). Here is the whole sequence (Note that this is probably not the most efficient way).

111 * 111 = 111^2
111^2 * 111^2 = 111^4
111^4 * 111^4 = 111^8
111^8 * 111^8 = 111^16
111^16 * 111^16 = 111^32
111^32 * 111^32 = 111^64
111^64 * 111^32 = 111^96
111^96 * 111^16 = 111^112
111^112 * 111^8 = 111^120
111^120 * 111^2 * 111^1 = 111^123.
CookieOfFortune
I'm fairly certain that if that really optimises anything, it'd have been built-into the class. Generally, prefer to do the simplest thing that works.
Chris Jester-Young
I thought poster might've been creating his own implementation or something.
CookieOfFortune
the problem is not in computing 111^123but in computing (111^123)^(1/123)let `a = 111^123` then to compute `a^(1/123)`, the standard algorithm must compute a^122 and all powers below that.This is a problem because (111^123)^122 is a very large number.Note that the BigDecimal class does not implement the root function.
Jus12
Use the same method, but using square roots.
CookieOfFortune
Well I really don't want to compute 111^123^122.. since either way the number is too large and will take memory and time. I need an alternative method to compute roots that doesn't first compute powers
Jus12
How much accuracy do you need?
CookieOfFortune
+4  A: 

However, I noticed that the same thing using double takes less than a millisecond. So obviously they use some smart ideas.

Not really. double simply has limited precision, so it basically only has to compute the most significant 52 bits of the result and can skip the rest of the calculation. And of course, having this implemented in hardware also helps.

Michael Borgwardt
Yes, the limited precision is probably what makes `double` fast. I should have figured that out myself :-)What I really need is a clever algorithm to keep precision and compute large roots quickly. But... I'm sure this has been done in the literature, so I'm looking for references.
Jus12