write a program in java to input a number and check whether the number is a perfect number,a number is said to be perfect if the sum of the number is equal to the number inputted
Share
write a program in java to input a number and check whether the number is a perfect number,a number is said to be perfect if the sum of the number is equal to the number inputted
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Explanation:
To,@pakayashaswi
Here's a Java program that checks if a number is a perfect number:
```java
import java.util.Scanner;
public class PerfectNumberChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
scanner.close();
if (isPerfectNumber(number)) {
System.out.println(number + " is a perfect number.");
} else {
System.out.println(number + " is not a perfect number.");
}
}
public static boolean isPerfectNumber(int num) {
if (num <= 0) {
return false;
}
int sum = 0;
for (int i = 1; i < num; i++) {
if (num % i == 0) {
sum += i;
}
}
return sum == num;
}
}
```
Copy and paste this code into a Java file (e.g., `PerfectNumberChecker.java`) and then compile and run it. It will prompt you to enter a number and then check if it's a perfect number or not.