High precision calculation

Time:2021-4-14

The simulation column vertical method is used for high precision calculation.
Generally, positive numbers are used for calculation, and sign bits are used for negative numbers.

1. High precision data storage

basic thought
High precision integers are stored and represented by arrays. An array element that holds one bit of a high-precision integer.
In order to facilitate the calculation, the number is successively stored in the position corresponding to the array subscript from low to high, in which the number of digits is stored in the position corresponding to the 0 subscript of the array.

#include
#include
#define MAX_LEN 200
int sz[MAX_LEN + 10];
char szLine[MAX_LEN + 10];

int main()
{
	int len, i;
	scanf("%s", szLine);
	Memset (SZ, 0, sizeof (SZ)); / * array clear*/
	sz[0] = strlen(szLine);
	for (i = 1; i <= sz[0]; i++) {
		sz[i] = szLine[sz[0] - i] - '0';
	}
	return 0;
}

2. High precision number comparison

int cmp(int a[], int b[]) {
	int i;
	if (a[0] > b[0]) {
		return 1;
	}
	else if (a[0] < b[0]) {
		return -1;
	}
	for (i = a[0]; i >= 1; i--) {
		if (a[i] > b[i]) {
			return 1;
		}
		else if (a[i] < b[i]) {
			return -1;
		}
	}
	return 0;
}

High precision addition

void plus(int a[], int b[]) {
	int i;
	if (a[0] < b[0]) {
		a[0] = b[0];
	}
	for (i = 1; i <= a[0]; i++) {
		a[i] += b[i];
		if (a[i] >= 10) {
			a[i + 1]++;
			a[i] -= 10;
		}
	}
	if (a[a[0] + 1] != 0) {
		a[0]++;
	}
}

4. High precision subtraction

int minus(int a[], int b[]) {
	int i;
	if (cmp(a, b) == 0) {
		memset(a, 0, sizeof(a));
		a[0] = 1;
		return 0;
	}
	else if (cmp(a, b) > 0) {
		for (i = 1; i <= a[0]; i++) {
			a[i] = a[i] - b[i];
			if (a[i] < 0) {
				a[i + 1] -= 1;
				a[i] += 10;
			}
		}
		while (a[a[0]] == 0) {
			a[0]--;
		}
		return 1;
	}
	else {
		minus(b, a);
		for (i = 0; i <= b[0]; i++) {
			a[i] = b[i];
		}
		return -1;
	}
}/*The return value represents the sign of the subtraction result*/

reference material:
1. Learning algorithm from scratch: high precision calculation
2. High precision algorithm

Recommended Today

Review of SQL Sever basic command

catalogue preface Installation of virtual machine Commands and operations Basic command syntax Case sensitive SQL keyword and function name Column and Index Names alias Too long to see? Space Database connection Connection of SSMS Connection of command line Database operation establish delete constraint integrity constraint Common constraints NOT NULL UNIQUE PRIMARY KEY FOREIGN KEY DEFAULT […]