## Hidden Squares

### June 2, 2020

We have a simple task today:

A number

nmay have squares hidden among its digits. For instance, in the number 1625649, the consecutive digits 1, 4, 9, 16, 25, 49, 64, 256 and 625 are all squares.

Your task is to write a program that takes a positive integer *n* and finds all of its hidden squares. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

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.