views:

763

answers:

4

From http://projecteuler.net/index.php?section=problems&id=99

Comparing two numbers written in index form like 211 and 37 is not difficult, as any calculator would confirm that 211 = 2048 37 = 2187.

However, confirming that 632382518061 > 519432525806 would be much more difficult, as both numbers contain over three million digits.

Using base_exp.txt (right click and 'Save Link/Target As...'), a 22K text file containing one thousand lines with a base/exponent pair on each line, determine which line number has the greatest numerical value.

How might I approach this?

+7  A: 

Not a full solution, but some ideas. You can use the following formula:

log(ax) = x*loga

The log10 can easily be estimated as number of digits. The log2 can easily be estimated by counting right shifts.

Based on the above you could narrow the list significantly. For the remaining numbers, you would have to do full calculations. Are math functions allowed in project Euler? If yes, it would be better to use logarithms.

kgiannakakis
Here a log seems to be missing.
starblue
+1. I translated it to Python and it works like a charm. Like so: reduce(lambda a, b: a if a[1] * log(a[0]) > b[1] * log(b[0]) else b, base_exp)
PEZ
nice ~ should have seen the possibility of the x*logA form
Devoted
+2  A: 

One possible approach would be to use logarithm identities (that is, ab is identical to eb * ln a). As a matter of fact, ab is identical to baseb * logbase a for all bases except 0 and 1.

Vatine
+3  A: 

Since the logarithm is a monotonic function, instead of ax you could compare x * log a to find the maximum. You might need to take numerical precision into account, though.

starblue
+2  A: 

Comparing exponent * log(base) instead of base^exponent for each line in the file works for this problem without taking precision into account. This is certainly the best solution from a mathematical perspective, but I just wanted to point out that this isn't really necessary.

Another possible solution is to divide every number in the file by some constant (say 100,000) before performing the exponentiation on the now smaller numbers. Since you're comparing all of the values to each other, scaling them all down by a constant factor doesn't affect the final outcome.

Bill the Lizard