转载自:http://blog.sina.com.cn/s/blog_4baa2c250100ijpn.html
1000的阶乘是一个非常之大的数字,在看到这个问题的第一个反应就是,直接运算肯定会溢出,事实也如此,我们如何解决这个问题呢?
我们小学的时候就会计算这样的乘法:123*9
三九二十七进二写七
二九十八
一九得九
最后的结果是1107
如何计算阶乘结果的位数?
方法一:
log1+log2+log3+log4+...+logn 取整加1
方法二:
斯特林公式
按照这样的步骤,把每次得到的结果存放到数组里,考虑到无法确定数组长度,采用ArrayList
实现如下:
- public
static void factorial(int value) { -
ArrayList result = new ArrayList(); -
int carryBit = 0; -
-
result.add(new Integer(1)); -
for (int out = 2; out <= value; out++) { -
for (int in = 0; in < result.size(); in++) { -
int temp = ((Integer) result.get(in)).intValue() * out -
+ carryBit; -
result.set(in, new Integer(temp % 10)); -
carryBit = temp / 10; -
} -
while (carryBit != 0) { -
result.add(new Integer(carryBit % 10)); -
carryBit = carryBit / 10; -
} -
} -
StringBuffer sb=new StringBuffer(result.size()); -
for(int i=0;i<result.size();i++) -
{ -
sb.append(result.get(i)); -
} -
sb=sb.reverse(); -
System.out.println("result="+sb); -
System.out.println("结果位数"+result.size()); -
}
C语言版:(自己写的)
#include<iostream>
using namespace std;
void factorial(int value);
void main()
{
}
void factorial(int value)
{
C#:自己写的:
public static void Factorial(int value)
{
int[] result = new int[10000];
int result_size = 1;//实时更新result的实际位数
int carryBit = 0; //进位的值
result[0] = 1;//初始结果为1
for (int i = 2; i <= value; i++) {
for (int j = 0; j < result_size; j++) {
int temp = result[j] * i
+carryBit;
result[j] = temp % 10;
carryBit = temp / 10;
}
while (carryBit != 0)
{
result[result_size] = carryBit % 10;
result_size++;
carryBit = carryBit / 10;
}
}
Console.WriteLine("{0}的阶乘结果:", value);
for (int i = 0; i < result.Length; i++)
{
Console.Write(result[i]);
}
}