4
$\begingroup$

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[#]] &]
$\endgroup$
1
  • $\begingroup$ First thing: you want Tuples[{1, 2, 3, 4, 5, 7}, {i}] instead if you want to list only tuples of length i. $\endgroup$ Apr 24, 2020 at 0:41

1 Answer 1

7
$\begingroup$

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
$\endgroup$
2
  • 1
    $\begingroup$ Nitpick: the digit 4 isn't allowed in the desired numbers. $\endgroup$ Apr 24, 2020 at 11:51
  • 1
    $\begingroup$ @MichaelSeifert, I went with the first line in the first code block in OP. $\endgroup$
    – kglr
    Apr 24, 2020 at 11:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.