http://d.hatena.ne.jp/satosystems/20121228/1356655565
#include <iostream> constexpr int fib(int n) { return n < 2 ? n : fib(n - 2) + fib(n - 1); } int main(int argc, char *argv[]) { const int f = fib(38); std::cout << f << std::endl; return 0; }
$ g++ --version g++ (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3 Copyright (C) 2011 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. $ g++ -O3 -g -std=c++0x -Wall fib.cpp -o fib_cpp
これならC++でもコンパイル時に計算してくれるのでとても速い。いったんconst int変数に代入しなきゃいけないのが不自然だけど、こう書かないとg++ではうまくいかなかった。
ただ、こういうズルをしないバージョンでも手元だとJavaよりC/C++バージョンの方が速いんだよね……