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

1 Answer

0 votes
package main

import (
    "fmt"
)

// 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 {
    sum := 0
    for n > 0 {
        d := n % 10
        sum += d * d
        n /= 10
    }
    return sum
}

// Determine whether n is a happy number
func isHappy(n int) bool {
    seen := make(map[int]bool)

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

func main() {
    a, b := 1, 100

    if a > b {
        a, b = b, a // swap
    }

    happyNumbers := []int{}

    for i := a; i <= b; i++ {
        if isHappy(i) {
            happyNumbers = append(happyNumbers, i)
        }
    }

    fmt.Printf("Happy numbers in range [%d, %d]:\n", a, b)
    for _, n := range happyNumbers {
        fmt.Printf("%d ", n)
    }
}


/*
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
...