尋找 C 語言中最大公因數的程式



一個最大公因數,又稱最高公因子,是兩個或多個值的最大的公因子。

例如 12 和 16 的因子為 -

12 → 1, 2, 3, 4, 6, 12

16 → 1, 2, 4, 8, 16

公因子為 1、2、4,最大公因子為 4。

演算法

此程式的演算法可推導為 -

START
   Step 1 → Define two variables - A, B
   Step 2 → Set loop from 1 to max of A, B
   Step 3 → Check if both are completely divided by same loop number, if yes, store it
   Step 4 → Display the stored number is HCF
STOP

虛擬碼

procedure even_odd()

   Define two variables a and b
   FOR i = 1 TO MAX(a, b) DO
      IF a % i is 0 AND b % i is 0 THEN
         HCF = i
      ENDIF
   ENDFOR
   DISPLAY HCF

end procedure

實現

此演算法的實現如下 -

#include<stdio.h>

int main() {
   int a, b, i, hcf;

   a = 12;
   b = 16;

   for(i = 1; i <= a || i <= b; i++) {
   if( a%i == 0 && b%i == 0 )
      hcf = i;
   }

   printf("HCF = %d", hcf);
   
   return 0;
}

輸出

程式的輸出應為 -

HCF = 4
mathematical_programs_in_c.htm
廣告
© . All rights reserved.