1.常規法ide
#include<stdio.h> #include<stdlib.h> int main(){ int a, b, i,j; printf("請輸入兩個數\n"); scanf("%d%d", &a, &b); for (i = 2;i<=a;i++){ if (a%i == 0 && b%i == 0) { j = i; } } printf("最大公約數爲:%d", j); system("pause"); return 0; }
2.展轉相除法code
#include<stdio.h> #include<stdlib.h> int main() { int a, b, c; printf("請輸入兩個數\n"); scanf("%d%d", &a, &b); while (b!=0) { //不用比較被除數和除數的大小 c = a % b; a = b; b = c; } printf("最大公約數爲:%d", a); system("pause"); return 0; }
3.更相減損法it
#include<stdio.h> int main() { int i = 0, j = 0, k = 0, a = 0, b = 0; scanf("%d%d", &i, &j); for (a = i,b = j;(a % 2 == 0) & (b % 2 == 0);) { a = a / 2; b = b / 2; } for (k=0;a!=b;) { while (a > b) { k = a - b; a = b; b = k; } if (a == b) break; k = b - a; a = a; b = k; } printf("%d與%d最大公約數爲:%d\n",i,j,k); system("pause"); return 0; }