简体   繁体   中英

Project Euler #23 (Java). I can't figure out what's wrong. Answer is off by 64

The problem is:

A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number. A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n. As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit.

Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.

My method creates a list of abundant numbers below the limit, creates a list of numbers created by adding abundant numbers to each other, then find the numbers which do not appear on this list, and adds them to find their sum. The answer is supposed to be 4179871, while I get 4179935. I am off by 64 and I can't figure out why. My code is:

public static void main(String[] args) {

    int limit = 28124;
    int sum=0;
    int tempNum;
    int listSize;
    ArrayList<Integer> list = new ArrayList<Integer>();
    ArrayList<Integer> sumList = new ArrayList<Integer>();
    for (int i=0; i<limit; i++) {

        if (isAbundant(i)) {

            list.add(i);
        }
    }
    listSize = list.size();

    for (int i=0; i<listSize; i++) {

        for (int j=i+1; j<listSize; j++) {

            tempNum = list.get(i) + list.get(j);
            if (tempNum < limit) {
                sumList.add(tempNum);
            }
        }
    }

    for (int i=1; i<limit; i++) {

        if (sumList.contains(i) == false) {

            sum += i;
        }
    }
    System.out.println(sum);
}

public static boolean isAbundant(int n) {

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

        if (n%i==0) {

            sum += i;
        }
    }
    if (sum>n) { return true; }
    else { return false; }
}

Any assistance is appreciated.

The nested for loop should start with i instead of i+1 (otherwise you ignore sum with same indices):

for (int i=0; i<listSize; i++) {

    for (int j=i; j<listSize; j++) {

        tempNum = list.get(i) + list.get(j);
        if (tempNum < limit) {
            sumList.add(tempNum);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM