Skip to content

Commit efd3034

Browse files
authored
Happy number python (#830)
* On branch AbundantNumber Changes to be committed: new file: Python/abundantnumber.py * On branch HappyNumberPython Changes to be committed: new file: Python/HappyNumber.py * On branch HappyNumberPython Changes to be committed: modified: Python/README.md * On branch HappyNumberPython Changes to be committed: deleted: Python/abundantnumber.py
1 parent 48423a0 commit efd3034

File tree

2 files changed

+48
-1
lines changed

2 files changed

+48
-1
lines changed

Python/HappyNumber.py

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# Python program to check if a number is happy or not:
2+
3+
# funtion to get sum of squares of the digits of a number:
4+
def ssd(n):
5+
a = b = 0;
6+
while(n > 0):
7+
a = n%10
8+
b += a*a
9+
n //= 10
10+
return b
11+
12+
# User input:
13+
print("Enter Number to Check:")
14+
n = int(input())
15+
h = n;
16+
17+
while(h != 1 and h != 4):
18+
h = ssd(h)
19+
20+
if(h == 1):
21+
print(n,"is a happy number")
22+
elif(h == 4):
23+
print(n,"is not a happy number")
24+
25+
'''
26+
Explanation:
27+
A happy number is a number which eventually reaches 1 when replaced
28+
by the sum of the square of each digit. All Non happy numbers eventually
29+
become 4 and get stuck in an infinite cycle, therefore if a number reaches 4
30+
anytime in the cycle it is not a happy number
31+
32+
Examples of Happy Numbers:
33+
-> 100 = 1*1 + 0*0 +0*0 = 1
34+
-> 13 = 1*1 + 3*3 = 10, 10 = 1*1 + 0*0 = 1
35+
-> 19 = 1*1 + 9*9 = 82, 82 = 8*8 + 2*2 = 68, 68 = 6*6 + 8*8 = 100, 100 = 1*1 + 0*0 + 0*0 =1
36+
37+
Sample Input:
38+
Enter Number to Check:
39+
13
40+
41+
Sample Output:
42+
13 is a happy number
43+
44+
Time Complexity : O(log N)
45+
Space Complexity : O(log N)
46+
'''

Python/README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,8 @@ Format: -[Program name](name of the file)
6666

6767
-[Greatest Common divisor](gcd.py)
6868

69+
-[Happy Number](HappyNumber.py)
70+
6971
-[Heap Sort](Heap_sort.py)
7072

7173
-[Inorder Tree Traversal](inordder.py)
@@ -171,4 +173,3 @@ Format: -[Program name](name of the file)
171173
-[Unique Number From A Set of Numbers repeated twice except unique number](unique_number_repeated_twice_except_unique_number.py)
172174

173175
-[All Hamiltonian Cycles/Paths](all_hamiltonian_cycles.py)
174-

0 commit comments

Comments
 (0)