Monday , December 18 2017
Home / Blue J / Java program to print happy numbers for a given range

Java program to print happy numbers for a given range

This is a Java program to print happy numbers for a given range. But what is a happy number?

A number whose sum of the square of digits is ultimatly equal to 1 is a happy number. By ultimately we mean that starting with any positive number we continue the addition of square of digits till we get a single digit number (0 ~ 9). But the on whose sum is ultimately 1 is a happy number.

ALSO CHECK : Java program to check for a happy number

import java.io.*;
class happynumber
{
public static void main(String args[])throws Exception
{
int i,j,n,k;
happynumber obj=new happynumber();
System.out.print("Enter the upper limit for happy number series : ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
n=Integer.parseInt(br.readLine());           // Accept the range for the happy numbers till n i.e happy numbers from 1 to n
for(k=0;k<n;k++)
{i=k;
	while((j= obj.happy(i))/10 !=0)       //   You have to check the sum of all digits until a single digit is achieved i.e. sum=1,2,3,..9
	{
	i=j;				// If sum of digits= 19 it then again goes to 1+9 =10 and again 1+0= '1' a single digit to check if 1 or not
	}
	if(j==1)
System.out.print(k+",");
}
}
int happy (int n)
{
if(n/10==0)
return n*n;
else
return (int)Math.pow(n%10,2)+ happy(n/10);
}
}

OUTPUT:

Java program to print happy number series
Java program to print happy number series

Incoming terms: Java program to print happy numbers for a given range, program for happy number series

Also See:   java program for pattern#8

Check Also

Java program to implement polymorphism

Java program to implement polymorphism: Polymorphism is a technique in java with which you can ...

Leave a Reply

Your email address will not be published. Required fields are marked *