|
| 1 | +""" |
| 2 | +Project Euler Problem 188: https://projecteuler.net/problem=188 |
| 3 | +
|
| 4 | +The hyperexponentiation of a number |
| 5 | +
|
| 6 | +The hyperexponentiation or tetration of a number a by a positive integer b, |
| 7 | +denoted by a↑↑b or b^a, is recursively defined by: |
| 8 | +
|
| 9 | +a↑↑1 = a, |
| 10 | +a↑↑(k+1) = a(a↑↑k). |
| 11 | +
|
| 12 | +Thus we have e.g. 3↑↑2 = 3^3 = 27, hence 3↑↑3 = 3^27 = 7625597484987 and |
| 13 | +3↑↑4 is roughly 103.6383346400240996*10^12. |
| 14 | +
|
| 15 | +Find the last 8 digits of 1777↑↑1855. |
| 16 | +
|
| 17 | +References: |
| 18 | + - https://en.wikipedia.org/wiki/Tetration |
| 19 | +""" |
| 20 | + |
| 21 | + |
| 22 | +# small helper function for modular exponentiation |
| 23 | +def _modexpt(base: int, exponent: int, modulo_value: int) -> int: |
| 24 | + """ |
| 25 | + Returns the modular exponentiation, that is the value |
| 26 | + of `base ** exponent % modulo_value`, without calculating |
| 27 | + the actual number. |
| 28 | + >>> _modexpt(2, 4, 10) |
| 29 | + 6 |
| 30 | + >>> _modexpt(2, 1024, 100) |
| 31 | + 16 |
| 32 | + >>> _modexpt(13, 65535, 7) |
| 33 | + 6 |
| 34 | + """ |
| 35 | + |
| 36 | + if exponent == 1: |
| 37 | + return base |
| 38 | + if exponent % 2 == 0: |
| 39 | + x = _modexpt(base, exponent / 2, modulo_value) % modulo_value |
| 40 | + return (x * x) % modulo_value |
| 41 | + else: |
| 42 | + return (base * _modexpt(base, exponent - 1, modulo_value)) % modulo_value |
| 43 | + |
| 44 | + |
| 45 | +def solution(base: int = 1777, height: int = 1855, digits: int = 8) -> int: |
| 46 | + """ |
| 47 | + Returns the last 8 digits of the hyperexponentiation of base by |
| 48 | + height, i.e. the number base↑↑height: |
| 49 | +
|
| 50 | + >>> solution(base=3, height=2) |
| 51 | + 27 |
| 52 | + >>> solution(base=3, height=3) |
| 53 | + 97484987 |
| 54 | + >>> solution(base=123, height=456, digits=4) |
| 55 | + 2547 |
| 56 | + """ |
| 57 | + |
| 58 | + # calculate base↑↑height by right-assiciative repeated modular |
| 59 | + # exponentiation |
| 60 | + result = base |
| 61 | + for i in range(1, height): |
| 62 | + result = _modexpt(base, result, 10 ** digits) |
| 63 | + |
| 64 | + return result |
| 65 | + |
| 66 | + |
| 67 | +if __name__ == "__main__": |
| 68 | + print(f"{solution() = }") |
0 commit comments