大整数乘法

题目地址:http://acm.cs.ecnu.edu.cn/problem.php?problemid=1070

代码是按一般思路写的

#include<stdio.h>
#include<string.h>
#define max 504
#define max2 1010
int aa[max];
int bb[max];
int c[max2];
int lenaa;
int lenbb;
int main()
{
	void init();
	void jinwei();
	void mul();
	void print();
	void change(char *a,char *b);
	char a[max];
	char b[max];
	int i,n;
	scanf("%d",&n);
	while(n--)
	{
		scanf("%s%s",a,b);
		if(strlen(a)>=strlen(b))    //若a的长度比b长,那么aa中放a,反之,放b
		{
			change(a,b);
		}
		else
		{
			change(b,a);
		}
		init();
		mul();
		jinwei();
        print();
	}
	return 0;
}

void change(char *a,char *b)             //将char转换为int
{                                       //a的位数比b的大,aa中放的是位数比较大那个数据
	int i;
	lenaa=strlen(a);
	lenbb=strlen(b);
	for(i=0;i<strlen(a);i++)
	{
		aa[i]=a[i]-'0';
	}
	for(i=0;i<strlen(b);i++)
	{
		bb[i]=b[i]-'0';
	}
}

void mul()  //做乘法,a[i]与b[j]相乘的积放在c[lenaa+lenbb-2-i-j]里面
{               //c[0]表示的是低位
	int i,j;
	for(j=lenbb-1;j>=0;j--)
	{
		for(i=lenaa-1;i>=0;i--)
		{
			c[lenaa+lenbb-2-i-j]=aa[i]*bb[j]+c[lenaa+lenbb-2-i-j];
		}
	}
}

void jinwei()
{
	int i;
	int t=0;     //记录进位
	for(i=0;i<=lenaa+lenbb-2;i++)
	{
		c[i]=c[i]+t;
		if(c[i]>=10)
		{
			t=c[i]/10;
			c[i]=c[i]%10;
		}
		else
		{
			t=0;
		}
	}
	c[i]=t;
}

void init()  //对c[]初始化
{
	int i;
	for(i=0;i<=lenaa+lenbb;i++)
	{
		c[i]=0;
	}
}

void print()      //打印
{
	int i;
	i=lenaa+lenbb-1;         
	while(c[i]==0&&i>=0)    //把前面的0去掉,但若乘机是0的话,则全部去掉,此时i=-1
		i--;                //前面很多0的情况只有当乘机是0才会出现
	if(i==-1)         
	{
		printf("0\n");
		return ;
	}
	while(i>=0) 
	{
		printf("%d",c[i]);
		i--;
	}
	printf("\n");
}


分治法如何做??

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值