Math
Translated from Chinese by an LLM.
Essential Math
Essential math knowledge (in Bi Dao’s words, this is all second-grade material).
Modular Arithmetic
This is very important - many problems require taking the remainder of the result.
Modular Inverse
Parity
Modulo methodreturn x % 2;AND operation
Essentially an AND operation with 1.
return x & 1;
Bitwise operations are clearly much faster than the modulo method.
Factorial
For any positive integer ,
When you need to use factorials of different numbers extensively, a lot of redundant computation occurs. In that case, you can build an array to store them.
Sum of the first natural numbers
Loop / Recursion method
This method is too slow, but the logic is simple. Time complexity - very slow.
int sum(int n){
int ans = 0;
for(int i = 1;i<=n;i++){
ans += i;
}
return ans;
}Formula method
This is clearly an arithmetic series, so:
In this formula, is too large. Rearranging slightly:
This reduces the risk of overflow. If you don’t cast to double, remember to check the parity of n.
Fast Exponentiation
Hence the following code:
long long qpow(long long a, long long b) {
long long res = 1;
for (; b; b >>= 1, a = a * a) // WTF, AI writes code this well?
if (b & 1) res *= a;
return res;
}