How to find all happy numbers in a specific range with Swift

1 Answer

0 votes
import Foundation

// A happy number is a number that eventually reaches 1 
// when repeatedly replaced by the sum of the squares of its digits.
//
// 19 = 1^2 + 9^2 = 82
// 19 -> 82 -> 68 ->100 -> 1 eventually reaches 1 
// 19 = happy numbe

// Compute the sum of squares of digits of n
func sumOfDigitSquares(_ n: Int) -> Int {
    var num = n
    var sum = 0
    while num > 0 {
        let d = num % 10
        sum += d * d
        num /= 10
    }
    return sum
}

// Determine whether n is a happy number
func isHappy(_ n: Int) -> Bool {
    var seen = Set<Int>()
    var num = n

    while num != 1 && !seen.contains(num) {
        seen.insert(num)
        num = sumOfDigitSquares(num)
    }
    return num == 1
}

func main() {
    let a = 1
    let b = 100

    var happyNumbers: [Int] = []

    for i in a...b {
        if isHappy(i) {
            happyNumbers.append(i)
        }
    }

    print("Happy numbers in range [\(a), \(b)]:")
    print(happyNumbers.map(String.init).joined(separator: " "))
}

main()


/*
run:

Happy numbers in range [1, 100]:
1 7 10 13 19 23 28 31 32 44 49 68 70 79 82 86 91 94 97 100 

*/

 



answered Feb 25 by avibootz
...