C 語言中求兩個值的最小公倍數的程式



兩個值的最小公倍數或最小公倍數是兩個值的倍數中的最小正值。

例如 3 和 4 的倍數為:

3 → 3、6、9、12、15 ...

4→ 4、8、12、16、20 ...

兩個數的最小公倍數是 12,因此 3 和 4 的最小公倍數是 12。

演算法

該程式的演算法可以如下得出:

START
   Step 1 → Initialize A and B with positive integers
   Step 2 → Store maximum of A & B to max
   Step 3 → Check if max is divisible by A and B
   Step 4 → If divisible, Display max as LCM
   Step 5 → If not divisible then step increase max, goto step 3
STOP

虛擬碼

我們現在為該程式推匯出虛擬碼:

procedure even_odd()
   
   Initialize A and B
   max = max(A, B)
   WHILE TRUE
      IF max is divisible by A and B THEN
         LCM = max
         BREAK
      ENDIF
      Increment max
   END WHILE
   DISPLAY LCM

end procedure

實現

該演算法的實現如下:

#include<stdio.h>

int main() {
   int a, b, max, step, lcm;

   a   = 3;
   b   = 4;
   lcm = 0;

   if(a > b)
      max = step = a;
   else
      max = step = b;

   while(1) {
      if(max%a == 0 && max%b == 0) {
         lcm = max;
         break;    
      }

      max += step;
   }

   printf("LCM is %d", lcm);
   return 0;
}

輸出

程式的輸出應該是:

LCM is 12
mathematical_programs_in_c.htm
廣告
© . All rights reserved.