I need to find the biggest $n$ and $n^2$ given a collection of digits. I need to use every digit.
For example the biggest $n$ in the collection
{ 1, 0, 0, 1, 0, 0 }
is $10$, because $10^2 = 100 = 00100$ (leading zeroes are allowed). How can I do this efficiently?
The length of the collection is always divisible by 3.
Additional examples:
{ 4, 2, 0 } => 2^2 = 04
{ 5, 2, 6, 1, 4, 3, 7, 8, 9 } => 567^2 = 321489
We can make some beforehand observations: We know the digit sum, i.e., the remainder modulo $9$ of $n$ and $n^2$ togerther, i.e., we know $n\cdot(n+1)\bmod 9$. Then $n\bmod 9$ can only have two possible values. But as a feasible general approach, I would take backtracking while building $n$ from the least to most significant digit. The following works, provided $n$ and $n^2$ fit into your
inttype.