Mrli
别装作很努力,
因为结局不会陪你演戏。
Contacts:
QQ博客园

ACM-大数定理(高精度)

2020/05/28 ACM C++ java
Word count: 496 | Reading time: 3min

ACM-大数定理(高精度)

由于c/c++中数据类型的范围比较固定,因此有些题目的数据范围正好卡在这些正常范围之外,此时就需要自己实现大数加减乘除的运算。

c/c++需要自己手写

java中有BigInteger类

C++ 加法实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <iostream>
#include <string>
#include <algorithm>

using namespace std;
typedef long long ll;
string add(string a , string b){

a = a.substr(a.find_first_not_of("0"));
// 去前导0
b = b.substr(b.find_first_not_of("0"));

ll lenA = a.length();
ll lenB = b.length();
ll len = max(lenA,lenB) + 10;

reverse(a.begin(),a.end());
// 翻转,方便相加
reverse(b.begin(),b.end());
// cout << "a" << a << endl;
// cout << "b" << b << endl;
string ans(len,'0');
// ans全赋值为0
for(int i =0 ; i < lenA ; i ++) ans[i] = a[i];
int tmp = 0;

for(int i = 0 ; i < len;i++){
if ( i < b.length() ) tmp += (ans[i] - '0') + (b[i] - '0');
else tmp += (ans[i] - '0') ;
ans[i] = (tmp % 10) + '0';
tmp /= 10;
}

reverse(ans.begin(),ans.end());
// 再将运算结果反转回来
return ans.substr(ans.find_first_not_of("0"));
// 仍然需要去前导0
}

int main(){
string a = "3";
string b = "2";
cout << add(a,b) <<endl;
return 0 ;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
A/B/C都是倒序的数字, 比如123, 那么
vector<int> A = {3, 2, 1}
*/
vector<int> add(vector<int> &A, vector<int> &B)
{
vector<int> C;
for (int i = 0, t = 0; i < A.size() || i < B.size() || t; i++) {
if (i < A.size() ) t += A[i];
if (i < B.size() ) t += B[i];
C.push_back(t % 10);
t /= 10;
}
// 去末尾0(前置)
while (C.size() > 1 && C.back() == 0) C.pop_back();
return C;
}

Java 加减乘除

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class HelloWorld {
public static void main(String []args) {
BigInteger a = new BigInteger("100");
BigInteger b = new BigInteger("2");
System.out.println(a.add(b));
// 102
System.out.println(a.subtract(b));
// 98
System.out.println(a.multiply(b));
// 200
System.out.println(a.divide(b));
// 50
BigInteger []c = a.divideAndRemainder(b);
System.out.printf("除数为:%d,余数为:%d\n", c[0],c[1] );
// 除数为:50,余数为:0
}
}

Author: Mrli

Link: https://nymrli.top/2019/04/25/ACM-大数定理(高精度)/

Copyright: All articles in this blog are licensed under CC BY-NC-SA 3.0 unless stating additionally.

< PreviousPost
Java课程第二次实验报告
NextPost >
使用git将项目上传到github(最简单方法)
CATALOG
  1. 1. ACM-大数定理(高精度)
    1. 1.1. C++ 加法实现
    2. 1.2. Java 加减乘除