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 }

讓我們看看完整的示例 -

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

輸出

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

示例 2

在這個示例中,我們將找到兩個數字的最小公倍數

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 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.