其他分享
首页 > 其他分享> > 2021-10-23

2021-10-23

作者:互联网

C++ 高精度

高精度乘法:

#include <iostream>
#include <cstring>
using namespace std;
//定义变量 
const int N = 1e6 + 10;
string s1 , s2;
int m = 0;
int a[N] , b[N] , c[N];
int lena , lenb , lenc;

int main()
{
	//初始化赋值 
	memset(a , 0 , sizeof(a));
	memset(b , 0 , sizeof(b));
	memset(c , 0 , sizeof(c));
	
	getline(cin , s1);
	getline(cin , s2);
	
	//定义两数值长度 
	lena = s1.length();
	lenb = s2.length();
	
	//赋值 
	for(int i = 1 ; i <= lena ; i++)
	{
		a[i] = s1[lena - i] - '0';	
	}   
	
	for(int i = 1 ; i <= lenb ; i++)
	{
		b[i] =  s2[lenb - i] - '0';
	}
	
	for(int i = 1 ; i <= lena ; i++)
	{
		m = 0;
		//错位相加 
		for(int j = 1 ; j <= lenb ; j++)
		{
			//当前乘积加上上次乘积的进位再加上原有数
			c[i + j - 1] = a[i] * b[j] + m + c[i + j - 1];
			//m为进位
			m = c[i + j - 1] / 10;
			//保存下来的数值 
			c[i + j - 1] %= 10; 
		}
		//往前进一位 
		c[i + lenb] = m;
	}
	
	//两数相乘的积最大为两数的长度相加,两位数乘以两位数最大为四位数 
	lenc = lena + lenb;
	
	//去掉结果前面多余的0 
	while(c[lenc] == 0 && lenc > 1)
	{
		lenc--;
	}
	
	for(int i = lenc ; i > 0 ; i--)
	{
		cout << c[i];
	}
	
	return 0;
}

高精度加法:

#include <iostream>
#include <cstring>
using namespace std;

const int N = 1e6 + 10;
int sa[N] , sb[N] , sc[N];
int m = 0;

int main()
{
	memset(sa , 0 , sizeof(sa));
	memset(sb , 0 , sizeof(sb));	
	memset(sc , 0 , sizeof(sc));	
	
	string a , b;
	cin >> a >> b;
	
	int lena , lenb , lenc;
	
	lena = a.size() , lenb = b.size();
	
	for(int i = 1 ; i <= lena ; i++)
	{
		sa[i] = a[lena - i] - '0';
	}
	
	for(int i = 1 ; i <= lenb ; i++)
	{
		sb[i] = b[lenb - i] - '0';
	}
	
	lenc = max(lena , lenb);
	
	for(int i = 1 ; i <= lenc ; i++)
	{
		sc[i] = (m + sa[i] + sb[i]) % 10;
		m = (m + sa[i] + sb[i]) / 10;
	}
	
	if(m != 0)
	{
		sc[++lenc] = 1;
	}
	
	while(sc[lenc] == 0 && lenc > 1)
	{
		lenc--;	
	} 
	
	for(int i = lenc ; i > 0 ; i--)
	{
		cout << sc[i];
	}
	
return 0;
}

高精度减法:

#include <iostream>
#include <cstring>
using namespace std;

const int N = 1e6 + 10;
int a[N] , b[N];

int main()
{
	memset(a , 0 , sizeof(a));
	memset(b , 0 , sizeof(b));
	string s1 , s2 , s3;
	
	int lena , lenb;
	getline(cin , s1);
	getline(cin , s2);
	
	lena = s1.length();
	lenb = s2.length();
	
	if(strcmp(s1.c_str() , s2.c_str()) == 0)
	{
		cout << 0;
		return 0;
	}
	
	if((lena < lenb || lena == lenb) && strcmp(s1.c_str() , s2.c_str()) < 0)
	{
		cout << "-";
		s3 = s1;
		s1 = s2;
		s2 = s3;
	}
	
	for(int i = 1 ; i <= lena ; i++)
	{
		a[i] = s1[lena - i] - '0';
	}
	for(int i = 1 ; i <= lenb ; i++)
	{
		b[i] = s2[lenb - i] - '0';
	}
	
	for(int i = 1 ; i <= lena ; i++)
	{
		if(a[i] < b[i])
		{
			a[i + 1]--;
			a[i] += 10; 
		}
		a[i] -= b[i];
	}
	
	while(a[lena] == 0 && lena > 1)
	{
		lena--;
	}
	
	for(int i = lena ; i >= 1 ; i--)
	{
		cout << a[i];
	}
	
	return 0;
}

标签:lenc,10,lena,23,int,s2,s1,lenb,2021
来源: https://blog.csdn.net/qq_51728241/article/details/120921973