C言語入門 -自然数の階乗を計算するサンプルコード

サンプルコード

#include <iostream>
using namespace std;

const int N = 40000;

void FactCal(int n)
{
int result[N];
int height;

result[0] = 1;
height = 1;
//計算
for(int i=1;i<=n;i++)
{
int res = 0;
for(int j=0;j<height;j++)
{
int buf = result[j]*i + res;
result[j] = buf%10;
res = buf/10;
}
while(res)
{
result[height++] = res%10;
res /= 10;
}
}
//出力
for(int i=height-1;i>=0;i–)
cout<<result[i];
cout<<endl<<" 長さ:"<<height<<endl;
}

int main()
{
int n;
cout<<“Input a number:";
cin>>n;
if(n>10000 || n<0)
cout<<“自然数を入力してください";
else
FactCal(n);
return 0;
}

C++

Posted by arkgame