Java Program to Check Sunny Number

A sunny number is a number where the next number (n + 1) is a perfect square.

For example, 8 is a sunny number because 8 + 1 = 9, which is a perfect square (3 × 3).

1. Understanding the Problem

Determine whether a given number is a sunny number.

Number: 8 → Sunny
Number: 15 → Sunny
Number: 10 → Not Sunny

2. Using Basic Loop

Java
Check sunny number using loop
import java.util.Scanner;

public class SunnyNumber {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int num = sc.nextInt();

        int next = num + 1;
        boolean isSunny = false;

        for (int i = 1; i * i <= next; i++) {
            if (i * i == next) {
                isSunny = true;
                break;
            }
        }

        if (isSunny)
            System.out.println("Sunny Number");
        else
            System.out.println("Not a Sunny Number");
    }
}

3. Optimized Approach

Java
Check sunny number using square root
import java.util.Scanner;

public class SunnyOptimized {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int num = sc.nextInt();

        int next = num + 1;
        int sqrt = (int) Math.sqrt(next);

        if (sqrt * sqrt == next)
            System.out.println("Sunny Number");
        else
            System.out.println("Not a Sunny Number");
    }
}

4. Common Mistakes

1. Forgetting to add 1 to the number.

2. Incorrect perfect square check.

3. Using floating-point comparison incorrectly.

4. Not casting square root properly.

5. Applications

1. Helps in understanding perfect square logic.

2. Useful for practicing mathematical conditions.

3. Common beginner-level programming problem.

Conclusion

Sunny numbers are useful for learning number properties and square root logic.

Using square root method makes the program efficient and simple.