LoginSignup
3
2

More than 5 years have passed since last update.

n! 階乗計算例(template練習)

Last updated at Posted at 2014-10-13

n!階乗計算例

template練習メモです.

factorial.cpp
// n! 階乗計算 =====================================
#include <iostream>
using namespace std;

/// ------------------------------------------
/// 階乗計算を行う
/// factorial<N>()関数テンプレート定義
/// ------------------------------------------
template<int N>
int factorial(){
  return factorial<N-1>() * N;
}

template<>  /// 特殊化:factorial<N=”1”>だったら,値を返す
int factorial<1>(){ 
  return 1;
}
/// ------------------------------------------

int main(){
  cout << factorial<1>()  << endl; /// Ans  1! = 1
  cout << factorial<3>()  << endl; ///      3! = 6
  cout << factorial<4>()  << endl; ///      4! = 24
  cout << factorial<10>() << endl; ///     10! = 3628800

}

実行結果

clang++ -std=c++11 factorial.cpp 
./a.out
1
6
24
3628800
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2