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.

3rd Oct 2017, 7:19 AM
Sangilivelu
Sangilivelu - avatar
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.
3rd Oct 2017, 7:23 AM
Sangilivelu
Sangilivelu - avatar