欧几里德公式求最大公因数和最小公倍数
如下:
#include<stdio.h> int gcd(int a,int b){ int temp; if(b > a){ temp = b; b = a; a = temp; } while(b){ temp = a%b; a = b; b = temp; } return a; } int lcm(int a,int b,int gcd){ int temp; if(b > a){ temp = b; b = a; a = temp; } return (a/gcd)*b; //先除再乘,避免溢出 } int main(){ int lcm2,gcd2; int a,b; while(~scanf("%d %d",&a,&b)){ gcd2 = gcd(a,b); lcm2 = lcm(a,b,gcd2); printf("%d和%d的最小公倍数是%d\n",a,b,lcm2); printf("%d和%d的最大公因数是%d\n",a,b,gcd2); } return 0; }