Happy Numbers, Unhappy Numbers & Prime Numbers with Programming
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
- Read the number
- Calculate the sum of the square of all digits in the given number
- Check whether the sum is 1 or 4
- If the sum is 1 then return the given number is Happy
- If the sum is 4 then return the given number is Unhappy
- Otherwise number := sum
- Repeat the iteration from step 2 until it reaches 1 or 4
- 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
- Read the number
- Initialize i := 2, flag := true
- if(number = 0 or number = 1) then do step 8
- while(i ≤ number/2 and number != 2) do step 5 to 7
- Calculate remainder(rem) of number divided by i
- Increment the counter i ← i+1
- if rem = 0 then flag ← false and do step 8
- if flag = true return “Prime Number”
- else return “Not a prime number”
- End of the program
Flowchart
Java Program to find whether the given number is prime or not