Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top


Let's take the number 180. This is an interesting number because the sum of digits of this number is equal to:

1 + 8 + 0 = 9

And the squared version of this number, or:

180² = 32400 > 3 + 2 + 4 + 0 + 0 = 9

These are both 9. The sum of digits of the original number and the squared number are the same. Of course, this is also found at OEIS: A058369.


Given a non-negative integer n, output the nth positive number with this condition.

Test cases (zero-indexed)

Input > Output

0 > 1
1 > 9
2 > 10
3 > 18
4 > 19
5 > 45
6 > 46
7 > 55
8 > 90
9 > 99
10 > 100
11 > 145
12 > 180
13 > 189
14 > 190
15 > 198
16 > 199
17 > 289
18 > 351
19 > 361

The input can also be 1-indexed if that fits you better.

This is , so the submission with the least amount of bytes wins!

share|improve this question
In case nobody has spotted it yet, only numbers which are equivalent to 0 or 1 (mod 9) can appear in the list. – Neil Mar 12 at 19:05
@MamaFunRoll Um... no. Sorry. Numbers with digital roots of 5 have squares whose digital root is 7. – Neil Mar 12 at 20:17
@Neil owait nvm – Mama Fun Roll Mar 12 at 20:42

12 Answers 12

up vote 5 down vote accepted

Jelly, 13 bytes


Input is 1-indexed. Try it online!

How it works

1dz#Ṫ    Main link. Argument: n (index)

1        Set the return value to 1.
   #     Execute ... until ... matches have been found.
 Ç         the helper link
  ³        n
    Ṫ    Extract the last match.

,²DS€=/  Helper link. Argument: k (integer)

,²       Pair k with k².
  D      Convert each to decimal.
   S€    Compute the sum of each list of base 10 digits.
     =/  Reduce by equality.
share|improve this answer

Haskell, 54 bytes
([x|x<-[1..],s x==s(x^2)]!!)

Usage example: ([x|x<-[1..],s x==s(x^2)]!!) 17 -> 289.

s calculates the digit sum:

                    show     -- turn number into a string
     map(read.pure)          -- turn every character (the digits) in to a
                             -- one element string and convert back to integer
sum                          -- sum those integers

main function:

[x|x<-[1..]            ]     -- make a list of all x starting from 1
           ,s x==s(x^2)      -- where s x == s (x^2)
                        !!   -- pick nth element from that list
share|improve this answer

Perl 6, 47 46 bytes

{(grep {$_.comb.sum==$_².comb.sum},1..*)[$_]}
share|improve this answer

Mathematica, 64 bytes


Simple anonymous function. Zero-indexed.

share|improve this answer

JavaScript (ES6), 76 73 72 bytes


I spent 30 minutes trying to get this to work until I realized I was outputting the wrong variable :|

This is zero-indexed.

share|improve this answer
I feel like turning this into a recursive function would shorten this up a lot... – Mama Fun Roll Mar 12 at 3:00

Pyth, 15


1 byte thanks to DenkerAffe!

Try it here or run a Test Suite.

Uses the 1-indexed option.

Naive implementation using .f which gets the first n numbers that match the given condition.

share|improve this answer
You can save one byte by removing h if you use 1-indexing which is explicitly allowed. – DenkerAffe Mar 11 at 22:29
@DenkerAffe Oh, thanks I should read more closely :P – FryAmTheEggman Mar 11 at 22:33

MATL, 24 23 bytes


Uses 1-based input.

Try it online!

x        % take inpout and delete it (gets copied into clipboard G)
`        %   do...while
  @      %   push loop iteration index: candidate number, n
  2:^    %   array [n n^2]
  "      %   for each element of that array 
    @    %     push that element 
    V!U  %     get its digits (to string, transpose, to number)
    Xs   %     compute their sum
  ]      %   end for each
  =      %   are the two sums equal?
  ?      %   if so
    @    %     the candidate number is valid: push it
  ]      %   end if
  NG<    %   is number of elements in stack less than input?
]        % if so, proceed with next iteration. End do...while. 
1$       % specify 1 input for implicit display: only top of stack
share|improve this answer
very nice that MATL is finally listed among distant compilers there !. – Agawa001 Mar 12 at 12:39
@Agawa001 Thanks! :-) – Luis Mendo Mar 12 at 14:00

Julia, 79 66 bytes


This is a recursive function that accepts an integer and returns an integer. It uses 1-based indexing.

We store a few things as function arguments:

  • n : The input
  • x : A counter for how many numbers with this condition we've found
  • i : A number to check for the condition
  • s : A function to compute the sum of the digits of its input

While x is less than the input, we recurse, incrementing x if i meets the condition and incrementing i. Once x == n, we return i, but we have to subtract 1 because it will have been incremented one too many times.

share|improve this answer

Convex 0.2, 36 35 bytes

Convex is a new language that I am developing that is heavily based on CJam and Golfscript. The interpreter and IDE can be found here. Input is an integer into the command line arguments. Indexes are one-based. Uses the CP-1252 encoding.

share|improve this answer

Mathematica, 63 60 61 59 bytes


While making this the other answer popped up but I'm beating them by a single byte and I'm posting this before that one gets golfed. One indexed.

share|improve this answer
Fails for input >2457. Simply increasing your Range won't help, because A058369[n]/n doesn't seem to converge. – murphy Mar 11 at 23:14
Better? filler+ – CalculatorFeline Mar 11 at 23:31
10^# would be shorter than 2^#*9. Of course it becomes too slow after n is bigger than about 6... – feersum Mar 12 at 3:19
Why not 9^#?fil – CalculatorFeline Mar 12 at 3:30
Do you have a proof that f(n) <= 9^n? (10 is obvious because 10^n is always a solution). – feersum Mar 12 at 3:42

Retina, 103 bytes

$*1 x
}`^ ?x


Definitely golfable.

Uses the new Retina feature % for squaring (hence not working with the online version yet).

share|improve this answer

Mathcad, 70 50 bytes

Mathcad has no built in functions to convert a number to its digit string, so the user function d(a) does this job. A program then iterates through the positive integers, testing for equality of sums, until it has accumulated n numbers in the vector v. The program is evaluated using the = operator, which displays the result vector. (Note that the whole program appears exactly as displayed below on the Mathcad worksheet)

Updated program: Assumes default initialization of a to zero and makes use of fact that Mathcad returns the value of the last evaluated statement in a program.
Makes use of evaluation order of expressions to increment variable a in the first summation (and which is then available for use in the sum of square)

enter image description here

Original program: Returns a vector of all numbers up to n.

enter image description here

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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