Happy numbers
This commit is contained in:
parent
1b9e60564a
commit
70f777aae4
1 changed files with 28 additions and 0 deletions
28
happynumbers.py
Executable file
28
happynumbers.py
Executable file
|
@ -0,0 +1,28 @@
|
||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
def happynumbers_step(n):
|
||||||
|
s = 0
|
||||||
|
for c in str(n):
|
||||||
|
s += int(c)**2
|
||||||
|
return s
|
||||||
|
|
||||||
|
def happynumbers(n):
|
||||||
|
founds = []
|
||||||
|
s = n
|
||||||
|
while True:
|
||||||
|
founds.append(s)
|
||||||
|
s = happynumbers_step(s)
|
||||||
|
if s == n:
|
||||||
|
return False
|
||||||
|
elif s in founds:
|
||||||
|
return False
|
||||||
|
elif s == 1:
|
||||||
|
return True
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
from sys import argv
|
||||||
|
if len(argv) > 1:
|
||||||
|
n = int(argv[1])
|
||||||
|
else:
|
||||||
|
n = 4
|
||||||
|
print("%d is a %s number" % (n,"happy" if happynumbers(n) else "unhappy"))
|
Loading…
Reference in a new issue