一,大数
下面为我的高精度整数模板
#include <cstdio> #include <cmath> #include <cstring> #include <iostream> using namespace std; #define MAXN 500 struct BigNum { int num[MAXN]; int len; }; //高精度比较 a > b return 1, a == b return 0; a < b return -1; int Comp(BigNum &a, BigNum &b) { int i; if (a.len != b.len) return (a.len > b.len) ? 1 : -1; for (i = a.len - 1; i >= 0; i--) if (a.num[i] != b.num[i]) return (a.num[i] > b.num[i]) ? 1 : -1; return 0; } //高精度加法 BigNum Add(BigNum &a, BigNum &b) { BigNum c; int i, len; len = (a.len > b.len) ? a.len : b.len; memset(c.num, 0, sizeof(c.num)); for (i = 0; i < len; i++) { c.num[i] += (a.num[i] + b.num[i]); if (c.num[i] >= 10) { c.num[i + 1]++; c.num[i] -= 10; } } if (c.num[len]) len++; c.len = len; return c; } //高精度减法,保证a >= b BigNum Sub(BigNum &a, BigNum &b) { BigNum c; int i, len; len = (a.len > b.len) ? a.len : b.len; memset(c.num, 0, sizeof(c.num)); for (i = 0; i < len; i++) { c.num[i] += (a.num[i] - b.num[i]); if (c.num[i] < 0) { c.num[i] += 10; c.num[i + 1]--; } } while (c.num[len - 1] == 0 && len > 1) len--; c.len = len; return c; } BigNum Mul(BigNum &a, BigNum &b) { int i, j, len = 0; BigNum c; memset(c.num, 0, sizeof(c.num)); for (i = 0; i < a.len; i++) { for (j = 0; j < b.len; j++) { c.num[i + j] += (a.num[i] * b.num[j]); if (c.num[i + j] >= 10) { c.num[i + j + 1] += c.num[i + j] / 10; c.num[i + j] %= 10; } } } len = a.len + b.len - 1; while (c.num[len - 1] == 0 && len > 1) len--; if (c.num[len]) len++; c.len = len; return c; } BigNum Pow(BigNum &a, int n) { BigNum ans; ans.num[0] = 1, ans.len = 1; while (n) { if (n & 1) ans = Mul(ans, a); a = Mul(a, a); n >>= 1; } return ans; } //高精度除以低精度,除的结果为c, 余数为f void Div1(BigNum &a, int &b, BigNum &c, int &f) { int i, len = a.len; memset(c.num, 0, sizeof(c.num)); f = 0; for (i = a.len - 1; i >= 0; i--) { f = f * 10 + a.num[i]; c.num[i] = f / b; f %= b; } while (len > 1 && c.num[len - 1] == 0) len--; c.len = len; } //高精度*10 void Mul10(BigNum &a) { int i, len = a.len; for (i = len; i >= 1; i--) a.num[i] = a.num[i - 1]; a.num[i] = 0; len++; while (a.num[len - 1] == 0 && len > 1) len--; a.len = len; } //高精度除以高精度,除的结果为c,余数为f void Div2(BigNum &a, BigNum &b, BigNum &c, BigNum &f) { int i, len = a.len; memset(c.num, 0, sizeof(c.num)); memset(f.num, 0, sizeof(f.num)); f.len = 1; for (i = len - 1; i >= 0; i--) { Mul10(f); f.num[0] = a.num[i]; while (Comp(f, b) >= 0) { f = Sub(f, b); c.num[i]++; } } while (len > 1 && c.num[len - 1] == 0) len--; c.len = len; } void print(BigNum &a) { //输出大数 int i; for (i = a.len - 1; i >= 0; i--) printf("%d", a.num[i]); puts(""); } void Init(BigNum &a, char *s, int &tag) { //字符串转化为大数 memset(a.num, 0, sizeof(a.num)); int i = 0, j = strlen(s); if (s[0] == '-') { j--; i++; tag *= -1; } a.len = j; for (; s[i] != '