mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-11-23 21:11:08 +00:00
Improve Project Euler problem 092 solution 1 (#5703)
* Fix typos * Improve solution
This commit is contained in:
parent
568425dfd1
commit
f92eac982d
|
@ -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:
|
||||
|
|
Loading…
Reference in New Issue
Block a user