Q:

Python program to print all happy numbers between 1 and 100

belongs to collection: Python Number Programs

0

In this programme, we need to print all happy numbers between 1 and 100 by following the algorithm as given below:

ALGORITHM:

  • STEP 1: isHappyNumber() determines whether a given number is happy or not.
    1. If the number is greater than 0, calculate remainder rem by dividing the number with 10.
    2. Calculate square of rem and add it to a variable sum.
    3. Divide number by 10.
    4. Repeat the steps from a to c till the sum of the square of all digits present in number has been calculated.
    5. Finally, return the sum.
  • STEP 2: To display all happy numbers between 1 and 100,
    1. Start a loop from 1 to 100, then make a call to isHappyNumber() method for each value from 1 to 100 and store the return value into a variable result.
    2. If the result is neither equal to 1 nor 4 then, make a call to isHappyNumber().
    3. Otherwise, if the result is equal to 1, it implies that the number is happy and display it.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

#isHappyNumber() will determine whether a number is happy or not    
def isHappyNumber(num):    
    rem = sum = 0;    
        
    #Calculates the sum of squares of digits    
    while(num > 0):    
        rem = num%10;    
        sum = sum + (rem*rem);    
        num = num//10;    
    return sum;    
            
#Displays all happy numbers between 1 and 100    
print("List of happy numbers between 1 and 100: ");    
for i in range(1, 101):    
    result = i;    
        
    #Happy number always ends with 1 and     
    #unhappy number ends in a cycle of repeating numbers which contains 4    
    while(result != 1 and result != 4):    
        result = isHappyNumber(result);    
        
    if(result == 1):    
        print(i),    
        print(" "),    

 

Output:

List of happy numbers between 1 and 100:
1  7  10  13  19  23  28  31  32  44  49  68  70  79  82  86  91  94  97  100 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python program to determine whether the given numb... >>
<< Python program to check if the given number is Hap...