Sunny Number in Java: Meaning, Explanation, Examples, and Practice Problems
A Sunny Number is a number for which the next consecutive number is a perfect square. This is a well-known number theory concept often asked in coding interviews and beginner Java assignments due to its simple and logical approach.
What Is a Sunny Number?
A number N is a Sunny Number if:
N + 1 is a perfect square
That means if you add 1 to the number, the result must be a complete perfect square like 4, 9, 16, 25, and so on.
Examples of Sunny Numbers
- 3 → 3 + 1 = 4 (perfect square)
- 8 → 8 + 1 = 9 (perfect square)
- 15 → 15 + 1 = 16 (perfect square)
- 24 → 24 + 1 = 25 (perfect square)
How to Check Sunny Number?
Steps to determine if a number is Sunny:
- Add 1 to the given number.
- Find the square root of the new number.
- If the square root is an integer → it is a Sunny Number.
- If not → it is not a Sunny Number.
Java Program to Check Sunny Number
import java.util.*;
public class SunnyNumber {
static boolean isPerfectSquare(int n) {
int root = (int)Math.sqrt(n);
return root * root == n;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
if (isPerfectSquare(num + 1)) {
System.out.println("Sunny Number");
} else {
System.out.println("Not a Sunny Number");
}
}
}
Examples Table
| Number | N + 1 | Perfect Square? | Sunny? |
|---|---|---|---|
| 3 | 4 | Yes | Sunny Number |
| 8 | 9 | Yes | Sunny Number |
| 14 | 15 | No | Not Sunny |
| 24 | 25 | Yes | Sunny Number |
| 30 | 31 | No | Not Sunny |
3 Practice Challenges
Challenge 1: Print Sunny Numbers in a Range
Write a Java program to display all Sunny Numbers between 1 and 10,000.
Challenge 2: Sunny Numbers in an Array
Accept an array from the user and count how many elements are Sunny Numbers.
Challenge 3: Next Sunny Number
Write a Java program to find the next Sunny Number after a given integer.