## Hidden Squares

### June 2, 2020

This is easy:

(define (square? n) (let ((s (isqrt n))) (= n (* s s))))

(define (k-squares k ds) (if (< (length ds) k) (list) (let ((n (undigits (take k ds)))) (if (square? n) (cons n (k-squares k (cdr ds))) (k-squares k (cdr ds))))))

(define (hidden-squares n) (let* ((ds (digits n)) (len (length ds))) (let loop ((k 1) (hs (list))) (if (< len k) (unique = (sort < hs)) (loop (+ k 1) (append (k-squares k ds) hs))))))

And here is the example:

> (hidden-squares 1625649) (1 4 9 16 25 49 64 256 625)

You can run the program at https://ideone.com/9Q3suE.

perl -e ‘print “@{[grep { $ARGV[0]=~/$

/ } map { $*$_ } 1..sqrt($ARGV[0]) ]}\n”;’ 1625649Try again – this time without letting wordpress mess up the formatting…

@programmingpraxis, your solution errors when there is a zero in the number, seemingly from the

`isqrt`

function.Here’s a solution in Python. The program skips the nested loop in some cases where a candidate cannot possibly be square. An online search suggests additional properties of squares in base 10 that can be utilized to narrow the search further (not implemented in my solution).

Output:

A naive implementation in Haskell in which I generate a list of candidate squares and then filter them based on the digits given in the argument:

Hello everybody. Here’s my solution which is implemented in C. I feel like it could be a naive approach, but at the same time I only test each “sub-integer” (like a substring) once, so I don’t think it’s too bad. I’m actually unsure how I could make it better if I’m being honest. Obviously my way of determining if a number is a square is risky (“if(rt == (int)rt)”), but I can’t think of a safe way to do this– and in everything I’ve tried so far it works.