Commit 257a2a8e by Andrew Dahl

Solved Problem 21

parent ecb9358d
Showing with 72 additions and 0 deletions
Question:
Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
If d(a) = b and d(b) = a, where a b, then a and b are an amicable pair and each of a and b are called amicable numbers.
For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.
Evaluate the sum of all the amicable numbers under 10000.
Answer: 31626
#include <iostream>
#include <vector>
using namespace std;
int main() {
bool found = false;
int sum = 1;
int max = 10000;
vector<int> numbers;
vector<int> final_numbers;
numbers.push_back(0);
numbers.push_back(1);
numbers.push_back(3);
numbers.push_back(4);
for(int i = 4; i <= max; i++)
{
sum = 0;
for(int j = 1; j < i/2; j++)
{
if(i % j == 0)
{
if(j == (i/j))
{
sum += j;
break;
}
if(j > i/j)
break;
if((i/j) != i)
sum += i/j;
sum += j;
}
}
numbers.push_back(sum);
}
sum = 0;
for(int i = 4; i <= max; i++)
{
if(numbers[i] <= max && numbers[numbers[i]] == i && i != numbers[i])
{
found = false;
for(int j = 0; j < final_numbers.size() && !found; j++)
if(final_numbers[j] == i)
found = true;
if(!found)
{
final_numbers.push_back(i);
final_numbers.push_back(numbers[i]);
sum += i + numbers[i];
}
}
}
cout << sum << endl;
return 0;
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment