intgcd(int a,int b){if(b ==0){return a;}returngcd(b, a % b);}
2.2 最大公因数 - 非递归解法
用辗转相除法即可
intgcd(int a,int b){while(b !=0){int r = a % b;
a = b;
b = r;}return a;}
2.3 最大公因数 - 内置函数(__gcd())
代码非常简单,加上 numeric 头文件就可以了
cout <<__gcd(a, b)<< endl;
2.4 最小公倍数
#include<iostream>usingnamespace std;intgcd(int x,int y){if(y ==0)return x;returngcd(y, x - y);}intmain(){int n, m, y;
cin >> n >> m;
y =gcd(max(n, m),min(n, m));
cout << n * m / y << endl;//n和m的乘积除以最大公约数=最小公倍数return0;}
#include<bits/stdc++.h>usingnamespace std;typedeflonglong ll;
ll n, m, s;char a[100][100];
ll fx[8]={0,0,1,-1,-1,-1,1,1};
ll fy[8]={1,-1,0,0,-1,1,1,-1};voiddfs(ll x, ll y){
a[x][y]='.';
ll tx, ty;for(ll i =0; i <8; i++){
tx = x + fx[i];
ty = y + fy[i];if(a[tx][ty]=='W'){dfs(tx, ty);}}}intmain(){
cin >> n >> m;for(ll i =1; i <= n; i++){for(ll j =1; j <= m; j++){
cin >> a[i][j];}}for(ll i =1; i <= n; i++){for(ll j =1; j <= m; j++){if(a[i][j]=='W'){
s++;dfs(i, j);}}}
cout << s << endl;return0;}
#include<iostream>#include<vector>usingnamespace std;
vector<int>v(20010),w(20010),dp(2010);int n, m, vi, wi, si, k;intmain(){
cin >> n >> m;for(int i =1; i <= n; i++){
cin >> wi >> vi >> si;int t =1;while(t <= si){
k++;
v[k]= t * vi;
w[k]= t * wi;
si -= t;
t *=2;}if(si >0){
k++;
v[k]= si * vi;
w[k]= si * wi;}}//01背包for(int i =1; i <= k; i++){for(int j = m; j >= w[i]; j--){
dp[j]=max(dp[j], dp[j - w[i]]+ v[i]);}}
cout << dp[m]<< endl;return0;}