[C++] 高精度乘法

目录


注意: 若还没有学过高精度运算的话先去看高精度加法


引入: 大整数比较

比较方法

大整数比较可以使用此方法比较(注释有讲解):

cpp 复制代码
/*
如果x比y小, 则返回true
否则(y >= x)返回false
*/
bool cmpBIG(int x[], int y[]){
	int lx = x[0], ly = y[0]		// 获取x和y的有效长度
	if(lx != ly) return lx < ly;	// 数位多者大
	for(int i = lx; i >= 1; i--){	// 大数逆向存储, 逆向遍历获得依次正向的数据
		if(x[i] != y[i]) return x[i] < y[i];
	}
	return false;					// 两个数组完全相同
}

例题1-青蛙计数

题目描述

现在皮皮有n个数和一个幸运数m, 希望你统计一下这n个数中有多少个数不小于m.

输入描述

第 1 行,一个整数n,表示有n个数;

第 2 行,一个整数m,表示幸运数;

第 3~n+2 行有 n 个数a[i], 表示每个数

输出描述

输出只有一个整数ans表示有ans个数不小于m

输入输出样例

input:

复制代码
 5
 12
 10
 1
 15
 100
 3

output:

复制代码
2

AC代码

cpp 复制代码
#include <iostream>
#include <string>
#include <cstring>
using namespace std;

bool cmpBIG(int x[], int y[]){
	int lx = x[0], ly = y[0];
	if(lx != ly) return lx < ly;
	for(int i = lx; i >= 1; i--){
		if(x[i] != y[i]) return x[i] < y[i];
	}
	return false;
}

void s2BIG(string s, int a[]){
	int len = s.size();
	for(int i = 1; i <= len; i++){
		a[i] = s[len - i] - '0';
	}
	a[0] = len;
}

int m[1010];
int a[1010];

int main(){
	int n, cnt = 0;
	cin >> n;
	string m2;
	cin >> m2;
	s2BIG(m2, m);
	for(int i = 1; i <= n; i++){
		string s;
		cin >> s;
		s2BIG(s, a);
		if(!(cmpBIG(a, m))){
			cnt++;
		}
		memset(a, 0, sizeof(a));
	}
	cout << cnt;
	return 0;
}

高精度乘法模版

cpp 复制代码
/*
高精度*int
*/
void mulBIG(int x[], int y, int z[]){
	z[0] = x[0];
	for(int i = 1; i <= z[0]; i++) z[i] = x[i] * y;
	for(int i = 1; i <= z[0]; i++){
		z[i + 1] += z[i] / 10;
		z[i] = z[i ] % 10;
		if(z[z[0] + 1] > 0) z[0]++;
	}
	while(z[0] > 1 && z[z[0]] == 0) z[0]--;
}

高精度运算小合集(这集乘法+上集加法)

cpp 复制代码
void s2BIG(string s, int a[]){
	int len = s.size();
	for(int i = 1; i <= len; i++){
		a[i] = s[len - i] - '0';
	}
	a[0] = len;
}

void i2BIG(int n, int a[]){
	int cur = 0;
	while(n > 0){
		cur++;
		a[cur] = n % 10;
		n /= 10;
	}
	if(cur == 0) cur++;
	a[0] = cur;
}

void printBIG(int a[]){
	int len = a[0];
	for(int i = len; i > 0; i--){
		cout << a[i];
	}
	cout << endl;
}

void addBIG(int x[], int y[], int z[]){
	z[0] = max(x[0], y[0]);
	for(int i = 1; i <= z[0]; i++)
		z[i] = x[i] + y[i];
	for(int i = 1; i <= z[0]; i++){	
		z[i + 1] += z[i] / 10;
		z[i] %= 10;
		if(z[z[0] + 1] != 0)
			z[0]++;
	}
}

/*
高精度*int
*/
void mulBIG(int x[], int y, int z[]){
	z[0] = x[0];
	for(int i = 1; i <= z[0]; i++) z[i] = x[i] * y;
	for(int i = 1; i <= z[0]; i++){
		z[i + 1] += z[i] / 10;
		z[i] = z[i ] % 10;
		if(z[z[0] + 1] > 0) z[0]++;
	}
	while(z[0] > 1 && z[z[0]] == 0) z[0]--;
}
相关推荐
地平线开发者2 小时前
J6B vio scenario sample
算法
BothSavage14 小时前
Trae远程开发中DeepSeek自定义模型4054错误的排查与修复
算法
小林ixn14 小时前
从暴力到KMP:一道题彻底搞懂字符串匹配的前世今生
算法
烬羽15 小时前
字符串算法入门:从反转字符串到回文判断,面试不再慌
算法·面试
郝学胜_神的一滴15 小时前
CMake 034:生成器表达式:解耦构建时序、精简分支逻辑的终极利器
c++·cmake
先吃饱再说1 天前
判断回文字符串,从一行代码到双指针优化
算法
见过夏天1 天前
C++ 基础入门完全指南
c++
黄敬峰1 天前
深入理解算法核心:从递归思想、数组扁平化到快速排序
算法