2011/05/21

Project Euler をやり始めてみた

数日前に存在を初めて知ったProject Euler
Project Euler is a series of challenging mathematical/computer programming problems that will require more than just mathematical insights to solve. Although mathematics will help you arrive at elegant and efficient methods, the use of a computer and programming skills will be required to solve most problems.
About Project Euler - Project Euler
要は、プログラミングで解く数学パズル、みたいなもの。WEB上に用意された沢山の問題を一つづつ解いていく。ちなみに、他のユーザが書いたコードを見ることもできて、ちょっと勉強になったりもする。
全部で300以上ある問題のうち、まだ10問しかクリアしてないけど、解き方を思いついたり、うまく一発で答えを当てられたときの気持よさはなかなかのもの。少しでもプログラミングできる人は是非お試しを。

さて、プログラミングにはどんな言語を使ってもいいんだけど、僕は結局Javaを選択して少しずつ問題を消化していこうかと。ちょっとだけクラスの設計もしたので、使ってみたかったgithubにリポジトリ作ってみた(こちら)。この設計に基づくと、記念すべき1問目、Problem1を解くSolverはこんな感じになる。
package euler;

public class Solver001 implements Solver
{
  public String solve()
  {
    int sum = sum(3, 1000) + sum(5, 1000) - sum(15, 1000);
    return Integer.toString(sum);
  }

  public int sum(int base, int max)
  {
    int n = (max - 1) / base;
    return base * n * (n+1) / 2;
  }
}
ま、あまり設計とか考えずにmain関数ベタ書きでよかったかも -_-;

まずは25問クリアして"Level1"になるのが目標です。