R 程序查找最小公倍数 (L.C.M)


2023年2月5日, Learn eTutorial
2512

如何查找给定数字的最小公倍数 (LCM)

最小公倍数 (LCM) 是指能被两个给定数字完美整除的最小正整数。例如,**2** 和 **3** 的最小公倍数是 **6**。最小公倍数应大于或等于两个给定数字中较大的一个。

R 程序中最小公倍数检查的实现方式

在这个 R 程序中,我们使用 `readline()` 函数来获取用户输入。将用户输入的值存储到 **n1** 和 **n2** 中。现在,找出 n1 和 n2 中最大的数字。然后使用无限 `while` 循环,检查这两个输入数字是否都能完美整除循环中的数字(较大者)。如果是,则将该数字存储为最小公倍数 (L.C.M.),否则将较大者递增 1,直到找到一个能被输入数字整除的数字,并将其作为最小公倍数打印出来。

算法

步骤 1:要求用户输入

步骤 2:使用 readline() 将用户输入存储到变量 n1, n2

步骤 3:首先确定给定数字中最大的数字

步骤 4:使用无限 while 循环 从该数字开始并向后遍历

步骤 5:检查两个输入数字是否都能完美整除我们的数字

步骤 6:如果可以,则将该数字存储为最小公倍数 (L.C.M.) 并退出循环

步骤 7:否则,该数字递增 1,循环继续

 

R 源代码

                                          lcm <- function(x, y) {
# choose the greater number
if(x > y) {
greater = x
} else {
greater = y
}
while(TRUE) {
if((greater %% x == 0) && (greater %% y == 0)) {
lcm = greater
break
}
greater = greater + 1
}
return(lcm)
}
# take input from the user
n1 = as.integer(readline(prompt = "Enter first number: "))
n2 = as.integer(readline(prompt = "Enter second number: "))
print(paste("The L.C.M. of", n1,"and", n2,"is", lcm(n1, n2)))
                                      

输出

Enter first number: 3
Enter second number: 5
[1] "The L.C.M. of 3 and 5 is 15"