Skip to content

Instantly share code, notes, and snippets.

@JellyWX
Created September 13, 2018 16:26
Show Gist options
  • Save JellyWX/27fb9e025ba87987768cffccd7b5ace1 to your computer and use it in GitHub Desktop.
Save JellyWX/27fb9e025ba87987768cffccd7b5ace1 to your computer and use it in GitHub Desktop.
import time
def sq_digits(n):
nums = []
div, mod = divmod(n, 10)
nums.append(mod)
while div >= 10:
div, mod = divmod(div, 10)
nums.append(mod)
nums.append(div)
r = 0
for d in nums:
r += d ** 2
return r
def test_happy(t):
li = set()
out = t
while out != 1:
out = sq_digits(out)
if out not in li:
li.add(out)
else:
return False
return True
count = 0
for i in range(0, 10):
print('Testing for {} digits (mean of 3)'.format(i))
times = []
for _ in range(3):
start = time.time()
for j in range(0, 10**i):
x = test_happy(j)
# print('is {} happy? {}.'.format(j, x))
if x:
count += 1
else:
invalid.add(j)
#print('{} happy numbers.'.format(count))
end = time.time()
print('- Completion time was {}s'.format(end-start))
times.append(end-start)
print('Average time: {}'.format(sum(times)/3))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment