DEV Community

Discussion on: Write a script to find "Happy Numbers"

Collapse
 
vinaypai profile image
Vinay Pai

Here's a golang implementation, optimized for speed. It takes about 200ms on my machine to find all the happy numbers from 1 to a million on my machine if you take out the prints.

package main

import (
    "fmt"
)

func sumDigitsSquare(n int) int {
    sum := 0
    for n != 0 {
        digit := n % 10
        sum += digit * digit
        n /= 10
    }
    return sum
}

func isHappy(n int, memo map[int]bool) bool {
    if result, seen := memo[n]; !seen {
        result = isHappy(sumDigitsSquare(n), memo)
        memo[n] = result
    }
    return memo[n]
}

func main() {
    memo := make(map[int]bool, 1000000)
    memo[1] = true
    memo[4] = false

    for i := 1; i <= 1000000; i++ {
        if isHappy(i, memo) {
            fmt.Println(i)
        }
    }
}