LogSeq/pages/简单数学算法.md
2023-07-01 23:59:11 +08:00

40 lines
1.3 KiB
Markdown
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

- 素数判定:$\sqrt{n}$算法直接枚举所有小于根号n的数字取模判定
- 素数筛法思路很简单把所有素数的倍数标记为非素数即可。可能需要long long。
- 质因数分解一句话描述从2开始到根号n逮到一个因数就死命除掉
```c
vector<int> prime_factor(int n){
vector<int> retval;
for (int i = 2; i * i <= n; ++ i){
if (n % i == 0) {
retval.push_back(i);
while(n % i == 0) n /= i;
}
}
if (n != 1) retval.push_back(i);
}
```
- 快速幂:
```c
int fpow(int a, int b) { // a^b
int ans = 1;
while (b) {
if (b & 1) ans *= a;
a*= a;
b >>= 1;
}
}
```
- GCD辗转相除没啥好说的其实也可以用编译器函数
```c
int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
inline int gcd(int a, int b) {
while (b) {
int tmp = a;
a = b;
b = tmp % b;
}
}
```
- 另外,对于 C++14我们可以使用自带的 `__gcd(a,b)` 函数来求最大公约数。而对于 C++ 17我们可以使用 [`<numeric>`](https://en.cppreference.com/w/cpp/header/numeric) 头中的 [`std::gcd`](https://en.cppreference.com/w/cpp/numeric/gcd) 与 [`std::lcm`](https://en.cppreference.com/w/cpp/numeric/lcm) 来求最大公约数和最小公倍数。