﻿ Java - Find and print the first 10 happy numbers

# Java: Find and print the first 10 happy numbers

## Java Numbers: Exercise-9 with Solution

Write a Java program to find and print the first 10 happy numbers.

Happy number: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1, or it loops endlessly in a cycle which does not include 1.

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

Pictorial Presentation: Sample Solution:

Java Code:

``````import java.util.HashSet;
public class Example9 {
public static void main(String[] args){
System.out.println("First 10 Happy numbers:");
for(long num = 1,count = 0;count<8;num++){
if(happy_num(num)){
System.out.println(num);
count++;
}
}
}
public static boolean happy_num(long num){
long m = 0;
int digit = 0;
HashSet<Long> cycle = new HashSet<Long>();
m = 0;
while(num > 0){
digit = (int)(num % 10);
m += digit*digit;
num /= 10;
}
num = m;
}
return num == 1;
}
}
```
```

Sample Output:

```First 10 Happy numbers:
1
7
10
13
19
23
28
31
```

Flowchart: Java Code Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿

## Java: Tips of the Day

IsPowerOfTwo

Checks if a value is positive power of two.

To understand how it works let's assume we made a call IsPowerOfTwo(4).

As value is greater than 0, so right side of the && operator will be evaluated.

The result of (~value + 1) is equal to value itself. ~100 + 001 => 011 + 001 => 100. This is equal to value.

The result of (value & value) is value. 100 & 100 => 100.

This will value the expression to true as value is equal to value.

```public static boolean isPowerOfTwo(final int value) {
return value > 0 && ((value & (~value + 1)) == value);
}
```

Ref: https://bit.ly/3sA5d4I

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook