Returns the number under n that generates the longest sequence using the formula: n → n/2 (n is even) n → 3n + 1 (n is odd) >>> solution(1000000) 837799 >>> solution(200) 171 >>> solution(5000) 3711 >>> solution(15000) 13255
(n: int = 1000000)
| 20 | |
| 21 | |
| 22 | def solution(n: int = 1000000) -> int: |
| 23 | """Returns the number under n that generates the longest sequence using the |
| 24 | formula: |
| 25 | n → n/2 (n is even) |
| 26 | n → 3n + 1 (n is odd) |
| 27 | |
| 28 | >>> solution(1000000) |
| 29 | 837799 |
| 30 | >>> solution(200) |
| 31 | 171 |
| 32 | >>> solution(5000) |
| 33 | 3711 |
| 34 | >>> solution(15000) |
| 35 | 13255 |
| 36 | """ |
| 37 | largest_number = 1 |
| 38 | pre_counter = 1 |
| 39 | counters = {1: 1} |
| 40 | |
| 41 | for input1 in range(2, n): |
| 42 | counter = 0 |
| 43 | number = input1 |
| 44 | |
| 45 | while True: |
| 46 | if number in counters: |
| 47 | counter += counters[number] |
| 48 | break |
| 49 | if number % 2 == 0: |
| 50 | number //= 2 |
| 51 | counter += 1 |
| 52 | else: |
| 53 | number = (3 * number) + 1 |
| 54 | counter += 1 |
| 55 | |
| 56 | if input1 not in counters: |
| 57 | counters[input1] = counter |
| 58 | |
| 59 | if counter > pre_counter: |
| 60 | largest_number = input1 |
| 61 | pre_counter = counter |
| 62 | return largest_number |
| 63 | |
| 64 | |
| 65 | if __name__ == "__main__": |