5.6大整数运算2

a+b完整代码

#include <cstdio>
#include <cstring> 
 
struct bign{			//结构体 
	
	int d[10000];
	int len;
	bign(){
		memset(d,0,sizeof(d));
		len =0;
	}
}; 

bign change(char str[]){	//把整数化成bign 
	bign a;
	a.len = strlen(str);
	for(int i=0; i<a.len; i++){
		a.d[i] = str[a.len-i-1]-'0';
	}
	
	return a;
}

	bign add(bign a,bign b){	//加法 
		
		bign c;
		int carry = 0;
		for(int i=0; i<a.len || i<b.len ; i++){
			int temp  = a.d[i] + b.d[i] + carry;
			c.d[c.len++] = temp %10;
			carry = temp /10 ;
		}
		
		if(carry !=0 ){
			c.d[c.len++] = carry; 
		} 			
		return c;
	} 

void prin(bign a){			//打印 
	
	for(int i=a.len-1; i>=0 ; i--){
		
		printf("%d",a.d[i])	;
		
	}
	printf("\n"); 
}

bool cmp(bign a, bign b){			//比较大小 
	if(a.len>b.len) return 1;
	else if(a.len <b.len) return -1;
	else {
		for(int i=a.len-1; i>=0 ;i--){
			if(a.d[i] >b.d[i]) return 1;
			else if(a.d[i] <b.d[i]) return -1;
		} 
		return 0; //相等 
	} 
}
 
int main(){

	char str1[1000] , str2[1000]; 
	while(scanf("%s%s",str1,str2) != EOF ){
		bign a = change(str1);	
		bign b = change(str2);
		prin(add(a,b));
	
	} 

	return 0;
}

习题,求N的阶乘(N<=1000)

用简单的int存储不了,应用高精度乘法乘低精度方法做

#include <cstdio>
#include <cstring>
//求N的阶乘(n<=1000)

struct bign{		//建一个结构体 
	int d[100000];		//若只有10000,则会显示答案错误 
	int len;
	
	bign(){
		memset(d,0,sizeof(d));
		len =0;
	}		
};

bign changeInt(int n){		//将int型化成大整数,用数组存
	bign a;
	while(n !=0){
		a.d[a.len++] = n%10;
		n = n/10;
	}
	return a;
}

bign multi(bign a, int b){

	bign  c;
	int carry =0;
	for(int i=0; i<a.len; i++){
		
		int temp = a.d[i] * b +carry;
		c.d[c.len++] = temp %10;
		carry = temp /10;
	}
	while(carry != 0 ) {
		c.d[c.len++] = carry % 10;
		carry = carry /10;
	}
	
	return c;
}



void prin(bign a){
	for(int i = a.len-1 ; i>=0 ;i --){
		printf("%d" , a.d[i]); 
	} 
	printf("\n");
}


int main(){

	int n;
	while(scanf("%d" , &n) != EOF ){		
		bign x = changeInt(n);
		if( n == 0) 	
			printf("1\n");
		else{
			for(int i=1; i<n; i++)
				x = multi(x,i);
			prin(x);
		}				
	}
	return 0;
}
    原文作者:大整数乘法问题
    原文地址: https://blog.csdn.net/qq_38300076/article/details/88579172
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞