Irena Rich
Irena Rich

Reputation: 150

Unable to nest a perfect number test within a loop

I'm trying to create a perfect number test for a range of numbers, with n being the start number and endNum being the end number. It won't loop properly, but the perfect number test (portion inside the "while" loop) works by itself. What am I doing wrong?

import java.util.Arrays;
import java.util.Scanner;

public class CodingChallenge3 {

public static void main(String[] args) {

    int n, sum = 0;
    Scanner s = new Scanner(System.in);
    System.out.print("Welcome to the Perfect Number Tester."
                        + "\n" + "Enter a number range."
                        + "\n" + "From: ");
    n = s.nextInt();
    System.out.print("To: ");
    int endNum = s.nextInt();

    while (n <= endNum) {

        for (int i = 1; i < n; i++) {
            if (n % i == 0) {
                sum = sum + i;
            }
        }

        if (sum == n && n != 0) {
            System.out.println(n + " is perfect");
        }

        if (sum > n) {
            System.out.println(n + " is imperfect abundant");
        }

        if (sum < n) {
            System.out.println(n + " is imperfect deficient");
        }

        if (n == 0) {
            System.out.println(n + " has no factors");
        }
        n++;
    }

}

}

Upvotes: 1

Views: 73

Answers (1)

Eran
Eran

Reputation: 393851

You forgot to reset the sum for each value of n:

while (n <= endNum) {
    sum = 0; // add this
    for (int i = 1; i < n; i++) {
        if (n % i == 0) {
            sum = sum + i;
        }
    }

    if (sum == n && n != 0) {
        System.out.println(n + " is perfect");
    }

    if (sum > n) {
        System.out.println(n + " is imperfect abundant");
    }

    if (sum < n) {
        System.out.println(n + " is imperfect deficient");
    }

    if (n == 0) {
        System.out.println(n + " has no factors");
    }
    n++;
}

Upvotes: 4

Related Questions