TITLE: Logic problem involving sum of digits
QUESTION [5 upvotes]: Good one guys! 
I'm studying to the national maths olympiad (brazil)  by myself, and I ran up to the following question: 
Let $S(n)$ be the sum of the digits of n. For example $S(77) = 14$   and   $S(2003) = 5 $ .
Tell if there is a n that is integer, and positive with :
$S(n) = 9 $
&
$S(n^2) = 81 $
I found a number, it is $111 111 111$  ( 9 times de digit 1), 
but it was just a lucky guess. 
I want to go deeper into the exercise and know if there are ways to calculate it (without lucky guesses) using logic or any concept from maths.
Thanks in advance

REPLY [7 votes]: Only a sketch:
one can prove that 
$$s(x+y) \le s(x)+s(y)$$
Equality holds if and only if no carry occurs when adding the digits.
So if $x=\sum 10^i x_i $ and  $y= \sum  10^i y_i$ then equality holds if and only if $x_i+y_i<=9$ for all $i$.
$$s(xy)<=s(x)s(y)$$
Equality holds if and only if: no digit product is larger than $9$ and no carry occurrs while adding the digit products, so $x_j y_{i-j}<=9$ for all possible $i,j$ and  $\sum_j x_j y_{i-j}<=9$. 
Therefore $s(n^2)<=s(n)^2$
and  if $s(n)=9$ then $s(n^2)<=81$
So the number cannot contain a digit larger than $3$ because then the square of the digit is larger than $9$. Also if $x_i$ and $x_j$ are two digits and $x_i\ge 3$ and $x_j \gt 1$ then $x_i x_j+x_j x_i \ge 12$. This is larger than 9 and therefore cannot happen.

So we have only the following possibilities:  
$n$ contains only the digits $0$ and $1$ and $2$
$n$ contains the digits $0$ and $1$ and exactly one digit $3$.

So besides $0$ we can have the following digits
$$1,1,1,1,1,1,1,1,1$$
$$1,1,1,1,1,1,1,2$$
$$1,1,1,1,1,1,2,2$$
$$1,1,1,2,2,2$$
$$1,2,2,2,2$$
$$1,1,1,1,1,1,3$$
If we position nonzero digits only at the digit positions 
$$1,3,7,15,31,\ldots,2^k-1,\ldots$$
then we can guarantee that the product contains only digitsums of the form $(x_i)^2$ (at position $2i$) and $2x_i x_j$ (at position i+j). So no carry will occur. 
So for each digit tuple above we can construct a number with $s(n)=9$ and $s(n^2)=81$, e.g for $1,2,2,2,2$ we can construct $$20000000000000002000000020002010$$
(we can also use a permutation of these digits, e.g $2,2,1,2,2$) 
This will be a number with the desired property.If one adds $0$, it will be a valid number, too. But one can try to construct smaller numbers by removing some of the $0$. As long as no carry occurs, this will be a valid number.