大整数乘法

大整数乘法

#define _CRT_SECURE_NO_WARNINGS  1

#include <stdlib.h>
#include <cstring>
#include <stdio.h>
#include <iostream>
using namespace std;
char sa[1000];
char sb[1000];

typedef struct _Node
{
	int s[100];
	int l;
	int c;
} Node,*pNode;

void cp(pNode src, pNode des, int st, int l) //src待分解的节点,des分解后得到的节点
{
	int i, j;
	for (i = st, j = 0; i < st + 1; i++, j++)
	{
		des->s[j] = src->s[i];
	}
	des->l = l;
	des->c = st + src->c;
}
void add(pNode pa, pNode pb, pNode ans)
{
	int i, cc, k, palen, pblen, len;
	int ta, tb;
	pNode temp;
	if ((pa->c < pb->c))
	{
		temp = pa;
		pa = pb; 
		pb = temp;
	}
	ans->c = pb->c;
	cc = 0;
	palen = pa->l+ pa->c;
	pblen = pb->l + pb->c;
	if (palen > pblen)
		len = palen;
	else
		len = pblen;
	k = pa->c - pb->c;
	for (i = 0; i < len - ans->c; i++)
	{
		if (i < k)
			ta = 0;
		else
			ta = pa->s[i - k];
		if (i < pb->l)
			tb = pb->s[i];
		else
			tb = 0;
		if (i >= pa->l + k)
			ta = 0;
		ans->s[i] = (ta + tb + cc) % 10;
		cc = (ta + tb + cc) / 10;
	}
	if (cc)
		ans->s[i++] = cc;
	ans->l = i;
}
void  mul(pNode pa, pNode pb, pNode ans)
{
	int i, cc, w;
	int ma = pa->l >> 1, mb = pb->l>> 1;
	Node ah, al, bh, bl;
	Node t1, t2, t3, t4, z;
	pNode temp;
	if (!ma || !mb)
	{
		if (!ma)
		{
			temp = pa;
			pa = pb;
			pb = temp;
		}
		ans->c = pa->c + pb->c;
		w = pb->s[0];
		cc = 0;
		for (i = 0; i < pa->l;++i )
		{
			ans->s[i] = (w * pa->0 s[i] + cc) %10;
			cc = (w * pa->s[i] + cc) / 10;
		}
		if (cc)
			ans->s[i++] = cc;
		ans->l = i;
		return;
	}

	//分治核心
	cp(pa, &ah, ma, pa->l - ma);
	cp(pa, &al, 0, ma);
	cp(pb, &bh, mb, pb->l - mb);
	cp(pb, &bl, 0, mb);

	mul(&ah, &bh, &t1);
	mul(&ah, &bl, &t2);
	mul(&al, &bh, &t3);
	mul(&al, &bl, &t4);

	add(&t3, &t4, ans);
	add(&t2, ans, &z);
	add(&t1, &z, ans);
}

int main()
{
	Node ans , a, b;
	cout << "输入大整数a: " << endl;
	cin >> sa;
	cout << "输入大整数b: " << endl;
	cin >> sb;
	/*printf("输入最大整数a:\n");
	scanf("%d", &sa);
	printf("输入最大整数b:\n");
	scanf("%d", &sb);*/

	a.l = strlen(sa);
	b.l = strlen(sb);

	int z = 0,i;

	for (i = a.l - 1; i >= 0; i--)
	{
		a.s[z++] = sa[i] - '0';
	
	}
	a.c = 0;
	z = 0;
	for (i = b.l - 1; i >= 0; i--)
	{
		b.s[z++] = sb[i] - '0';
	}
	b.c = 0;
	mul(&a, &b, &ans);
	printf("输出的结果为: ");
	for (i = ans.l - 1; i >= 0; i--)
		printf("%d", ans.s[i]);
	printf("\n");
	return 0;

}

后续

本代码来源于趣学算法,分治问题,代码我检查了无数遍了,用得上vs2021,没调通,有没有大佬帮忙看看哪里有问题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值