大数乘大数

下面代码是求阶层,调用:Mul("123456", "123")
#include <iostream>
using namespace std;

const int MAX = 100002;
char result[MAX];
char a[MAX], b[MAX];
char res[MAX]; //小数乘大数的结果
//大数相乘模版
int atoi(char c)
{
	return c - '0';
}

char atoc(int N)
{
	return N + '0';
}

bool signMul(char c[], int N)
{
	int len, i, ans, j;
	char t;
	len = strlen(c);
	ans = 0;
	if(len > MAX)
		return false; //乘数过大,不能被结果数组保存
	for(i = len - 1, j= 0; i >= 0; i--)
	{
		res[j++] = atoc((atoi(c[i]) * N + ans) % 10);
		ans = (atoi(c[i]) * N + ans) / 10;
	}
	if(ans > 0)
		res[j++] = atoc(ans);
	for(i = 0; i < j / 2;  i++)
	{
		t = res[i];
		res[i] = res[j - i - 1];
		res[j - i - 1] = t;
	}
	res[j] = '\0';
	return true;
}

//大数相加
void Add(char a[], char b[])
{
	int alen = strlen(a);
	int blen = strlen(b);
	int i, j, ans, k;
	char c;
	for(i = alen - 1, j = blen - 1, ans = 0, k = 0; i >= 0 && j >= 0; i--, j--)
	{
		result[k++] = atoc((atoi(a[i]) + atoi(b[j]) + ans) % 10);
		ans = (atoi(a[i]) + atoi(b[j]) + ans) / 10;
	}
	while(i >= 0)
	{
		result[k++] = atoc((atoi(a[i]) + ans) % 10);
		ans = (atoi(a[i]) + ans) / 10;
		i--;
	}
	while(j >= 0)
	{
		result[k++] = atoc((atoi(b[j]) + ans) % 10);
		ans = (atoi(b[j]) + ans) / 10;
		j--;
	}
	if(ans > 0)
		result[k++] = atoc(ans);
	for(i = 0; i < k / 2; i++)
	{
		c = result[i];
		result[i] = result[k - i - 1];
		result[k - i - 1] = c;
	}
	result[k] = '\0';
}
//乘的最终结果放在result数组中
bool Mul(char a[], char b[])
{
	int alen = strlen(a);
	int blen = strlen(b);
	int len, i, j, reslen;
	char temp[MAX];
	result[0] = '\0';
	for(i = blen - 1; i >= 0; i--)
	{
		signMul(a, atoi(b[i]));
		len = strlen(result);
		for(j = 0; j < len; j++)
		{
			temp[j] = result[j];
		}
		temp[len] = '\0';
		reslen = strlen(res);
		for(j = 0; j < blen - 1- i; j++)
		{
			res[reslen + j] = '0';
		}
		res[reslen + j] = '\0';
		Add(temp, res);
	}
	return true;
}
int main()
{
	int n, i, len, j;
	while(cin>>n)
	{
		result[0] = '1';
		result[1] = '\0';
		a[0] = '1';
		a[1] = '\0';
		if(n == 1 || n == 0)
		{
			cout<<'1'<<endl;
			continue;
		}
		for(i = 2; i <= n; i++)
		{
			sprintf(b, "%d", i);
			Mul(a, b);
			len = strlen(result);
			for(j = 0; j < len; j++)
				a[j] = result[j];
			a[len] = '\0';
		}
		printf("%s\n", result);
	}
	return 0;
}

你可能感兴趣的:(大数乘大数)