// calculate large factorials (factorials above 12!)
// note that 13! already exceeds unsigned long
// a Dev-C++ tested console program by vegaseat 26mar2005
#include
#include
using namespace std;
int main()
{
unsigned int nd, nz; // number of digits
unsigned char *ca; // char array to hold result
unsigned int j, n, q, temp;
int i;
double p;
while(1)
{
cout
cin >> n;
if (n == 0) break;
//calculate nd = the number of digits required
p = 0.0;
// p is really log10(n!)
for(j = 2; j
{
p += log10((double)j); // cast to double
}
nd = (int)p + 1;
// allocate memory for the char array
//ca = new unsigned char[nd];
ca = (unsigned char*)malloc(sizeof(unsigned char)*(nd+1));
if (!ca)
{
cout
exit(0);
}
//initialize char array
for (i = 1; i
{
ca[i] = 0;
}
ca[0] = 1;
// put the result into a numeric string using the array of characters
p = 0.0;
for (j = 2; j
{
p += log10((double)j); // cast to double!!!
nz = (int)p + 1; // number of digits to put into ca[]
q = 0; // initialize remainder to be 0
for (i = 0; i
{
temp = (ca[i] * j) + q;
q = (temp / 10);
ca[i] = (char)(temp % 10);
}
}
cout
// the factorial is stored in reverse, spell it from the back
for( i = nd - 1; i >= 0; i--)
{
cout
}
cout
// free up allocated memory
free(ca);
} // while
return 0;
}
算100!的C++程序
所有跟帖:
•
well done!
-吴用先生-
♂
(0 bytes)
()
02/10/2009 postreply
23:02:32
•
回复:well done!
-怪哉-
♂
(193 bytes)
()
02/10/2009 postreply
23:07:33
•
该程序还需加强一些输入值检测,
-吴用先生-
♂
(64 bytes)
()
02/10/2009 postreply
23:14:25
•
是啊,原程序STRING位数都没算对
-怪哉-
♂
(70 bytes)
()
02/10/2009 postreply
23:17:48
•
justjust兄是指时空复杂度吧?怪哉兄一定有所准备的。
-吴用先生-
♂
(0 bytes)
()
02/10/2009 postreply
23:24:21
•
呵,知己知彼了已经。
-吴用先生-
♂
(0 bytes)
()
02/10/2009 postreply
23:22:45
•
强!俺好像头一回看见有人帖原代码在这。
-吴用先生-
♂
(0 bytes)
()
02/10/2009 postreply
23:03:56
•
老土别删,我留着明天看用得上不
-怪哉-
♂
(0 bytes)
()
02/10/2009 postreply
23:08:38
•
为甚要删? 明天肯定用得上! 3q!
-美国老土-
♂
(0 bytes)
()
02/10/2009 postreply
23:18:21
•
Good luck for your interview. Amazon is an interesting
-ffppyy-
♂
(207 bytes)
()
02/10/2009 postreply
23:46:16
•
乱码,看不懂
-魔法彩虹-
♀
(0 bytes)
()
02/11/2009 postreply
00:39:21
•
回复:乱码,看不懂
-吴用先生-
♂
(73 bytes)
()
02/11/2009 postreply
01:25:16
•
都是俺的偶像 :)
-魔法彩虹-
♀
(0 bytes)
()
02/11/2009 postreply
07:23:31