Project Euler: Problem 23

By | 4. Oktober 2015

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.

public class Problem23 {

	static List<Integer> abundant = new ArrayList<Integer>();
	static Set<Integer> sumList = new HashSet<Integer>();


	static long sum = 0;

	public static void main(String[] args) {
		for (int i = 1; i <= 28123; i++) {
			if (getSumOfDivisors(i) > i) {
				abundant.add(i);
			}
		}
		System.out.println("Total abundant numbers: " + abundant.size());
		for (int j = 0; j < abundant.size(); j++) {
			for (int k = 0; k < abundant.size(); k++) {
				int tempNum;
				if ((tempNum = abundant.get(j) + abundant.get(k)) < 28123) {
					sumList.add(tempNum);
				}
			}
		}
		System.out.println("Sum list generated: " + sumList.size());
		for (int i = 0; i < 28123; i++) {
			if (!sumList.contains(i)) {
				sum += i;
			}
		}
		System.out.println(sum);

	}

	public static int getSumOfDivisors(int number) {
		int sum = 0;
		for (int j = number / 2; j > 0; j--) {
			if (number % j == 0) {
				sum += j;
			}
		}
		return sum;
	}

}

Lösung: 4179871

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert