對於兩個正整數m,n的最大公因數可以用do—while實現

來源:《信息學奧賽一本通(C++版)》P64

【題目描述】
4.9 對於兩個正整數 m,n 的最大公因數可以用do—while實現。
代碼如下,請完善:

#include<iostream>
using namespace std;
int main()
{
	int m,n,r;
	cin>>m>>n;
	do //碾轉相除法
	{
		r=m%n;
		m=____;
		n=____;
	}
	while(____);
	cout<<"the greatest common divisor:"<<_____;
	return 0;
}

注:本樣例爲作者所加,不是書本上的內容

【輸入樣例】
12 3

【輸出樣例】
the greatest common divisor:3

本題解法如下:

注:代碼僅供參考,不只有一種解法。

//這裏是補全後的代碼
#include<iostream>
using namespace std;
int main(){
	int m,n,r;
	cin>>m>>n;
	do //碾轉相除法
	{
		r=m%n;
		m=n;
		n=r;
	}
	while(r!=0);
	cout<<"the greatest common divisor:"<<m<<endl;
	//endl是換行,也可以不加
	system("pause");//防止閃退,可以不加
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章