fork download
  1. def is_beautiful(num, memo={}):
  2. # Function to check if a number is beautiful using memoization
  3. if num in memo:
  4. return memo[num]
  5.  
  6. seen = set()
  7. while num != 1 and num not in seen:
  8. seen.add(num)
  9. num = sum(int(digit)**2 for digit in str(num))
  10.  
  11. memo[num] = num == 1
  12. return memo[num]
  13.  
  14. def beautiful_numbers(l, r):
  15. # Function to find beautiful numbers within range [l, r]
  16. beautiful_nums = []
  17. for num in range(l, r+1):
  18. if is_beautiful(num):
  19. beautiful_nums.append(num)
  20. return beautiful_nums
  21.  
  22. def solve(l, r):
  23. # Function to solve the problem
  24. beautiful_nums = beautiful_numbers(l, r)
  25. if beautiful_nums:
  26. return sum(beautiful_nums)
  27. else:
  28. return 0
  29. print (solve(31,32))
Success #stdin #stdout 0.03s 9372KB
stdin
Standard input is empty
stdout
63