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) } } }
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
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.