遞歸法求最大公約數(shù)和最小公倍數(shù)的實(shí)現(xiàn)代碼
數(shù)學(xué)原理:
設(shè)有兩個(gè)數(shù)num1和num2,假設(shè)num1比較大。令余數(shù)r = num1 % num2。
當(dāng)r == 0時(shí),即num1可以被num2整除,顯然num2就是這兩個(gè)數(shù)的最大公約數(shù)。
當(dāng)r != 0時(shí),令num1 = num2(除數(shù)變被除數(shù)),num2 = r(余數(shù)變除數(shù)),再做 r = num1 % num2。遞歸,直到r == 0。
以上數(shù)學(xué)原理可以用具體的兩個(gè)數(shù)做一下分析,這樣容易理解。
代碼實(shí)現(xiàn)(求最大公約數(shù)):
#include <iostream>
using namespace std;
int gcd(int a, int b);//聲明最大公約數(shù)函數(shù)
int main()
{
int num1 = 1;
int num2 = 1;
cin >> num1 >> num2;
while(num1 == 0 || num2 == 0)//判斷是否有0值輸入,若有則重新輸入
{
cout << "input error !" << endl;
cin >> num1 >> num2;
}
cout << "The gcd of " << num1 << " and " << num2 << " is: " << gcd(num1, num2) << endl;//調(diào)用最大公約數(shù)函數(shù)
return 0;
}
int gcd(int a, int b)//函數(shù)定義
{
int max = a > b ? a : b;
int min = a < b ? a : b;
a = max;
b = min;
int r = a % b;
if(0 == r)//若a能被b整除,則b就是最大公約數(shù)。
return b;
else
return gcd(b, r);//遞歸
}
最小公倍數(shù)的求法建立在求最大公約數(shù)的方法之上。因?yàn)樽钚」稊?shù)等于兩個(gè)數(shù)的積除以最大公約數(shù)。
代碼實(shí)現(xiàn)(求最小公倍數(shù)):
#include <iostream>
using namespace std;
int gcd(int a, int b);//聲明最大公約數(shù)函數(shù)
int main()
{
int num1 = 1;
int num2 = 1;
int lcm = 1;
cin >> num1 >> num2;
while(num1 == 0 || num2 == 0)//判斷是否有0值輸入,若有則重新輸入
{
cout << "input error !" << endl;
cin >> num1 >> num2;
}
lcm = num1 / gcd(num1, num2) * num2;//先除后乘可以在一定程度上防止大數(shù)
cout << "The lcm of " << num1 << " and " << num2 << " is: " << lcm << endl;
return 0;
}
int gcd(int a, int b)//函數(shù)定義
{
int max = a > b ? a : b;
int min = a < b ? a : b;
a = max;
b = min;
int r = a % b;
if(0 == r)//若a能被b整除,則b就是最大公約數(shù)。
return b;
else
return gcd(b, r);//遞歸
}
以上是僅僅限與求兩個(gè)書的最大公約數(shù)和最小公倍數(shù),當(dāng)數(shù)字有很多時(shí),該法是否依然適用,還有待考證。
- Java求解兩個(gè)非負(fù)整數(shù)最大公約數(shù)算法【循環(huán)法與遞歸法】
- Python實(shí)現(xiàn)的求解最大公約數(shù)算法示例
- 詳解C語言求兩個(gè)數(shù)的最大公約數(shù)及最小公倍數(shù)的方法
- C#獲取兩個(gè)數(shù)的最大公約數(shù)和最小公倍數(shù)示例
- C++ 實(shí)現(xiàn)求最大公約數(shù)和最小公倍數(shù)
- JavaScript隨機(jī)打亂數(shù)組順序之隨機(jī)洗牌算法
- 淺析JavaScript中的常用算法與函數(shù)
- JavaScript實(shí)現(xiàn)的一個(gè)計(jì)算數(shù)字步數(shù)的算法分享
- JavaScript數(shù)據(jù)結(jié)構(gòu)和算法之圖和圖算法
- JS笛卡爾積算法與多重?cái)?shù)組笛卡爾積實(shí)現(xiàn)方法示例
- JavaScript求一組數(shù)的最小公倍數(shù)和最大公約數(shù)常用算法詳解【面向?qū)ο?,回歸迭代和循環(huán)】
相關(guān)文章
詳談C與C++的函數(shù)聲明中省略參數(shù)的不同意義
下面小編就為大家分享一篇詳談C與C++的函數(shù)聲明中省略參數(shù)的不同意義,具有非常好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2017-11-11Visual?Studio?2022?激活碼(親測(cè)可用)
在?Visual?Studio?2019?的基礎(chǔ)上,新版集成開發(fā)壞境提供了非常多的改進(jìn),包括對(duì)?64?位、.NET?6?的支持,為核心調(diào)試器提供更好的性能。本文給大家分享Visual?Studio?2022?激活碼,需要的朋友參考下吧2021-12-12C++版本基于ros將文件夾中的圖像轉(zhuǎn)換為bag包
這篇文章主要介紹了C++版本基于ros將文件夾中的圖像轉(zhuǎn)換為bag包,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-01-01