Sunny Number in Java

Configurare noua (How To)

Situatie

Sunny Number

A number is called a sunny number if the number next to the given number is a perfect square. In other words, a number N will be a sunny number if N+1 is a perfect square.

Let’s understand it through an example.Suppose, we have to check if 80 is a sunny number or not. Given, N=80 then N+1 will be 80+1=81, which is a perfect square of the number 9. Hence 80 is a sunny number.

Let’s take another number 10.

Given, N=10 then N+1 will be 10+1=11, which is not a perfect square. Hence 10 is not a sunny number.

Steps to Find Sunny Number

The logic is very simple. To find the sunny number, we need only to check whether N+1 is the perfect square or not.

  1. Read or initialize a number (num).
  2. Add 1 to the given number i.e. num+1.
  3. Find the square root of num+1.
  4. If the square root is an integer, the given number is sunny, else not a sunny number.

Backup

  1. import java.util.*;
  2. public class SunnyNumberExample1
  3. {
  4. //driver code 
  5. public static void main(String args[])
  6. {
  7. Scanner sc = new Scanner(System.in);
  8. System.out.print(“Enter a number to check: “);
  9. //reading a number from the user
  10. int N=sc.nextInt();
  11. //calling user-defined function 
  12. isSunnyNumber(N);
  13. }
  14. //function checks whether the given is a perfect square or not 
  15. static boolean findPerfectSquare(double num)
  16. {
  17. //finds the square root of the ggiven number
  18. double square_root = Math.sqrt(num);
  19. //if square root is an integer 
  20. return((square_root – Math.floor(square_root)) == 0);
  21. }
  22. //function that checks whether the given number is Sunny or not
  23. static void isSunnyNumber(int N)
  24. {
  25. //checks N+1 is perfect square or not
  26. if (findPerfectSquare(N + 1))
  27. {
  28. System.out.println(“The given number is a sunny number.”);
  29. }
  30. //executes if N+1 is not a perfect square
  31. else
  32. {
  33. System.out.println(“The given number is not a sunny number.”);
  34. }
  35. }
  36. }

Output 1:

Enter a number to check: 80
The given number is a sunny number.

Output 2:

Enter a number to check: 670
The given number is not a sunny number.

Solutie

Tip solutie

Permanent

Voteaza

(11 din 21 persoane apreciaza acest articol)

Despre Autor

Leave A Comment?