Created
February 22, 2025 01:43
-
-
Save jamescurran/4ec7068be8a1ec92f22eeba54709cb9d to your computer and use it in GitHub Desktop.
Daily Challenge #JS-105: Check if a Number is a Happy Number
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| A happy number is a number which eventually reaches 1 | |
| when replaced repeatedly by the sum of the square of | |
| its digits. If it loops endlessly in a cycle, | |
| then it is not a happy number. | |
| For example, starting with 19, the sequence is: 1² + 9² = 82, | |
| 8² + 2² = 68, | |
| 6² + 8² = 100, | |
| 1² + 0² + 0² = 1. | |
| Hence, 19 is a happy number. | |
| Implement a function to check if a given number is a happy number. | |
| https://en.wikipedia.org/wiki/Happy_number | |
| */ | |
| void Main() | |
| { | |
| IsHappyNumber(13).Dump(); | |
| IsHappyNumber(4).Dump(); | |
| IsHappyNumber(320).Dump(); | |
| IsHappyNumber(321).Dump(); | |
| } | |
| HashSet<int> HappyNums = new HashSet<int>(); | |
| HashSet<int> NonHappyNums = new HashSet<int>(); | |
| bool IsHappyNumber(int num) | |
| { | |
| var foundNums = new HashSet<int>(); | |
| while (num != 1) | |
| { | |
| if (HappyNums.Contains(num)) | |
| break; | |
| if(NonHappyNums.Contains(num)|| foundNums.Contains(num)) | |
| { | |
| AddRange(NonHappyNums, foundNums); | |
| return false; | |
| } | |
| foundNums.Add(num); | |
| num = SumDigitsSquared(num); | |
| } | |
| foundNums.Add(num); | |
| AddRange(HappyNums, foundNums); | |
| return true; | |
| } | |
| int SumDigitsSquared(int num) => Digits(num).Select(n => n * n).Sum(); | |
| IEnumerable<int> Digits(int n) | |
| { | |
| while (n > 0) | |
| { | |
| yield return n % 10; | |
| n = n /10; | |
| } | |
| } | |
| void AddRange(HashSet<int> hs, IEnumerable<int> others) | |
| { | |
| foreach (int n in others) | |
| hs.Add(n); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment