This is my program for project euler #23 --
http://projecteuler.net/problem=23Quote
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.
The answer is 4179871, but my program is showing 3796959, can anyone see why?
Quote
#include <iostream>
#include <cmath>
using namespace std;
int hold[28124];
int abundant[7000] = {0};
bool abundance(int x){ <-- this function shows if number is abundant, works as intended
int counter = 0;
int counter2 = 0;
for (int i = 2; i < sqrt(x); i++){
if (x % i == 0){
counter += i;
counter += x / i;
}
}
int y = sqrt(x);
if (x % y == 0){
counter += sqrt(x);
}
if (counter > x){
return true;
} else {
return false;
}
}
int main()
{
int counter = 0;
for (int i = 0; i < 28124; i++){ <-- fills hold[0] ... hold[28123] with numbers 0 ... 28123, by default all numbers aren't sums of 2 abundant numbers (up to 28123 )
hold[i] = i;
}
for (int j = 10; j < 28124; j++){ <-- fills array abundant with abundant numbers, works just fine (12, 18, 20, 24, 30, 36, 40, etc.)
if (abundance(j) == true){ final value = 28122, no need for more because 28122 + 12 is already more than 28123
abundant[counter] = j;
counter++;
}
}
for (int m = 0; m < 7000; m++){ <-- adds every possible abundant number combination, 12 + 12, 12 + 18 ... 12 + 28122 --- 18 + 12, 18 + 18 ... 18 _ 28122, etc
for (int n = 0; n < 7000; n++){
if (abundant[m]+abundant[n] < 28124){
hold[abundant[m]+abundant[n]] = 0; <-- for every sum, sets the corresponding element in hold[ ] to 0, any left over CAN'T be the sum of 2 abundant numbers
}
}
}
long long counter2 = 0; <-- lastly, just add all the values together like the program asks
for (int x = 0; x < 28124; x++){
counter2 += hold[x];
}
cout << counter2 << endl;
}
This post was edited by Foxic on Apr 20 2013 01:52am