試以輾轉相除法, 解最大公因數.- #include<cstdlib>
- using namespace std;
- int main()
- {
- int x,y,tmp;
- cout<<"請依序輸入兩個正整數: ";
- cin>>x>>y;
- cout<<x<<"與"<<y<<"的最大公因數為: ";
- while(x%y!=0) //FOR迴圈,條件 (初始值;條件;運算方式)
- {
- tmp=x%y;
- x=y;
- y=tmp;
- }
- cout<<y<<endl<<endl;
- system("pause");
- return 0;
- }
- /*
- x y
- 35 / 56 = 0 ... 35
- 56 / 35 = 1 ... 21
- 35 / 21 = 1 ... 14
- 21 / 14 = 1... 7
- 14 / 7 = 2 ... 0
- */
複製代碼 |