0

enter image description here

Diese Frage melden
gefragt

Punkte: 18

 
Kommentar schreiben
1 Antwort
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
geantwortet

Schüler, Punkte: 455

 

Kommentar schreiben