How to find the first integer equal to the sum of its digits raised to some power in Swift

1 Answer

0 votes
// compute sum of digits
func digitSum(_ n0: Int64) -> Int64 {
    var n = n0
    var s: Int64 = 0

    while n > 0 {
        s += n % 10
        n /= 10
    }

    return s
}

func main() {
    var n: Int64 = 2

    while true {
        let s = digitSum(n)

        // Try powers k = 2..10 (enough for reasonable ranges)
        var p: Int64 = s * s
        for k in 2...10 {
            if p == n {
                print("Found: \(n) = (\(s))^\(k)")
                return
            }
            p *= s // next power
        }

        n += 1
    }
}

main()


/*
run:

Found: 81 = (9)^2

*/

 



answered 1 day ago by avibootz

Related questions

...