#include<iostream>
using namespace std;int gcd (int a,int b){if(b ==0)return a;returngcd(b, a%b);}intmain(){int a, b;
cin >> a >> b;
cout <<gcd(a, b)<< endl;return0;}
分数求和
#include<iostream>#include<cstdio>
using namespace std;intgcd(int x,int y){if(y ==0)return x;returngcd(y, x%y);}intmain(){int n;
cin >> n;int a, b, c, d;scanf("%d/%d",&a,&b);for(int i =2; i <= n; i ++){scanf("%d/%d",&c,&d);int fz = a*d + b*c;int fm = b*d;int t =gcd(fz, fm);
a = fz / t;
b = fm / t;}printf("%d/%d", a, b);return0;}
全排列
#include<iostream>
using namespace std;
string s;char ans[6];
bool used[6];int len;voiddfs(int x){if(x == len){for(int i =0; i < len; i ++) cout << ans[i];
cout << endl;return;}for(int i =0; i < len; i ++){if(!used[i]){
ans[x]= s[i];
used[i]= true;dfs(x +1);
used[i]= false;}}}intmain(){
cin >> s;
len = s.size();dfs(0);return0;}
因子分解
#include<iostream>
using namespace std;int ans[40], len;voidf(int x){if(x ==1){
cout << ans[1];int cnt =1;for(int i =2; i <= len; i ++){if(ans[i]== ans[i-1]) cnt ++;else{if(cnt ==1) cout <<'*'<< ans[i];else cout <<'^'<< cnt <<'*'<< ans[i];
cnt =1;}}if(ans[len]== ans[len-1]) cout <<'^'<< cnt;}for(int i =2; i <= x; i ++){if(x%i ==0){
ans[++len]= i;f(x/i);break;}}}intmain(){int n;
cin >> n;f(n);return0;}
分解因数
#include<iostream>
using namespace std;int a, cnt;int ans[20]={2};voiddfs(int x){if(a ==1){
cnt ++;return;}for(int i = ans[x-1]; i <= a; i ++){if(a % i ==0){
ans[x]= i;
a /= i;dfs(x+1);
a *= i;}}}intmain(){int n;
cin >> n;while(n --){
cin >> a;
cnt =0;dfs(1);
cout << cnt << endl;}return0;}
2的幂次方表示
#include<iostream>
using namespace std;int a[15]={1};voidf(int x){for(int i =14; i >=0; i --){if(x >= a[i]){if(i ==0) cout <<"2(0)";elseif(i ==1) cout <<"2";else{
cout <<"2(";f(i);
cout <<")";}
x -= a[i];if(x >0) cout <<"+";elsereturn;}}}intmain(){int n;
cin >> n;for(int i =1; i <=14; i ++) a[i]= a[i-1]*2;f(n);return0;}
逆波兰表达式
#include<iostream>#include<cstdio>#include<cstdlib>
using namespace std;char s[20];doublef(){scanf("%s", s);if(s[0]=='+')returnf()+f();if(s[0]=='-')returnf()-f();if(s[0]=='*')returnf()*f();if(s[0]=='/')returnf()/f();returnatof(s);}intmain(){printf("%f\n",f());return0;}
汉诺塔问题
#include<iostream>#include<cstdio>
using namespace std;int n;char a,b,c;voidmov(int n,char a,char b,char c){if(n ==0)return;mov(n-1, a, c, b);printf("%c->%d->%c\n", a, n, c);mov(n-1, b, a, c);}intmain(){
cin >> n >> a >> b >> c;mov(n, a, c, b);return0;}
扩号匹配问题
#include<iostream>#include<cstdio>#include<cstring>
using namespace std;char a[100],b[100];int up (int d){if(d==-1)return-1;elseif(b[d]=='$')return d;elsereturnup(d-1);}intmain(){while(cin>>a){
cout << a << endl;int len =strlen(a);memset(b,' ',sizeof(b));for(int i=0;i<len;i++){if(a[i]=='(') b[i]='$';elseif(a[i]==')'){int m=up(i-1);if(m==-1) b[i]='?';else b[m]=' ';}}
cout << b << endl;}return0;}