From f92eac982dee9d4ea97e36cfda0f1fa19213b9f4 Mon Sep 17 00:00:00 2001 From: Maxim Smolskiy Date: Sun, 31 Oct 2021 13:38:28 +0300 Subject: [PATCH] Improve Project Euler problem 092 solution 1 (#5703) * Fix typos * Improve solution --- project_euler/problem_092/sol1.py | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/project_euler/problem_092/sol1.py b/project_euler/problem_092/sol1.py index dcda3a486..437a85bad 100644 --- a/project_euler/problem_092/sol1.py +++ b/project_euler/problem_092/sol1.py @@ -12,11 +12,14 @@ How many starting numbers below ten million will arrive at 89? """ +DIGITS_SQUARED = [digit ** 2 for digit in range(10)] + + def next_number(number: int) -> int: """ Returns the next number of the chain by adding the square of each digit - to form a neww number. - For example if number = 12, next_number() will return 1^2 + 2^2 = 5. + to form a new number. + For example, if number = 12, next_number() will return 1^2 + 2^2 = 5. Therefore, 5 is the next number of the chain. >>> next_number(44) 32 @@ -27,12 +30,15 @@ def next_number(number: int) -> int: """ sum_of_digits_squared = 0 while number: - sum_of_digits_squared += (number % 10) ** 2 + sum_of_digits_squared += DIGITS_SQUARED[number % 10] number //= 10 return sum_of_digits_squared +CHAINS = {1: True, 58: False} + + def chain(number: int) -> bool: """ The function generates the chain of numbers until the next number is 1 or 89. @@ -40,7 +46,7 @@ def chain(number: int) -> bool: following chain of numbers: 44 → 32 → 13 → 10 → 1 → 1. Once the next number generated is 1 or 89, the function returns whether - or not the the next number generated by next_number() is 1. + or not the next number generated by next_number() is 1. >>> chain(10) True >>> chain(58) @@ -48,10 +54,13 @@ def chain(number: int) -> bool: >>> chain(1) True """ - while number != 1 and number != 89: - number = next_number(number) + if number in CHAINS: + return CHAINS[number] - return number == 1 + number_chain = chain(next_number(number)) + CHAINS[number] = number_chain + + return number_chain def solution(number: int = 10000000) -> int: