大数阶乘

描述
我们都知道如何计算一个数的阶乘,可是,如果这个数很大呢,我们该如何去计算它并输出它?
输入
输入一个整数m(0<m<=5000)
输出
输出m的阶乘,并在输出结束之后输入一个换行符
样例输入
50
样例输出

30414093201713378043612608166064768844377641568960512000000000000


// GreatNumFactorial.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<vector>
#include<deque>
#include<iostream>
using namespace std;


deque<int>re, t1, t2;
void GreatNumFactorial(int num);
void multi(int num);
void multiwithsinglenum(int num, deque<int>&temp);
void addwithshiftk(int k);
int _tmain(int argc, _TCHAR* argv[])
{
	
	GreatNumFactorial(17);
	deque<int>::iterator it;
	for (it = re.begin(); it != re.end(); it++)
		cout << *it;
	cout << endl;
	cout << re.size();
	system("pause");
	return 0;
}


void GreatNumFactorial(int num)
{
	int tt = num;
	re.push_back(tt % 10);
	tt = tt / 10;
	int kk = 1;
	while (tt > 0)
	{
		re.push_back(tt % 10);
		tt = tt / 10;
		++kk;
	}
	--num;
	while (num > 0)
	{
		multi(num);
		--num;
	}
}

void multi(int num)//乘以一个多位数字
{
	int a = num % 10;
	multiwithsinglenum(a, t1);
	int k = 0;
	num = num / 10;
	while (num > 0)
	{
		++k;
		a = num % 10;
		multiwithsinglenum(a, t2);
		addwithshiftk(k);
		num = num / 10;
	}
	re.clear();
	re = t1;
	t1.clear();
	
}

void multiwithsinglenum(int num, deque<int>&temp)//和一个个位数相乘
{
	int kk = 0;
	deque<int>::iterator it;
	for ( it = re.begin(); it != re.end(); it++)
	{
		
		int a = *it * num + kk;
		kk = a / 10;
		temp.push_back( a % 10);
	}
	if (kk)
		temp.push_back(kk);
}
void addwithshiftk(int k)
{
	int i = 0;
	int ff = 0;
	deque<int>::iterator it;
	for (int i = 0; i < k; i++)
		t2.push_front(0);
	int s1 = t1.size();
	int s2 = t2.size();
	for (int i = 0; i <s2-s1; i++)
		t1.push_back(0);
	for (i = 0; i < s2; i++)
	{
		t1[i] += t2[i] + ff;
		ff = t1[i ] / 10;
		t1[i] = t1[i ] % 10;
	}
	t2.clear();//清零以存储下一次的结果
}
17以前结果正确,从18开始结果错误,坐等大神指出问题

版权声明:

posted on 2015-07-05 09:18  moffis  阅读(174)  评论(0编辑  收藏  举报

导航