3

Say I have two numbers, a and bsuch that

1 <= a, b <= 10**9

How can I quickly check which is greater: a^b or b^a? Calculating a**b directly in Python is too slow.

planetp
  • 14,248
  • 20
  • 86
  • 160

2 Answers2

4

This is more of a mathematical question than a Python related question, but you can use math.log to find the b * math.log(a) and a * math.log(b) and compare them.

import math
a = 10
b = 9

if b * math.log(a) > a * math.log(b):
   print("a^b is greater than b^a")
else if b * math.log(a)< a * math.log(b):
   print("a^b is smaller than b^a")
Ahmed Tounsi
  • 1,482
  • 1
  • 14
  • 24
3

If a,b > e then you can only compare a,b:

Consider: f(x) = x/ln x:

Then:

f'(x) = (ln(x)-1) / ln(x)^2 which is positive for x>e: so f is increasing for x>e.

Now if a,b>e:

if a>b <=> f(a) > f(b) <=> alog(b) > blog(a)

Same for a<b.

coder
  • 12,832
  • 5
  • 39
  • 53