使用 C 語言中的 while 迴圈找出兩個數字的最大公約數
問題
使用 C 程式語言找出任意兩個數字的最大公約數。
解決方案
讓使用者從控制檯輸入任意兩個數字。對於這兩個數字,讓我們找出最大公約數。
兩個數字的最大公約數是能同時整除這兩個數字且餘數為零的最大數字。
我們用來找出兩個數字最大公約數的邏輯如下 −
while(b!=0) //check for b=0 condition because in a/b ,b should not equal to zero { rem=a % b; a=b; b=rem; } Print a
程式 1
#include<stdio.h> int main(){ int a,b,rem; printf("enter any two numbers:"); scanf("%d%d",&a,&b); while(b!=0) //check for b=0 condition because in a/b ,b should not equal to zero{ rem=a % b; a=b; b=rem; } printf("GCD of two numbers is:%d
",a); return 0; }
輸出
enter any two numbers:8 12 GCD of two numbers is:4 Check: 8= 2 * 2 *2 12= 2 * 2 * 3 The Greatest common divisor of two numbers is : 2 * 2 =4
程式 2
在這個示例中,讓我們使用 for 迴圈找出兩個數字的最大公約數 −
#include <stdio.h> int main(){ int num1, num2, i, GCD; printf("enter two numbers: "); scanf("%d %d", &num1, &num2); for(i=1; i <= num1 && i <= num2; ++i){ if(num1%i==0 && num2%i==0) GCD = i; } printf("GCD of two numbers is:%d", GCD); return 0; }
輸出
enter two numbers: 24 48 GCD of two numbers is:24
廣告