Kotlin程序:检查两个整数之间的阿姆斯特朗数
在本文中,我们将了解如何在Kotlin中显示给定两个数字之间的阿姆斯特朗数。阿姆斯特朗数是一个等于其自身数字立方和的数字。例如,153是
153 = (1)3 + (5)3 + (3)3
以下是相同的演示
假设我们的输入是
1 & 500
期望的输出将是
The Armstrong numbers between 1 and 500 are 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407
算法
步骤1 − 开始
步骤2 − 声明四个整数:inputLow、inputHigh、originalNumber和myResult
步骤3 − 定义inputLow和inputHigh的值
步骤4 − 读取值
步骤5 − 运行for循环,使用%、/和*运算符生成阿姆斯特朗数
步骤6 − 除以10并获得'originalNumber'的余数。
步骤7 − 将'余数'乘以三次,加到'myResult'中,并将其设为当前'myResult'。
步骤8 − 将'originalNumber'除以10,并将其设为当前'originalNumber'。
步骤9 − 显示结果
步骤10 − 结束
示例1
在这个例子中,我们将检查Kotlin中两个整数之间的阿姆斯特朗数。首先,声明并设置两个变量。这是我们将查找阿姆斯特朗数的范围:
val inputLow = 1 val inputhigh = 500
现在,使用for循环内的while循环来查找范围内的阿姆斯特朗数
for (number in inputLow + 1..inputhigh - 1) { var tempDigits = 0 var myResult = 0 var originalNumber = number while (originalNumber != 0) { originalNumber /= 10 ++tempDigits } originalNumber = number while (originalNumber != 0) { val remainder = originalNumber % 10 myResult += Math.pow(remainder.toDouble(), tempDigits.toDouble()).toInt() originalNumber /= 10 }
现在让我们看看查找阿姆斯特朗数的完整示例
fun main() { val inputLow = 1 val inputhigh = 500 println("The lower and higher limit are defined as $inputLow and $inputhigh ") println("The Armstrong numbers are:") for (number in inputLow + 1..inputhigh - 1) { var tempDigits = 0 var myResult = 0 var originalNumber = number while (originalNumber != 0) { originalNumber /= 10 ++tempDigits } originalNumber = number while (originalNumber != 0) { val remainder = originalNumber % 10 myResult += Math.pow(remainder.toDouble(), tempDigits.toDouble()).toInt() originalNumber /= 10 } if (myResult == number) print("$number ") } }
输出
The lower and higher limit are defined as 1 and 500 The Armstrong numbers are: 2 3 4 5 6 7 8 9 153 370 371 407
示例2
在这个例子中,我们将获得两个整数之间的阿姆斯特朗数
fun main() { val inputLow = 1 val inputhigh = 500 println("The lower and higher limit are defined as $inputLow and $inputhigh ") printArmstrongNumbers(inputLow, inputhigh) } fun printArmstrongNumbers(inputLow: Int, inputhigh: Int) { println("The Armstrong numbers are:") for (number in inputLow + 1..inputhigh - 1) { var tempDigits = 0 var myResult = 0 var originalNumber = number while (originalNumber != 0) { originalNumber /= 10 ++tempDigits } originalNumber = number while (originalNumber != 0) { val remainder = originalNumber % 10 myResult += Math.pow(remainder.toDouble(), tempDigits.toDouble()).toInt() originalNumber /= 10 } if (myResult == number) print("$number ") } }
输出
The lower and higher limit are defined as 1 and 500 The Armstrong numbers are: 2 3 4 5 6 7 8 9 153 370 371 407
广告