常用基础算法程序
常用(常抄 的基础算法程序
1.高位数逐位取出
逆序输出:
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
while (n)
{
cout << n % 10;
n /= 10;
}
return 0;
}
正序输出(使用递归):
#include <iostream>
void get_first_digit(int num) {
if(num < 10) {
std::cout << num << " ";
return;
}
get_first_digit(num / 10);
std::cout << (num % 10) << " ";
}
int main() {
int num = 12345;
get_first_digit(num); // 输出:1 2 3 4 5
return 0;
}
2.获取多位数位数
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int cnt = 0;
while (n)
{
n /= 10;
cnt++;
}
cout << cnt << endl;
return 0;
}
3.求最大公约数
辗转相除
#include <iostream>
using namespace std;
/// @brief Greatest Common Divisor
/// @param a
/// @param b
/// @return
int gcd(int a, int b)
{
if (b == 0)
{
return a;
}
else
{
return gcd(b, a % b);
}
}
int main()
{
int a, b;
cin >> a >> b;
cout << gcd(a, b) << endl;
return 0;
}
或者是递推:
#include <iostream>
using namespace std;
int main()
{
int a, b;
cin >> a >> b;
int c = a % b;
while (c)
{
a = b;
b = c;
c = a % b;
}
cout << b << endl;
return 0;
}
4.求最小公倍数
需要先实现最大公因数。见3.
#include <iostream>
using namespace std;
int main()
{
int a, b;
cin >> a >> b;
cout << a * b / gcd(a, b) << endl;
return 0;
}
5. 排序算法
在之前的随笔总结过,点击查看。
但推荐使用alogithm库中的sort函数。
6. 标准输入输出
在标准库iomanip中提供了很多控制输出流格式的方法。
#include <iostream>
#include <iomanip>
using namespace std;
int main(int argc, char const *argv[])
{
double pi = 3.141592653589793238462643383979;
double f = 12.005782939976756456879889;
double i = 12345678.90;
int h = 64;
int d = 0x12;
cout << fixed << setprecision(10) << pi << endl; // 精确到某位
cout << setprecision(10) << f << endl; // 保留_位有效数字
cout << scientific << i << endl; // 科学计数法
cout << hex << h << endl; // 16进制输出(持续生效)
cout << showbase << oct << d << endl; // 八进制输出显示前缀
cout << setw(8) << dec << h << endl; // 设置宽度
cout << setfill('*') << setw(8) << left << h << endl; // 设置填充字符,默认为空格
return 0;
}
输出:
3.1415926536
12.0057829400
1.2345678900e+07
40
022
64
64******
在main开头加上:
std::ios::sync_with_stdio(false); // 关闭与stdio的同步
std::cin.tie(nullptr); // 取消cin和cout的绑定,减少不必要的缓冲刷新
可以加快读写速度,但是限定不能将scanf、printf和cin、cout混用
7.埃氏筛质数查表
bool isPrime[N];
fill(isPrime, isPrime + N + 1, true);
for (int i = 2; i * i <= N; i++)
{
if (isPrime[i])
{
for (int j = i * i; j <= N; j += i)
{
isPrime[j] = false;
}
}
}
想获取所有质数可以在中间添加相关代码。
8.二分以及模板
手动二分(左闭右开形式):
int l = 1, r = N + 1; // l 指向首位,r指向末尾后一位置,左闭右开
while (l + 1 < r)
{
int mid = (l + r) >> 1; // (l + r) / 2
if (check(a[mid]))
{
l = mid;
}
else
{
r = mid;
}
}
当然可以用algorithm库里的lower_bound代替。

一些常用的算法程序笔记,时不时会忘记怎么写,因此记录一下
浙公网安备 33010602011771号