# Happy Primes Code Kata

This code kata takes the typical kata to produce a list of primes or check if a number is a prime and puts a bit of a Doctor Who spin on it by producing a list of primes then checking to see if they are happy. A prime number is one that can only be factored by itself or one. A happy number is one that when the sum of the square of it’s digits are added then this method repeated will ultimately produce one.

For example 19 is a happy number:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

A happy prime is a number that is happy and prime. This kata is designed to iterate through a list of numbers to determine if a number is both prime and happy and therefore a happy prime. It could be adjusted to allow for user input to determine if the number given is a happy prime.

### Main class

The main class begins with a for loop iterating from 0 through 500. Each iteration checks first if the number is prime by calling a boolean method in the static HappyPrimeFinder class. If the IsPrime method returns true the IsHappy method is called to check if the prime is also a happy number. If IsHappy returns true the number is written to the console in the list of Happy Primes.

### IsPrime Method

IsPrime is a boolean method within the static class HappyPrimeFinder that takes an integer and checks if it is a prime number. If it is the method returns true. The boolean statement ((num & 1) == 0) returns true for even numbers. Then if the number is 2 it is a prime and the method returns true however if the even number is larger than two it is divisible by two and therefore not a prime and the method returns false.

Next in the method a for loop starts with 3 and increases by two so long as the square of increment is less than or equal to the number being tested. It then tests to see if the remainder of the number divided by the increment is 0. If that is true it returns false.

### IsHappy Method

IsHappy is another boolean method in the HappyPrimeFinder class that tests the prime numbers to see if they are also happy numbers. Remember that a happy number is one whose sum of it’s squared digits ultimately reduces down to one.

The method starts by converting the number (primes) into a character array then converting that into an array of integers with a foreach converting each character in the array into an integer then adding it to the integer array. Then it creates an intermediate integer for the sum of the squares of the digits in the integer array.

If the intermediate equals 1 the number is happy and the while loop is skipped. If the intermediate equals 4 the number is sad and will not reduce to 1 and the while loop is skipped. Any other values for intermediate enter the while loop and follow the same pattern of calculating the sum of the squared digits until intermediate equals either 1 or 4. If intermediate equals 1 the number is happy and the method returns true, if not the number is sad and returns false.

share