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")); 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());
string ans(len,'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")); }
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
|
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; } 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)); System.out.println(a.subtract(b)); System.out.println(a.multiply(b)); System.out.println(a.divide(b)); BigInteger []c = a.divideAndRemainder(b); System.out.printf("除数为:%d,余数为:%d\n", c[0],c[1] ); } }
|