(递归)最大公约数
題目:
f(x,y)f(x,y)f(x,y)={f(y,x%y),(y>0)x,(y=0)\left\{\begin{matrix} & f(y,x\% y),(y>0) \\ & x,(y=0) \end{matrix}\right.{?f(y,x%y),(y>0)x,(y=0)?
輸入:第一行一個整數t(t ≤100\leq 100≤100)然后有t行,每行兩個整數x(1≤x≤1091 \leq x \leq 10^91≤x≤109),y(1≤x≤1091 \leq x \leq 10^91≤x≤109).
輸出x,y的最大公約數
樣例輸入
1
6 8
樣例輸出
2
代碼:
不解釋了,能用遞歸解決最大公約數問題。歐幾里得輾轉相除法,數論問題。
#include<iostream> #include<algorithm> using namespace std; int f(int x,int y){if(y==0) return x;else return f(y,x%y); } int main(){int t,x,y;cin>>t;while(t--){cin>>x>>y;cout<<f(x,y)<<endl;} }總結
- 上一篇: python queue windows
- 下一篇: (回溯1)八皇后