大数运算(自己练习)

今天遇见大数问题,不想以后再求模板了,想自己写一个能用的

可能里面有些错误,后续会在使用过程当中慢慢改正

#include<stdio.h>
#include<string.h>
#define MAX 500

typedef struct A{
	int num[MAX];
	int len;
	A(){
		memset(num, 0, sizeof(num));
		len = 0;
	}
	A(int a){
		memset(num, 0, sizeof(num));
		len = 0;
		while(a){
			num[len++] = a % 10;
			a /= 10;
		}
	}
	A(char kk[]){
		int i, j, k;
		memset(num, 0, sizeof(num));
		len = 0;
		for(i = strlen(kk) - 1; i >= 0; i--){
			num[len++] = kk[i] - '0';
		}
	}
}Big_int;

Big_int add(Big_int a, Big_int b){
	Big_int ret = Big_int();
	int rem = 0;
	int i, j, k;
	for(i = 0; i < MAX; i++){
		if(!rem && !a.num[i] && !b.num[i]){
			ret.len = i;
			break;
		}
		ret.num[i] = (rem + a.num[i] + b.num[i]) % 10;
		rem = (rem + a.num[i] + b.num[i]) / 10;
	}
	return ret;
}

Big_int subtract(Big_int a, Big_int b){
	Big_int ret = Big_int();
	int i, j, k;
	for(i = 0; i < MAX; i++){
		if(!a.num[i] && !b.num[i]){
			ret.len = i;
			break; 
		}
		if(a.num[i] < b.num[i]){
			int tem = i + 1;
			while(!a.num[tem]){
				a.num[tem] = 9;
				tem++;
			}
			a.num[tem]--;
			ret.num[i] = 10 + a.num[i] - b.num[i];
		}
		else{
			ret.num[i] = a.num[i] - b.num[i];
		}
	}
	return ret;
}

Big_int multiply(Big_int a, Big_int b){
	Big_int ret = Big_int();
	int i, j, k;
	for(i = 0; i < a.len; i++){
		for(j = 0; j < b.len; j++){
			ret.num[i + j] += a.num[i] * b.num[j];
		}
	}
	int rem = 0;
	for(i = 0; i < MAX; i++){
		int tem = rem + ret.num[i];
		ret.num[i] = tem % 10;
		rem = tem / 10;
	}
	for(i = MAX - 1; ; i--){
		if(ret.num[i] != 0){
			ret.len = i + 1;
			break;
		}
	}
	return ret;
}

Big_int divide(Big_int a, int b){
	Big_int ret;
	int i, j, k;
	int rem = 0;
	for(i = a.len - 1; i >= 0; i--){
		ret.num[i] = (rem * 10 + a.num[i]) / b;
		rem = (rem * 10 + a.num[i]) % b;
	}
	for(i = MAX - 1; ; i--){
		if(ret.num[i] != 0){
			ret.len = i + 1;
			break;
		}
	}
	return ret;
}

int mod(Big_int a, int b){
	int i, j, k, ret = 0;
	for(i = a.len - 1; i >= 0; i--){
		ret = (a.num[i] % b + ((ret % b) * (10 % b)) % b) % b;	
	}
	return ret;
}

Big_int power(Big_int a, int b){
	Big_int ret = Big_int(1);
	int i, j, k;
	Big_int tem = Big_int(1);
	tem = multiply(tem, a);
	while(b){
		if(b & 1){
			ret = multiply(ret, tem);
		}
		b >>= 1;
		tem = multiply(tem, tem);
	}
	for(i = MAX - 1; ; i--){
		if(ret.num[i] != 0){
			ret.len = i + 1;
			break;
		}
	}
	return ret;
}

void display(Big_int a){
	int i, j, k;
	if(a.len == 0){
		printf("0");
	}
	else{
		for(i = a.len - 1; i >= 0; i--){
			printf("%d", a.num[i]);
		}	
	}	
	printf("\n");
}


 

你可能感兴趣的:(大数运算(自己练习))