マツケンのマインド

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

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

こんにちは、マツケンです。
さあさあ、やっていきましょう!

今回の問題↓
Problem 30 - PukiWiki

<考え方>
・関数使って、計算は別のところでやってもらう。(見やすくしたい...)
・探索範囲の最小値は一桁の5乗は明らかにないので10。最大は9の5乗の5倍の270245まで見ればよい。
・ほかは特になし!<ソースコード>

/*Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:

 1634 = 1^4 + 6^4 + 3^4 + 4^4
 8208 = 8^4 + 2^4 + 0^4 + 8^4
 9474 = 9^4 + 4^4 + 7^4 + 4^4
 As 1 = 1^4 is not a sum it is not included.

 The sum of these numbers is 1634 + 8208 + 9474 = 19316.

 Find the sum of all the numbers that can be written as the sum of fifth powers of their digits.*/

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

int calculate(int num) {
	int sum = 0;

	while (num != 0) { // 各桁の5乗を足し合わせていく。
		sum += pow(num % 10, 5); 
		num /= 10;
	}
	return sum;
}

int main(void) {
    long long ans = 0; // どれぐらい大きくなるかわからないので...
    clock_t start, end;

    start = clock();
	
	for (int i = 10; i <= 270245; i++) // 探索範囲の減少 
		if (calculate(i) == i) ans += i; // calculate関数に値を渡して戻ってきた値と一致すればansに加えていく。
    
    printf("%lld\n", ans);

    end = clock();

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

	return 0;
}

<実行結果>

443839
経過時間:189[ms]

せいっ!(* ´艸`)