recursive algorithm

The common recursive algorithm is the factorial, such as finding 5! , the overflow problem needs special attention here. The algorithm is implemented as follows:

#include <iostream>
using namespace std;

#define U64 unsigned long long
#define U16 unsigned short

U64 factorial(U64 n)
{ 
    if(1 == n)
      return 1;
    else
    {
      return n*factorial(n-1);     
    } 
}


int main()
{
  U64 result=0;
  U64 n=0;
  cout<<"***** 递归算法 *****"<<endl;
  cout<<" 请输入待求的阶乘数:";
  cin>>n;

  if(n>64)
  {
    cout<<"请输入小于64的数"<<endl;
    return -1;
  }

  result = factorial(n);  

  cout<<endl;
  cout<<"计算结果:" <<endl;
  cout<<n<<"的阶乘为:"<<result<<endl;    


  return 0;
}


Juyin @ 2018/4/25

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324886707&siteId=291194637