Happy Numbers, Unhappy Numbers & Prime Numbers with Programming

Mayuravaani Mathuranathan
3 min readApr 27, 2021

Hi there! In this article, we will see about the happy numbers, unhappy numbers and prime numbers and how we can program it using java.

Happy Numbers

A happy number is a number which eventually reaches 1 when replaced by the sum of the square of each digit. For example, 19 is a happy number which could be explained as follows:

Unhappy Numbers

Unhappy number is a number, when the number is replaced by sum of the square of each digit, the cycle will repeat infinitely. For example, 3 is a unhappy number which could be explained as below.

The unhappy number will result in 4,37,58,89,145,42,20,4,37,……

Algorithm to find the given number is happy or not

  1. Read the number
  2. Calculate the sum of the square of all digits in the given number
  3. Check whether the sum is 1 or 4
  4. If the sum is 1 then return the given number is Happy
  5. If the sum is 4 then return the given number is Unhappy
  6. Otherwise number := sum
  7. Repeat the iteration from step 2 until it reaches 1 or 4
  8. End of the program

Flowchart

Java Program to find whether the given number is happy or not

Prime Numbers

Prime numbers are numbers that have only 2 factors: 1 and themselves. For example, if we consider 7 it can be divide by 1 and itself. So this is called as prime number and number 4 can be divide by 2. So this is not a prime number.

Algorithm to find the given number is prime or not

  1. Read the number
  2. Initialize i := 2, flag := true
  3. if(number = 0 or number = 1) then do step 8
  4. while(i ≤ number/2 and number != 2) do step 5 to 7
  5. Calculate remainder(rem) of number divided by i
  6. Increment the counter i ← i+1
  7. if rem = 0 then flag ← false and do step 8
  8. if flag = true return “Prime Number”
  9. else return “Not a prime number”
  10. End of the program

Flowchart

Java Program to find whether the given number is prime or not

--

--