## Sum Square Digits Sequence

### April 27, 2018

Here is our solution, with help from the Standard Prelude; we short-circuit the loop by stopping as soon as any member of the loop is found:

(define (ssds n) ; sum square digits sequence (let loop ((n n) (ns (list))) (if (or (= n 1) (member n '(4 16 37 58 89 145 42 20))) (reverse (cons n ns)) (let ((x (sum (map square (digits n))))) (loop x (cons n ns))))))

Here are two examples:

> (ssds 19) (19 82 68 100 1) > (ssds 18) (18 65 61 37)

You can run the program at https://ideone.com/Ro26ys. There is more to the topic of Happy Numbers than we have discussed here; oeis.org is a good place to learn more.

Advertisements

Pages: 1 2

Although the problem is ill-defined (there is a case of a number being neutral, i.e. neither happy or sad), we’ll look at the case where the number is happy if and only if the end result is 1. Here is my take with Julia.

global sad = [4, 16, 37, 58, 89, 145, 42, 20];

function DigitsOf(n::Int64)

digits = split(string(n), “”)

z = length(digits)

Z = Array{Int64}(z)

end

function IsHappy(n::Int64)

D, nd = DigitsOf(n)

S = [n]

end

Whatever the case, creative problems like this can make someone quite happy, for sure. Happy weekend everyone!

Perl6 solution with a simple loop:

Here is my Golang solution, with a disclaimer that I’m just learning Go and so far don’t like it very much:

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

}

Here is a pastebin of the above code (thought WordPress formatted Go these days).

Here’s a Haskell solution. (I’m calling the sequence a “Porges sequence”.)

Python 3 version, one function to generate the sequence, terminating with either a known sad number or 1, and one function to check the ‘happiness’ of a number:

I used mathematical operations to find the sum of squared digits, rather than casting to string, although Python does make that easy :)

Here’s a solution in C.

Example Usage:

@Zach, the problem mentions and links to a proof that all natural numbers are either “happy” or “sad”. I think this contradicts there being any “neutral” numbers.

Zach -> Zack