0
Happy number algorithm
Is your number happy? It's fun, quick and thoughtful. Take a positive integer (any digit): Say, 129 Square each digit and add them: 1^2+2^2+9^2=1+4+81=86 We need to repeat it until we reach the sum of square of all digits equal to 1 8^2+6^2=64+36=100 1^2+0^2+0^2=1+0+0=1 It is not happy, if it ends in any of the following numbers, 4, 16, 37, 58, 89, 145, 42, 20, 4. This is your base case for any loop. The challenge is, List all the happy numbers upto given number if possible, list happy primes too.
1 Answer
0
You can improve the answer with following abilities.
1) âAbility to choose power.
In basic case, we do squares to demonstrate happyness. But, this can be generalized.
2) âAbility to find happy numbers in all positive integer bases. In this case,
âassume given number is base10
âfor each number from 1 to given number,
âbase10 to baseGiven
ârun the happy subroutine
âcheck happyness â
âthen display in base 10
In this case, your base case for loop changes a bit.
Every time you find a number's pair, you can dynamically store the number and proceed. After every iteration, you check the new value with already found ones. If it is there, you can simply conclude that the number is not happy, because same cycle of numbers will appear again.
Thus you don't need to proceed.