加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

大数乘法C实现

发布时间:2020-12-14 03:01:27 所属栏目:大数据 来源:网络整理
导读:pre name="code" class="plain" #includestdio.h#includestring.h#includemalloc.hconst int maxNumber=1004;//实现2个大数相乘//by WeiBiao 2014/9/27 12::40void mul(char* s1,char* s2);//遍历s2去乘每个s1整体,然后移位累加void subMul(int posVal,int
<pre name="code" class="plain">
#include<stdio.h>
#include<string.h>
#include<malloc.h>
const int maxNumber=1004;
//实现2个大数相乘
//by WeiBiao 2014/9/27 12::40
void mul(char* s1,char* s2);//遍历s2去乘每个s1整体,然后移位累加
void subMul(int posVal,int index1,char* s1,int* temp);//取出第二个数的个位、十位、百位etc依次乘第一个数个位,结果存入temp数组中。。。
void updateS1(int index1,int index2,int* t1,int* t2);//更新累加结果,一共需要更新strlen(s2)次
void outPut(int* s);//输出某个数组代表的数(大数)

int main(){
	char s1[maxNumber],s2[maxNumber];
	while(~scanf("%s%s",s1,s2)){
		mul(s1,s2);
	}
	return 0;
}

void outPut(int* s){
	int i;
	for( i = maxNumber-1; i>=0; i--) if(s[i]) break;
	for( int j = i; j >=0; j--)
		printf("%d",s[j]);
	puts("");
}

void updateS1(int index1,//index1,到index2开始加
				int* t1,int* t2){//与s1对齐,相加
	int incre=0;
	for(int i = index1; i<= index2; i++){
		if((incre+t1[i]+t2[i]) >= 10){ 
			int tp;
			tp=(incre+t1[i]+t2[i])/10;
			t1[i] = (incre+t1[i]+t2[i])%10;
			incre = tp;
		}
		else{
			t1[i] = (t1[i]+t2[i]+incre);
			incre = 0;
		}
	}

	//outPut(t1);
}

void subMul(int posVal,int* temp){//得到temp
	int j,incre;
	for(j = 0,incre=0; j < strlen(s1); ++j){//遍历s1
		if( (incre+ posVal*(s1[j]-'0')) >= 10){
			temp[index1+j] = (incre+ posVal*(s1[j]-'0'))%10;
			incre = (incre+ posVal*(s1[j]-'0'))/10;
		}else{
			temp[index1+j] = posVal*(s1[j]-'0');
			incre = 0;
		}
	}
	temp[index1 + j] = incre;
	//outPut(temp);
}

void mul(char* s1,char* s2){
	s1 = strrev(s1); s2 = strrev(s2);
	int a[maxNumber]={0},a1 = strlen(s1),a2 = strlen(s2);

	int temp[1010];//申请temp数组存放每一步结果

	for(int i = 0; i < a2; ++i){//执行a2次结束
		memset(temp,NULL,sizeof(temp));
		int posVal = s2[i]-'0'; 

		subMul( posVal,i,temp);//局部乘法,更新temp数组;
		updateS1( i,a1+i+1,a,temp);//更新累加结果
	}
	outPut(a);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读