C++ 大数运算(加减乘除取模)
加法:(字符串模拟小学加法)
1 string add(string s1, string s2) { 2 int len1 = s1.length(), len2 = s2.length(); 3 int maxlen = max(len1, len2) + 1; 4 string res(maxlen, '0'); 5 int flag = 0; 6 int i = len1 - 1, j = len2 - 1, k = maxlen - 1; 7 for (; i >= 0 && j >= 0; i--, j--) { 8 int temp = (s1[i] - '0') + (s2[j] - '0') + flag; 9 flag = temp / 10; 10 res[k--]= temp % 10 + '0'; 11 } 12 while (i >= 0) { 13 int temp = s1[i--] - '0' + flag; 14 flag = temp / 10; 15 res[k--] = temp % 10 + '0'; 16 } 17 while (j >= 0) { 18 int temp = s2[j--] - '0' + flag; 19 flag = temp / 10; 20 res[k--] = temp % 10 + '0'; 21 } 22 res[k] = flag + '0'; 23 if (flag) { 24 return res; 25 } else { 26 return res.substr(1); 27 } 28 }
减法:
乘法:
除法:
取模:
1)(a * b) % m = (a % m * b % m) % m
= (a % m * b) % m
= (a * b % m) % m
2) (a + b) % m = (a % m + b % m) % m
= (a % m + b) % m
= (a + b % m) % m
举例子:
1234 % m = ((((1 * 10) + 2) * 10 + 3) * 10 + 4) % m
= (((((1 * 10) + 2) * 10 + 3) * 10) % m + 4) % m
= (((((1 * 10) + 2) * 10 + 3) % m * 10) % m + 4) % m
1 long long mod(string s, int m) { 2 //假设字符串s符合条件,代表一个整数(正数或者负数) 3 int len = s.length(); 4 int start = 0; 5 if (s[0] == '-') { 6 start = 1; 7 } 8 long long num = 0; 9 for (int i = start; i < len; i++) { 10 num = (num * 10 + s[i] - '0') % m; 11 } 12 return num; 13 }
越努力,越幸运