Problem 23

Statement
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.

Solution
The code, in C.

#include <stdio.h>
#include <stdlib.h>

struct vector{
  int l;
  int s;
  int *a;
};

struct vector *vectorNew(){
  struct vector *v = (struct vector *) malloc(sizeof(struct vector));
  v->l=0;
  v->s=1;
  v->a=malloc(sizeof(int));
  return v;
}

void vectorAdd(struct vector *v, int a){
  if(v->l < v->s){
    v->a[0] = a;
    (v->l)++;
  }
  else{
    (v->l)++;
    (v->s)++;
    v->a = realloc((void *) v->a,sizeof(int)*(v->l));
    v->a[v->l-1] = a;
  }
  return;
}

int factSum(int a)
{
  int i,b=a,s=1;
  for(i=2;i<b;i++){
    if(!(a%i)){
      s+=i;
      if(i!=a/i)
	s+=a/i;
      b=a/i;
    }
  }
  return s;
}

int main(void)
{
  int i,j,r[28123+1]={0};
  long long int n=0;
  struct vector *v = vectorNew();
  for(i=1;i<=28123;i++)
    if(factSum(i)>i)
      vectorAdd(v,i);
  for(i=0;i<v->l;i++)
    for(j=i;j<v->l;j++)
      if(v->a[i]+v->a[j]<=28123)
	r[v->a[i]+v->a[j]]=1;
  for(i=0;i<=28123;i++)
    if(!r[i])
      n+=i;
  printf("%d\n",n);
  return 0;
}

Answer
4179871

No tags for this post.

SPEAK / ADD YOUR COMMENT
Comments are moderated.

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>