大数阶乘的AS3与C++版本

最近在面试flash的时候,出了道题目:用程序求1000的阶乘。

说出这个问题的时候,有两种情况,一种会问:“阶乘是什么?”,另外一种可能会想,这个结果会走出Number型能表述的上限。

 

之前业余的时候写了两个版本:AS3、C++,C++是大二学过后再没碰过了,写的时候查了资料

AS3版本的大数阶乘:

package
{
import flash.display.Sprite;

public class AlgorithmDemo extends Sprite
{
public function AlgorithmDemo()
{
initView();
}

private function initView():void
{

var num:uint = 5;

var val:String = factorial(num);

trace(num + "! = " + val);

}

private function factorial(n:int):String
{
var a:Array = [1];


for (var i:int = 1; i <=n; i++)
{
for (var j:int = 0, c:int = 0; j < a.length || c != 0; j++)
{
var m:int = (j < a.length) ? (a[j] * i + c) : c;
a[j] = m % 10;
c = m / 10;
}
}

return a.reverse().join("");
}
}
}

C++版本的:

#include <iostream>
#include <vector>
#include <algorithm>
#include <sstream>

using namespace std;

int main() {
vector<int> myVector;
vector<int>::iterator it;

stringstream ss;
string str;

int n;

cout<<"请输入您需要计算的阶乘值(1~1000):";
cin>>n;

if(n <= 0 || n > 1000) {
cout<<"输入的值不符合要求。\n";
system("pause");
return 0;
}



myVector.push_back(1);

for (int i = 1; i <= n; i++) {
for (int j = 0, c = 0; j < myVector.size() || c != 0; j++) {
int m = (j < myVector.size()) ? (myVector[j] * i + c) : c;
int p = m % 10;

if (j < myVector.size()) {
myVector[j] = p;
}
else {
myVector.push_back(p);
}

c = m / 10;
}
}

reverse(myVector.begin(), myVector.end());

for (it = myVector.begin(); it != myVector.end(); ++it) {
ss<<*it;
}

str = ss.str();


cout<<n<<"的阶乘结果为:"<<str<<"\n";

system("pause");
return 0;
}

运行的结果:
image

 

这里有一个JavaScript版本的大数阶乘

posted @ 2012-03-07 19:58  meteoric_cry  阅读(717)  评论(0编辑  收藏  举报