寻找 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
广告