Programmers Arena: HAPPY Numbers using Python

Friday, 11 July 2014

HAPPY Numbers using Python

Okay so this is my second post in the special mathematical series, this time its HAPPY NUMBERS, this series of numbers is easy to understand in base 10. Any number whose digits when separately squared and then added gives 1 is a happy number.
For more info refer to the link below:

http://en.wikipedia.org/wiki/Happy_number

So  you're gonna want to separate the digits of your number, what you can do is,

    i=input("Enter the number")
    a=i/100
    b=i/10-a*10
    c=i-b*10-a*100

Note the fact that the above code would only work for a number less than 100.

Now you need to verify whether the number is happy or unhappy (unhappy numbers are those numbers which are not happy :P).

n=0
while True:
        a=a**2
        b=b**2
        c=c**2
        n=n+1
        t=a+b+c
        if t==1:
            print n,":",i, "--> Happy!"
            break
        if n>=50:
            print i, "--> Unhappy!"
            break
        a=t/100
        b=t/10-a*10
        c=t-b*10-a*100

The above loop works as your verification code, if your number "i" is a happy number which get a sum of one within the first fifty trials then it would give you an output saying its a happy number, otherwise it would give you a message saying its an unhappy number. Further more if you want to save your happy and unhappy numbers separately in two different lists you can make a full fledged script to do it, copy the following code to your empty python script and save it as "Happy num.py"

l1=[]
l2=[]
for i in range (0,100):
    t=i    
    a=i/100
    b=i/10-a*10
    c=i-b*10-a*100
    n=0
    while True:
        a=a**2
        b=b**2
        c=c**2
        n=n+1
        t=a+b+c
        if t==1:
            print n,":",i, "--> Happy!"
            l1.append(i)
            break
        if n>=50:
            print i, "--> Unhappy!"
            l2.append(i)
            break
        a=t/100
        b=t/10-a*10
        c=t-b*10-a*100
Programmers Arena Home
Copyright © Programmers Arena