- 利用示例學習 C 語言
- 利用示例學習 C 語言 - 主頁
- C 語言示例 - 簡單程式
- C 語言示例 - 迴圈/迭代
- C 語言示例 - 模式
- C 語言示例 - 陣列
- C 語言示例 - 字串
- C 語言示例 - 數學
- C 語言示例 - 連結串列
- C 語言程式設計實用資源
- 利用示例學習 C 語言 - 快速指南
- 利用示例學習 C 語言 - 資源
- 利用示例學習 C 語言 - 討論
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
廣告