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

1 Answer

0 votes
// compute sum of digits
fun digitSum(n0: Long): Long {
    var n = n0
    var s: Long = 0

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

    return s
}

fun main() {
    var n: Long = 2

    while (true) {
        val s = digitSum(n)

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

        n++
    }
}


/*
run:

Found: 81 = (9)^2

*/

 



answered 1 day ago by avibootz

Related questions

...