L.C.M

优质
小牛编辑
127浏览
2023-12-01

LCM或最小公共两个值的多个,是两个值的倍数的最小正值。

For example ,3和4的倍数是 -

3 →3,6,9,12,15 ......

4 →4,8,12,16,20 ......

两者的最小倍数为12,因此3和4的最小公倍数为12。

算法 (Algorithm)

该程序的算法可以推导为 -

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

伪代码 (Pseudocode)

现在让我们为这个程序派生伪代码 -

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

实现 (Implementation)

该算法的实现如下 -

#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;
}

输出 (Output)

该方案的产出应该是 -

LCM is 12