C/C++程式設計題之求兩個數的最大公約數和最小公倍數
阿新 • • 發佈:2019-01-25
求兩個數的最大公約數和最小公倍數
方法:最大公約數使用輾轉相除法求,最小公倍數等於兩個數的乘積/最大公約數 輾轉相除法的原理:用輾轉相除法求幾個數的最大公約數,先求出其中任意兩個數的最大公約數,再求這個最大公約數與第三個數的最大公約數,依次求下去,直到最後一個數為止。最後所得的那個最大公約數,就是所有這些數的最大公約數。 程式碼:#include <stdlib.h> /* 輸出:unsigned int *pHighCommonDivissor //最大公約數 unsigned int *pLeastCommonMultiple //最小公倍數 */ unsigned int gcd(unsigned int first, unsigned int second) { if(second == 0) return first; return gcd(second,first%second); } void getNumber(unsigned int first, unsigned int second, unsigned int *pHighCommonDivissor, unsigned int *pLeastCommonMultiple) { /*在這裡實現功能*/ if(pHighCommonDivissor == NULL || pLeastCommonMultiple == NULL || first == 0 || second == 0) return; unsigned int tmp; if(first < second) { tmp = first; first = second; second = tmp; } tmp = first * second; *pHighCommonDivissor = gcd(first,second); *pLeastCommonMultiple = tmp/(*pHighCommonDivissor); return; }