完整程式碼
#include <stdio.h> int main(void){ int A, B, i, gcd; scanf("%d %d", &A, &B); for(i=A; i>=1; i--){ if(A%i == 0 && B%i ==0){ gcd = i; break; } } printf("%d\n", gcd); printf("%d", A*B/gcd); return 0; }
While迴圈解
#include <stdio.h> int main(void){ int a, b, r, num1, num2; scanf("%d %d", &a, &b); num1=a; num2=b; while(b!=0){ r = a%b; a = b; b = r; } printf("%d\n%d", a, num1*num2/a); return 0; }
遞迴函式
#include <stdio.h> int gcd(int a, int b); int lcm(int a, int b); int main(void){ int a, b; scanf("%d %d", &a, &b); printf("%d\n",gcd(a,b)); printf("%d",lcm(a,b)); return 0; } // GCD, LCM 遞迴函式 int gcd(int a, int b){ if(b==0){ return a; }else{ return gcd(b, a%b); } }int lcm(int a, int b){ return (a*b/gcd(a,b)); }
輸出結果
參考資料:TQC+ C第2版