Algorithm Training/10%

#99 Largest exponential

Hwigang Lee 2022. 1. 31. 00:20

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, 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.

 

NOTE: The first two lines in the file represent the numbers in the example given above.


더보기

This is a rather simple problem. If you want to know how many digits 1000 is, take a log of it. log101000 is equal to 3 and 1000 is a 4-digit number. Likewise, 632382518061 would be a number with 3 million and 5262 digits and 519432525806 with 3 million and 5260 digits in the decimal system.

 

with open("p099_base_exp.txt", "r") as f:
    data = [[int(x) for x in y.split(",")] for y in f.read().split()]

The data come out as follows.

[[519432, 525806],
 [632382, 518061],
 [78864, 613712],
 ...
 [325361, 545187],
 [172115, 573985],
 [13846, 725685]]

 

I used enumerate function to get the index since the problem requires the line number.

According to the power rule of logarithms, the log of n to the power of m is m times logarithm of n.

from math import log10

# initialize the index and maximum
index = 0
maximum = [1, 1]

for line, exp in enumerate(data):
    # the power rule of logarithms
    a = exp[1] * log10(exp[0])
    b = maximum[1] * log10(maximum[0])

    # renew the largest exponential and keep the line number
    if a > b:
        maximum[0], maximum[1] = exp[0], exp[1]
        index = line + 1

 

The largest exponential is 895447504922, in the 709th line.

'Algorithm Training > 10%' 카테고리의 다른 글

#69 Totient maximum  (0) 2022.01.30
#81 Path sum: two ways  (0) 2022.01.25