Write a java program using loop to check whether a number is perfect square or not.
Answers
Answer:
input:
package com.beginnersbook;
import java.util.Scanner;
class JavaExample {
static boolean checkPerfectSquare(double x)
{
// finding the square root of given number
double sq = Math.sqrt(x);
/* Math.floor() returns closest integer value, for
* example Math.floor of 984.1 is 984, so if the value
* of sq is non integer than the below expression would
* be non-zero.
*/
return ((sq - Math.floor(sq)) == 0);
}
public static void main(String[] args)
{
System.out.print("Enter any number:");
Scanner scanner = new Scanner(System.in);
double num = scanner.nextDouble();
scanner.close();
if (checkPerfectSquare(num))
System.out.print(num+ " is a perfect square number");
else
System.out.print(num+ " is not a perfect square number");
}
}
Answer :-
Java Program to Check if a given Number is Perfect Number
- public class Perfect.
- int n, sum = 0;
- Scanner s = new Scanner(System.
- System. out. print("Enter any integer you want to check:");
- n = s. nextInt();
- for(int i = 1; i < n; i++)
- if(n % i == 0)
- sum = sum + i;