0
import java.util.Scanner;
public class PerfectNumber {
public static void main(String[] args) throws PR1Exception {
// get input
Scanner scanner = new Scanner(System.in);
int input = scanner.nextInt();
// determine whether the input number is perfect
if (isPerfectNumber(input))
System.out.println("Yes, the given number is perfect");
else
System.out.println("No, the given number is not perfect");
}
public static boolean isPerfectNumber(int n) throws PR1Exception {
if (n <= 0)
throw new PR1Exception();
// get all divisors of n
// sum up all divisors
int sum = 0;
for (int i = 1; i <= n/2; i++) {
if (n % i == 0)
sum += i;
}
// check if sum equals to n
return n == sum;
}
private static class PR1Exception extends Exception {
public PR1Exception() {
System.out.println("Input invalid");
}
}
}
Diese Antwort melden
Link
geantwortet
daniel.kuenkel
Schüler, Punkte: 455
Schüler, Punkte: 455