Kotlin程序查找两个数的最小公倍数


在本文中,我们将了解如何在 Kotlin 中计算两个数字的最小公倍数。两个数字的最小公倍数 (LCM) 是可以被这两个数字整除的最小正整数。

下面是演示

假设我们的输入是

24 and 18

期望的输出将是

The LCM of the two numbers is 72

算法

  • 步骤 1 − 开始

  • 步骤 2 − 声明三个整数:input1、input2 和 myResult

  • 步骤 3 − 定义值

  • 步骤 4 − 使用 while 循环从 1 到两个输入中较大的数字,检查 'i' 值是否能整除这两个输入,并且没有余数。

  • 步骤 5 - 将 'i' 值显示为这两个数字的最小公倍数

  • 步骤 6 - 停止

示例 1

在这个示例中,我们将使用 while 循环查找两个数字的最小公倍数。首先,声明并设置两个输入,稍后我们将找到它们的最小公倍数

val input1 = 24
val input2 = 18

另外,设置一个用于结果的变量 -

var myResult: Int

现在,使用 while 循环并获取最小公倍数

myResult = if (input1 > input2) input1 else input2 while (true) { if (myResult % input1 == 0 && myResult % input2 == 0) { println("The LCM is $myResult.") break } ++myResult }

让我们看看完整的示例 -

Open Compiler
fun main() { val input1 = 24 val input2 = 18 var myResult: Int println("The input values are defined as $input1 and $input2") myResult = if (input1 > input2) input1 else input2 while (true) { if (myResult % input1 == 0 && myResult % input2 == 0) { println("The LCM is $myResult.") break } ++myResult } }

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输出

The input values are defined as 24 and 18
The LCM is 72.

示例 2

在这个示例中,我们将找到两个数字的最小公倍数

Open Compiler
fun main() { val input1 = 24 val input2 = 18 println("The input values are defined as $input1 and $input2") getLCM(input1, input2) } fun getLCM(input1: Int, input2: Int){ var myResult: Int myResult = if (input1 > input2) input1 else input2 while (true) { if (myResult % input1 == 0 && myResult % input2 == 0) { println("The LCM is $myResult.") break } ++myResult } }

输出

The input values are defined as 24 and 18
The LCM is 72.

更新于: 2022年10月13日

553 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告