# Consider all numbers, from two-digit up to 10-digit, written only with digits 1, 2, 3, 5, 7. Identify those that are perfect squares

Consider all numbers, from two-digit up to 10-digit, written only with digits 1, 2, 3, 5, 7. Identify those that are perfect squares

I got this problem but don't know how to solve it. This is what I did so far.

For example: 121 is one such number, since it uses only digits 1 and 2 and it is a perfect square.

list = Flatten[Table[Tuples[{1, 2, 3, 4, 5, 7}, i], {i, 2, 10}], 1];
list2 = Table[FromDigits[list[[j]]], {j, 1, Length[list]}];
Select[list2, IntegerQ[Sqrt[#]] &]

• First thing: you want Tuples[{1, 2, 3, 4, 5, 7}, {i}] instead if you want to list only tuples of length i. Commented Apr 24, 2020 at 0:41

OP's method used with smaller number of digits:

n = 9;
(list = Flatten[Table[Tuples[{1, 2, 3, 4, 5, 7}, i], {i, 2, n}], 1];
list2 = Table[FromDigits[list[[j]]], {j, 1, Length[list]}];
result0 = Select[list2, IntegerQ[Sqrt[#]] &];) //  AbsoluteTiming // First

359.991


An alternative approach:

result1 = Select[FreeQ[0 | 6 | 8 | 9] @* IntegerDigits]@
(Range[3, Ceiling[N @ Sqrt[FromDigits[ConstantArray[7, n]]]]]^2); //
AbsoluteTiming // First

 0.091785

result0 == result1

 True


We get the result for 10 digits in a fraction of a second:

result10digits = Select[FreeQ[0 | 6 | 8 | 9] @* IntegerDigits]@
(Range[3, Ceiling[N@Sqrt[FromDigits[ConstantArray[7, 10]]]]]^2); //
AbsoluteTiming // First

0.2668

Length @ result10digits

714

• Nitpick: the digit 4 isn't allowed in the desired numbers. Commented Apr 24, 2020 at 11:51
• @MichaelSeifert, I went with the first line in the first code block in OP.
– kglr
Commented Apr 24, 2020 at 11:58