支持求2个以上数值的最大公约数和最小公倍数,可以用作通分。 #include <stdio.h> #include <math.h> //两个数最大公约数 int getMaxDivisor(int large, int little) { //修补一个bug //int temp = large%little; int temp = 0; if (little==0) return large; temp = large%little; while(temp) { large = little; little = temp; temp = large%little; } return little; } //两个数最小公倍数 int getMinMultiple(int large, int little) { return large*little/getMaxDivisor(large,little); } //多个数最大公约 int getGroupMaxDivisor(int array[], int number) { int i = 0; int temp = array[0]; int little,large; for (i=1; i<number;i++) { little = temp<array[i]?temp:array[i]; large = temp>array[i]?temp:array[i]; temp = getMaxDivisor(large, little); } return temp; } //多个数最小公倍数 int getGroupMinMulti(int array[], int number) { int i = 0; int temp = array[0]; int little,large; while(i <= number -1) { little = temp<array[i]?temp:array[i]; large = temp>array[i]?temp:array[i]; temp = getMinMultiple(large, little); i++; } return temp; } void test() { //printf("12,8,%d/n",getMinMultiple(128,24)); //printf("4,8,%d/n",getMinMultiple(12,20)); int a[4] = {2,8,16,10}; printf("%d/n",getGroupMaxDivisor(a,sizeof(a)/sizeof(int))); printf("%d/n",getGroupMinMulti(a,sizeof(a)/sizeof(int))); } int main() { test(); return 0; }