天天看點

【基礎】高精度乘法

描述 Description

高精度乘法

輸入:兩行,每行表示一個非負整數(不超過10000位)

輸出:兩數的乘積。

樣例輸入 Sample Input

99

101

樣例輸出 Sample Output
9999
時間限制 Time Limitation
各個測試點1s

我又菜了,交了兩次才過。都是不做資料的錯。

是因為讀入資料壓位寫錯了,對于bit的整倍數長度的數,要先把長度+1,因為會跳過一開始的零頭位處理。

#include <cstdio>
#include <string>
#include <cstring>

typedef long long ll;

const long bit = 8;
const ll bit10 = 100000000;

void pocess(char* x,ll* y)
{
	long l = 0;
	while (x[++l]);l--;
	y[0] = l/bit+1;

	long rr = l%bit;
	for (long i=1;i<rr+1;i++)
	{
		y[y[0]] = (y[y[0]]<<3)+(y[y[0]]<<1)+x[1]-'0';
		x++; l--;
	}

	rr = y[0];
	for (long i=1;i<l+1;i++)
	{
		if (!((i-1) % bit)) rr --;
		y[rr] = (y[rr]<<3)+(y[rr]<<1)+x[1]-'0';
		x++;
	}
}

void multiply(ll* a,ll* b,ll* c)
{
	c[0] = a[0] + b[0];
	for (long i=1;i<a[0]+1;i++)
	{
		for (long j=1;j<b[0]+1;j++)
		{
			c[i+j-1] += a[i]*b[j];
			while (c[i+j-1] >= bit10)
			{
				c[i+j] += c[i+j-1]/bit10;
				c[i+j-1] %= bit10;
			}
		}
	}
	while (!c[c[0]])c[0]--;
}

void output(ll* a)
{
	printf("%ld",long(a[a[0]]));
	for (long i=a[0]-1;i>0;i--)
	{
		printf("%08ld",long(a[i]));
	}
}

char aa[10010];
char bb[10010];
ll a[10010];
ll b[10010];
ll c[20010];

int main()
{
	freopen("multiply.in","r",stdin);
	freopen("multiply.out","w",stdout);

	scanf("%s",aa+1);
	scanf("%s",bb+1);

	pocess(aa,a);
	pocess(bb,b);

	multiply(a,b,c);

	output(c);

	return 0;
}