Swift 程序判断给定数字是否为强数
强数是一个特殊的数字,其中其各位数字的阶乘之和等于该数字本身。例如 -
数字 = 345
345! = 3! + 4! + 5! = 6 + 24 + 120 = 150
这里 345 不是强数,因为其各位数字的阶乘之和不等于该数字本身。
数字 = 145
145! = 1! + 4! + 5! = 1 + 24 + 120 = 145
这里 145 是强数,因为其各位数字的阶乘之和等于该数字本身。
在这篇文章中,我们将学习如何编写一个 Swift 程序来判断给定数字是否为强数。
算法
步骤 1 - 创建一个函数。
步骤 2 - 创建原始数字的副本并初始化 sum = 0。
步骤 3 - 运行 while 循环以查找给定数字的最后一位数字。
步骤 4 - 现在找到给定数字所有个位数字的阶乘。
步骤 5 - 将数字的阶乘加起来并将结果存储在 sum 变量中。
步骤 6 - 比较 sum 和原始数字。如果 sum 和原始数字相等,则返回 true。否则,返回 false。
步骤 7 - 创建一个测试变量来存储数字并将其传递给函数。
步骤 8 - 打印输出。
示例
以下是 Swift 程序,用于判断给定数字是否为强数。
import Foundation import Glibc // Function to check if te given number is strong or not func CheckStrongNumber(num: Int) -> Bool { var originalNum = num var sum = 0 // Finding the sum of the factorial // of the digits of the given number while originalNum > 0 { // Calculating the factorial of the digit let lDigit = originalNum % 10 var factorial = 1 for x in 1...lDigit { factorial *= x } // Calculating the sum of the factorial // of the digits of the given number sum += factorial originalNum /= 10 } // Return true if the sum and the number is equal // Otherwise return false return sum == num } // Test case 1 let myInput = 345 if CheckStrongNumber(num: myInput) { print("YES! \(myInput) is a strong number.") } else { print("NO! \(myInput) is not a strong number.") } // Test case 2 let myInput2 = 145 if CheckStrongNumber(num: myInput2) { print("YES! \(myInput2) is a strong number.") } else { print("NO! \(myInput2) is not a strong number.") }
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
输出
NO! 345 is not a strong number. YES! 145 is a strong number.
结论
在上面的代码中,我们有两个数字 345 和 145。现在我们创建一个函数来检查给定的数字是否为强数。在这个函数中,首先,我们首先创建一个原始数字的副本并将 sum 初始化为 0。现在我们运行一个 while 循环来重复提取数字的最后一位,然后执行该数字的阶乘并将阶乘结果添加到 sum 中。然后函数检查给定数字是否等于其各位数字阶乘的和。如果是,则函数返回 true。否则,返回 false。
这就是我们如何检查给定数字是否为强数。