Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "bufio"
- "fmt"
- "math"
- "os"
- "strconv"
- "strings"
- )
- func main() {
- reader := bufio.NewReader(os.Stdin)
- for {
- fmt.Println("Enter a positive number >= 1, or negative number to quit: ")
- text, _ := reader.ReadString('\n')
- i, err := strconv.Atoi(strings.TrimSpace(text))
- if err != nil {
- fmt.Println("Please enter a number")
- continue
- }
- if i <= 1 {
- fmt.Println("Bye")
- break
- }
- typ, sequence := happyOrSad(i)
- fmt.Printf("%d is %s and the sequence is %v\n", i, typ, sequence)
- }
- }
- func happyOrSad(num int) (string, []int) {
- seen := make(map[int]bool)
- seq := []int{num}
- for num != 1 && !seen[num] {
- seen[num] = true
- cur := num
- num = 0
- for cur > 0 {
- num += int(math.Pow(float64(cur%10), float64(2)))
- cur /= 10
- }
- seq = append(seq, num)
- }
- var typ string
- if num == 1 {
- typ = "happy"
- } else {
- typ = "sad"
- }
- return typ, seq
- }
Advertisement
Add Comment
Please, Sign In to add comment