プログラムで解く数学の問題 -Project Eulerをやってみた-
最近学び始め,今後使う予定があるpythonの練習のために,以前に存在を知って気になっていた「Project Euler」に登録してみました.
Project Eulerとは
Project Eulerは,プログラムで解く数学的な問題が掲載されているサイトです.
全て英語で書かれていますが,日本語に翻訳しているwikiも存在しています.
Project Euler - PukiWiki
実際に,アカウント登録をしてから問題を解く手順などは,こちらで詳しく解説されています.
実際に問題を2問だけ解いてみました.
問題1
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
Problem 1 - Project Euler
日本語訳
10未満の自然数のうち, 3 もしくは 5 の倍数になっているものは 3, 5, 6, 9 の4つがあり, これらの合計は 23 になる.
同じようにして, 1000 未満の 3 か 5 の倍数になっている数字の合計を求めよ. Problem 1 - PukiWiki
解くために書いたソースコード
i = 0 total = 0 for i in range(1000): if i % 3 == 0 or i % 5 == 0 : total += i print(total)
実行結果
233168
問題2
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
日本語訳
フィボナッチ数列の項は前の2つの項の和である. 最初の2項を 1, 2 とすれば, 最初の10項は以下の通りである.
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... 数列の項の値が400万以下の, 偶数値の項の総和を求めよ.
Note:この問題は最近更新されました. お使いのパラメータが正しいかどうか確認してください.
Problem 2 - PukiWiki
解くために書いたソースコード
f = 0 pre = [1,2] total = 2 while f < 4000001: f = pre[0] + pre[1] pre[0] = pre[1] pre[1] = f if f % 2 == 0 : total += f print(total)
実行結果
4613732
最初の問題だけあって,私でもなんとか解けるような簡単な問題ですが,問題が進んでいくにつれてどんどん難しい問題も出てくるようです.
問題を解くことで力が身につきそうなので,時間を見つけて出来るだけやっていきたいと思います.