Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

Java Exercises: 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:

Java: ind and print the first 10 happy numbers.

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>();
	   while(num != 1 && cycle.add(num)){
           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:

Flowchart: Find and print the first 10 happy numbers

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program to print out the first 10 Catalan numbers by extracting them from Pascal's triangle.
Next: Write a Java program to check whether a given number is a happy number or unhappy number.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Java: Tips of the Day

How to sort an ArrayList?

Collections.sort(testList);
Collections.reverse(testList);

That will do what you want. Remember to import Collections though!

Ref: https://bit.ly/32urdSe