マツケンのマインド

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

プロジェクトオイラー 問題12

こんにちは、マツケンです。
今日は問題12を扱っていくのですが、良いアルゴリズムがなかったので、計算量がえげつないことになっています...
1秒未満に抑えたい気持ちはあったのですが...
なので、「こんな解法あるよ!」などありましたら教えていただけると幸いです!
初の黒歴史?コードの投稿になります(´;ω;`)

今回の問題↓
Problem 12 - PukiWiki

<考え方>
・1づつ足していき、三角数を表していく。
三角数が求まるたびに、その値まで1から地道に割り切れるかの検証。
・countが500以上になれば終了。ならなければcountを0に戻し、また足し合わせていく。<ソースコード>

/*
    The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:

    1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...

    Let us list the factors of the first seven triangle numbers:

    1: 1
    3: 1,3
    6: 1,2,3,6
    10: 1,2,5,10
    15: 1,3,5,15
    21: 1,3,7,21
    28: 1,2,4,7,14,28
    We can see that 28 is the first triangle number to have over five divisors.

    What is the value of the first triangle number to have over five hundred divisors?
*/
#include <stdio.h>
#include <time.h>

int main(void){
    int ans = 0;
    int count = 0;
    clock_t start, end;

    start = clock();

    while(count < 500){
        for(int i = 1;; i++){
            ans += i;
            for(int j = 1; j <= ans; j++)
                if(ans % j == 0)
                    count++;
            if(count < 500)
                count = 0;
            else
                break;
        }
    }
    end = clock();
    printf("Ans = %d\n", ans);
    printf("経過時間 = %d[ms]\n", end - start);
    return 0;
}

<実行結果>

Ans = 76576500
経過時間 = 1042919[ms]

うぉぉぉぉぉぉぉぉぉぉぉぉ(´;ω;`)