How to check if a number is strong number in Swift

2 Answers

0 votes
// Strong numbers are the numbers that the sum of factorial of its digits 
// is equal to the original number
   
// 145 is a strong number: 1 + 24 + 120 = 145

import Foundation

func factorial(_ n: Int) -> Int {
    var fact = 1
    
    for i in 1...n {
        fact *= i
    }
    
    return fact
}

func main() {
    var n = 145, reminder: Int, sum = 0, tmp: Int
    
    tmp = n

    while n != 0 {
        reminder = n % 10
        sum += factorial(reminder)
        n /= 10
    }

    if sum == tmp {
        print("\(tmp) is a strong number")
    } else {
        print("\(tmp) is not a strong number")
    }
}

main()

 
 
/*
run:
 
145 is a strong number
 
*/

 



answered Oct 19, 2024 by avibootz
0 votes
// Strong numbers are the numbers that the sum of factorial of its digits 
// is equal to the original number
   
// 145 is a strong number: 1 + 24 + 120 = 145

import Foundation

func factorial(_ n: Int) -> Int {
    var fact = 1
    
    for i in 1...n {
        fact *= i
    }
    
    return fact
}

func checkStrongNumber(n: Int) -> Bool {
    var reminder: Int, sum = 0, tmpn: Int
    
    tmpn = n

    while tmpn != 0 {
        reminder = tmpn % 10
        sum += factorial(reminder)
        tmpn /= 10
    }
    
    return n == sum
}

func main() {
    let n = 145
    
    if checkStrongNumber(n: n) {
        print("\(n) is a strong number")
    } else {
        print("\(n) is not a strong number")
    }
}

main()

 
 
/*
run:
 
145 is a strong number
 
*/

 



answered Oct 19, 2024 by avibootz
...