【學習筆記】hdu1042(高精度乘法)

原題鏈接:http://acm.hdu.edu.cn/showproblem.php?pid=1049

代碼:

#include <cstdio> 
#include <cstring>
#include <malloc.h> 
#include <iostream>

using namespace std;

void intToArray(int num, char* a)
{
	int i = 0, len;
	int t;
	while (num)
	{
		a[i++] = num % 10 + '0';
		num /= 10;
	}
	len = i;
	for (i = 0; i < len / 2; i++) 
	{
		t = a[i];
		a[i] = a[len - i - 1];
		a[len - i - 1] = t;
	}
	a[len] = 0;
}
  
void multiply(char* a, char* b, char* c) 
{      
	int i, j, ca, cb, * s;
	ca = strlen(a);     
	cb = strlen(b);      
	s = (int*)malloc(sizeof(int)*(ca+cb));     
	for (i = 0; i < ca + cb; i++)      
	s[i] = 0;      
	for (i = 0; i < ca; i++)      
		for (j = 0; j < cb; j++) s[i+j+1] += (a[i]-'0')*(b[j]-'0');     
	for (i = ca+cb-1; i >= 0; i--)      
		if (s[i] >= 10)      
		{          
			s[i-1] += s[i] / 10;          
			s[i] %= 10;         
		}     
	i = 0;      
	while (s[i]==0)      
		i++;      
	for (j = 0; i < ca + cb; i++, j++)      
		c[j] = s[i] + '0';     
	c[j] = '\0';     
	free(s); 
}

int main()
{
	int n, i;
	char ans[40000],b[10];
	while(~scanf("%d",&n))
	{
		ans[0] = '1'; ans[1] = 0;
		for (i = 1; i <= n; i++)
		{
			intToArray(i,b);
			multiply(ans,b,ans);
		}
		cout << ans << endl;
	}
	return 0;
} 

其中multiply函數是個很有用的高精度乘法.
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章