問題:
ある検索サイトに5!と入力するとその計算結果である120が表示されます。
その検索サイトに2.5!と入力するとなんと3.32335097と表示されます。
さらにその検索サイトに(-1.9)!と入力すると-10.5705641と表示されます。
きっとそれらの仕組みはとても難しくて企業秘密に違いないので是非ともこれらを実行するプログラムを作ってほしい。
ただし、君のPCは古いのでネットワークや便利で高度な数学関数は入っていません。
入っている数学関数はsin,cos,tan,log,pow,floorなどの初歩的な関数のみです、残念ながら。
i)入力された整数a(0<=a<=10)の階乗を求めるプログラムを作ってください。 ii)入力された実数a(0<=a<=10)の階乗を求めるプログラムを作ってください。 iii)入力された実数a(-1.9<=a<=-1.1)の階乗を求めるプログラムを作ってください。 回答(C++プログラムコード):
#include
#include
#include
#include
#include
using namespace std;
// define the constants
static const int g=7;
static const double pi =3.1415926535897932384626433832795028841972 ;
static const double p[g+2] = {0.99999999999980993, 676.5203681218851,
-1259.1392167224028, 771.32342877765313, -176.61502916214059,
12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6,
1.5056327351493116e-7};
// define the Lanczos_approximation of gamma function
complex gamma( complex z)
{
if ( real(z)<0.5 )
{
return pi / (sin(pi*z)*gamma(1.0-z));
}
z -= 1.0;
complex x=p[0];
for (int i=1; i(i,0));
}
complex t = z + (g + 0.5);
return sqrt(2*pi) * pow(t,z+0.5) * exp(-t) * x;
}
int main()
{
double r,i;
cout<<"Please input the real part of the complex number:"<>r;
cout<<"Please input the imaginary number of the complex number:"<>i;
cout << "The factorial of "<(r,i)<<" is "<(r+1,i)) << endl;
system("PAUSE");
return 0;
}
プログラムコード:LifeClock.cpp
URL: https://leybreeze.com/blog/wp-content/uploads/2012/02/RealNumberFactorial.cpp
回答できた問題の出力:
入力によって違います。
アルゴリズムの簡単な説明:
実数の階乗と言うと、ガンマ関数のことです。
使用可能な数学関数はsin,cos,tan,log,pow,floorなどの初歩的な関数のみですから、Lanczos approximationというの近似法は使えます。
(ご参考まで:http://en.wikipedia.org/wiki/Lanczos_approximation )
実行方法:RealNumberFactorial.exe (msvcp100d.dllは必要です。)実行して実数の実部と虚部を入力してください
URL: https://leybreeze.com/blog/wp-content/uploads/2012/02/RealNumberFactorial.exe
実行環境:Windows XP/Vista/7
ライセンス:GPLv3