Java Program to Check Sunny Number

Write a Java program to check sunny number or not. Any number (n) can be the sunny number if its successor or the following number (n + 1) is a perfect square. For instance, 23 is because its following number, 24 (23 + 1), is a perfect square of 4.

package NumPrograms;

import java.util.Scanner;

public class SunnyNumber1 {
	private static Scanner sc;
	
	public static void main(String[] args) {

		sc = new Scanner(System.in);	
		
		System.out.print("Enter Number to Check for Sunny Number = ");
		int sNum = sc.nextInt();

		if (perfectSquare(sNum + 1)) 
		{
			System.out.println(sNum +  " is a Sunny Number");
		}
		else 
		{
			System.out.println(sNum +  " is Not a Sunny Number");
		}
	}
	
	static boolean perfectSquare(double sNum) {
		double squareRoot = Math.sqrt(sNum);
		
		return ((squareRoot - Math.floor(squareRoot)) == 0);
	}
}
Java Program to Check Sunny Number

This program accepts the start and end range and prints the sunny numbers between a range or 1 to N.

package NumPrograms;

import java.util.Scanner;

public class Example2 {
	private static Scanner sc;
	
	public static void main(String[] args) {

		sc = new Scanner(System.in);	
		
		System.out.print("Enter Start and End Range = ");
		int start = sc.nextInt();
		int end = sc.nextInt();
		
		System.out.println("The List of Numbers from " + start + " to " + end);
		for(int i = start; i <= end; i++)
		{
			if (perfectSquare(i)) 
			{
				System.out.print(i +  "  ");
			}
		}
	}
	
	static boolean perfectSquare(int sNum) {
		if(Math.sqrt(sNum + 1) % 1 == 0)
		{
			return true;
		}
		else 
		{
			return false;
		}
	}
}
Enter Start and End Range = 1 1000
The List of Numbers from 1 to 1000
3  8  15  24  35  48  63  80  99  120  143  168  195  224  255  288  323  360  399  440  483  528  575  624  675  728  783  840  899  960 

About Suresh

Suresh is the founder of TutorialGateway and a freelance software developer. He specialized in Designing and Developing Windows and Web applications. The experience he gained in Programming and BI integration, and reporting tools translates into this blog. You can find him on Facebook or Twitter.