Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Happy number python #830

Merged
merged 4 commits into from
Aug 31, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions Python/HappyNumber.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# Python program to check if a number is happy or not:

# funtion to get sum of squares of the digits of a number:
def ssd(n):
a = b = 0;
while(n > 0):
a = n%10
b += a*a
n //= 10
return b

# User input:
print("Enter Number to Check:")
n = int(input())
h = n;

while(h != 1 and h != 4):
h = ssd(h)

if(h == 1):
print(n,"is a happy number")
elif(h == 4):
print(n,"is not a happy number")

'''
Explanation:
A happy number is a number which eventually reaches 1 when replaced
by the sum of the square of each digit. All Non happy numbers eventually
become 4 and get stuck in an infinite cycle, therefore if a number reaches 4
anytime in the cycle it is not a happy number

Examples of Happy Numbers:
-> 100 = 1*1 + 0*0 +0*0 = 1
-> 13 = 1*1 + 3*3 = 10, 10 = 1*1 + 0*0 = 1
-> 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

Sample Input:
Enter Number to Check:
13

Sample Output:
13 is a happy number

Time Complexity : O(log N)
Space Complexity : O(log N)
'''
3 changes: 2 additions & 1 deletion Python/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,8 @@ Format: -[Program name](name of the file)

-[Greatest Common divisor](gcd.py)

-[Happy Number](HappyNumber.py)

-[Heap Sort](Heap_sort.py)

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

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