![]() |
A Happy Number n is defined by the following process. Starting with n, replace it with the sum of the squares of its digits, and repeat the process until n equals 1, or it loops endlessly in a cycle that does not include 1. Those numbers for which this process ends in 1 are Happy Numbers, while those that do not end in 1 are unhappy numbers. Example :
Python Program to Print all Happy Numbers Between 1 and 100Below, are the code examples of Python programs to Print all Happy Numbers Between 1 and 100.
Print all Happy Numbers Between 1 and 100 Using Set() MethodIn this example, below Python code defines two functions: ‘numSquareSum()’ function computes the sum of squares of digits. ‘isHappyNumber()‘ uses ‘numSquareSum()‘ to determine happiness, tracking visited numbers with a set. The loop prints Happy Numbers between 1 and 100 using ‘isHappyNumber()’.
Output 1 7 10 13 19 23 28 31 32 44 49 68 70 79 82 86 91 94 97 100 Print all Happy Numbers Between 1 and 100 Using Floyd’s Cycle Detection AlgorithmIn this example, in below Python code loop checks numbers from 1 to 100 using ‘isHappyNumber()‘, which applies Floyd’s Cycle Detection Algorithm with ‘numSquareSum()‘ to find happy numbers. ‘numSquareSum()‘ calculates the sum of squares of digits.
Output 1 7 10 13 19 23 28 31 32 44 49 68 70 79 82 86 91 94 97 100 Print all Happy Numbers Between 1 and 100 Using RecursionIn this example, Python code defines two functions: ‘numSquareSum()‘ calculates the sum of squares of digits of a number, and ‘isHappyNumber()‘ determines if a number is happy by recursively applying ‘numSquareSum()’ until either 1 is reached (indicating happiness) or a cycle is detected, using a set to keep track of visited numbers.
Output 1 7 10 13 19 23 28 31 32 44 49 68 70 79 82 86 91 94 97 100 |
Reffered: https://www.geeksforgeeks.org
Python |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 15 |