How to check if a number is a happy number in Go

1 Answer

0 votes
package main

// 8^2 + 2^2 = 68
// 6^2 + 8^2 = 100
// 1^2 + 0^2 + 0^2 = 1 = happy number

import (
    "fmt"
)

func sumOfSquares(n int) int {
    sum := 0
    for n > 0 {
        d := n % 10
        sum += d * d
        n /= 10
    }
    return sum
}

func isHappy(n int) bool {
    seen := make(map[int]bool)

    for n != 1 && !seen[n] {
        seen[n] = true
        n = sumOfSquares(n)
    }

    return n == 1
}

func main() {
    num := 82

    if isHappy(num) {
        fmt.Printf("%d is a happy number\n", num)
    } else {
        fmt.Printf("%d is NOT a happy number\n", num)
    }
}



/*
run:

82 is a happy number

*/

 



answered Feb 23 by avibootz
edited Feb 24 by avibootz
...