マツケンのマインド

とある理系大学生のブログです。基本は勉強とつぶやきとまとめです。

プロジェクトオイラー 問題23(project euler problem 23)

中間爆死...(´;ω;`)ウゥゥ


今回の問題↓
Problem 23 - PukiWiki

<考え方>
・過剰数をabundant_numの配列に入れていく。
・配列nonabundantの添え字で数値を表し、過剰数同士の和で表せる添え字の箱に1を入れて、最終的には箱に0が入っている添え字が過剰数の和で表せない数字になる。
・あとは足し合わせていくだけ。<ソースコード>

/*
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.
*/

#include <stdio.h>
#include <time.h>

int main(void){
  int abundant_num[28124] = {0};
  int nonabundant[28124] = {0};
  int count = 0; // 過剰数の個数をカウントする変数
  int sum = 0;
  clock_t start, end;

  start = clock();

  for (int i = 1; i < 28124; i++){ // 1~28123までの数が過剰数かどうかの判定。
    sum = 0;
    for (int j = 1; j <= i / 2; j++){ // 約数をsumに加えていく。
      if (i % j == 0) sum += j;
    }
    if(sum > i){ // 過剰数かどうかの判定
	  abundant_num[count] = i;
	  count++;
	}
  }

  sum = 0;

  for(int i = 0; i < count; i++) {
    for(int j = 0; j < count; j++) {
      if(abundant_num[i] + abundant_num[j] <= 28123)
      nonabundant[abundant_num[i] + abundant_num[j]] = 1;
    }
  }

  for (int i = 1; i < 28124; ++i) {
    if (nonabundant[i] == 0){ // 過剰数の和ではないならば
      sum += i;
    }
  }

  printf("%d\n",sum);

  end = clock();

  printf("経過時間%d[ms]\n", end - start);
}

<実行結果>

4179871
経過時間1276[ms]

これ以上速くできんかな...?
※先週分は中間テストに時間を優先したため、かけていません...時間が空いたら書きます...