マツケンのマインド

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

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

こんにちは!

Project EulerのProblem-6をC言語で解きました!

問題はこちら↓

odz.sakura.ne.jp

言われている通りに、プログラムを組めば簡単ですね!
アルゴリズム
・二乗和用と、和の二乗用の変数を用いる。
・1~100までforループで計算を進めていく。
・処理時間がかなり短いため、for文による冗長な処理時間の平均をとる。

ソースコード

/*
    The sum of the squares of the first ten natural numbers is 385

    The square of the sum of the first ten natural numbers is 3025

    Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 - 385 = 2640

    Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
*/
#include <stdio.h>
#include <time.h>
#define LOOP 10000

int main(void){
    int sum1 = 0, sum2 = 0;
    clock_t start, end;

    start = clock();

    for(int loop = 1; loop <= LOOP; loop++){

        sum1 = 0; // 二乗和用
        sum2 = 0; // 和の二乗用

        for(int i = 1; i < 101; i++){
            sum1 += i * i;
            sum2 += i;
        }

        sum2 *= sum2;

    }

    end = clock();

    printf("Ans = %d\n", sum2 - sum1);
    printf("経過時間%lf[sec]\n", (double)(end - start) / CLOCKS_PER_SEC / LOOP);
}

<実行結果>

Ans = 25164150
経過時間0.000002[sec]