比赛必背:可重用代码块
我们比赛中经常遇到一些高频次需求:比如判断素数、判断闰年、计算阶乘等,葛老师在这里把经常出现的需求代码写成函数的形式,大家直接背下来,可以在打比赛的时候节省大量时间。:
大整数运算:
1 struct Bigint { 2 int len, a[100]; 3 Bigint(int x = 0) { 4 memset(a, 0, sizeof(a)); 5 for (len = 1; x; len++) 6 a[len] = x % 10, x /= 10; 7 len--; 8 } 9 int& operator [](int i) { 10 return a[i]; 11 } 12 void flatten(int L) {//展平,一次性处理1到L范围内的进位 13 len = L; 14 for (int i = 1; i <= len; i++) 15 a[i + 1] += a[i] / 10, a[i] %= 10; 16 for (; !a[len];)len--;//将长度置为有效长度 17 } 18 void print() { 19 for (int i = max(len, 1); i >= 1; i--) 20 printf("%d", a[i]); 21 } 22 }; 23 Bigint operator+(Bigint& a, Bigint& b) { 24 Bigint c; 25 int len = max(a.len, b.len); 26 for (int i = 1; i <= len; i++) 27 c[i] += a[i] + b[i]; 28 c.flatten(len + 1); 29 return c; 30 } 31 Bigint operator*(Bigint& a, int b) { 32 Bigint c; 33 int len = a.len; 34 for (int i = 1; i <= len; i++) 35 c[i] = a[i] * b; 36 c.flatten(len + 11); 37 return c; 38 }