Saturday 11 April 2009

PROJECT EULER #23

Link to Project Euler problem 23

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 whose proper divisors are less than the number is called deficient and a number whose proper divisors exceed the number is called abundant.

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.


using System;
using System.Collections.Generic;

namespace project_euler
{
class Program
{
static void Main()
{
//Problem 23
DateTime start = DateTime.Now;
int result = 0;
List<int> abundantNumbers = new List<int>();
List<int> numbers = new List<int>();

for (int i = 0; i < 28123; i++)
{
numbers.Add(i+1);
result += numbers[i];
if (IsAbundant(numbers[i]))
abundantNumbers.Add(numbers[i]);
}
for (int i = 0; i < abundantNumbers.Count; i++)
for (int j = i; j < abundantNumbers.Count; j++)
{
int temp = abundantNumbers[i] + abundantNumbers[j] - 1;
if (temp < numbers.Count)
{
result -= numbers[temp];
numbers[temp] = 0;
}
}
Console.WriteLine(result);
TimeSpan time = DateTime.Now - start;
Console.WriteLine("This took {0}", time);
Console.ReadKey();
}

public static bool IsAbundant(int n)
{
int sum = 0;
for (int i = 1; i < n; i++)
if (n%i == 0)
sum += i;
if (sum > n)
return true;
return false;
}
}
}
71

No comments: