How to check which is greater: a**b or b**a for big numbers?

Viewed 187

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.

2 Answers

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")

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.

Related