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!

  • \$\begingroup\$ In case nobody has spotted it yet, only numbers which are equivalent to 0 or 1 (mod 9) can appear in the list. \$\endgroup\$
    – Neil
    Mar 12, 2016 at 19:05
  • \$\begingroup\$ @MamaFunRoll Um... no. Sorry. Numbers with digital roots of 5 have squares whose digital root is 7. \$\endgroup\$
    – Neil
    Mar 12, 2016 at 20:17
  • \$\begingroup\$ @Neil owait nvm \$\endgroup\$ Mar 12, 2016 at 20:42
  • \$\begingroup\$ I wrote a Brachylog predicate to determine whether or not the input is a term of this sequence, but couldn't get the find-nth boilerplate working, so I'll just leave it in a comment: ^₂;?{ẹ+}ᵛ \$\endgroup\$ May 9, 2019 at 3:35

21 Answers 21


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.

05AB1E, 10 9 8 bytes



-1 byte thanks to @Emigna by removing the implicit ½ (increase counter_variable after every iteration) at the end
-1 byte thanks to @Grimy removing the duplicated SO by using ‚1ö

Try it online.


µ         # Loop while the counter_variable is not equal to the (implicit) input yet:
 NÐ       #  Push the 0-based loop index three times
   n      #  Take the square of this index
          #   i.e. 180 → 32400
    ‚     #  Pair it with the index
          #   i.e. 180 and 32400 → [180,32400]
     1ö   #  Convert both numbers from base-1 to base-10, which basically sums the digits
          #   i.e. [180,32400] → [9,9]
       Ë  #  Check if both sums are equal
          #   i.e. [9,9] → 1 (truthy)
          #  (if they are: implicitly increase the counter_variable by 1)
          # (after the loop: implicitly print the top of the stack, which is the remaining
          #  copy of the index from the triplicate we've used)
  • 2
    \$\begingroup\$ You don't need ½ here as it's implicit \$\endgroup\$
    – Emigna
    May 8, 2018 at 15:25
  • 1
    \$\begingroup\$ -1: µNDn‚1öË. is like SO but vectorizes, which lets us avoid code duplication. \$\endgroup\$
    – Grimmy
    May 7, 2019 at 16:31
  • \$\begingroup\$ @Grimy Thanks again. I've also added that as a tip to my Small tips post. :) \$\endgroup\$ May 7, 2019 at 17:41

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

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.

  • 1
    \$\begingroup\$ I feel like turning this into a recursive function would shorten this up a lot... \$\endgroup\$ Mar 12, 2016 at 3:00

Perl 6, 47 46 bytes

{(grep {$_.comb.sum==$_².comb.sum},1..*)[$_]}

Mathematica, 64 bytes


Simple anonymous function. Zero-indexed.


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.

  • \$\begingroup\$ You can save one byte by removing h if you use 1-indexing which is explicitly allowed. \$\endgroup\$
    – Denker
    Mar 11, 2016 at 22:29
  • \$\begingroup\$ @DenkerAffe Oh, thanks I should read more closely :P \$\endgroup\$ Mar 11, 2016 at 22:33

Vyxal, 8 bytes


Try it Online!

Insights scraped from the MathGolf answer and the 05AB1E answer.

↵'²"Ṡ≈;i # Takes the number as input and returns the n-th number in the series, 0-indexed
↵        # 10**input
 '    ;  # Filter the implicit range [0..n]
  ²      # Square the input
   "     # Pair the square with the input
    Ṡ    # Vectorised sum
     ≈   # All equal?
       i # Index into the resulting list

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
  • 1
    \$\begingroup\$ very nice that MATL is finally listed among distant compilers there !. \$\endgroup\$
    – Abr001am
    Mar 12, 2016 at 12:39

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.


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.


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.

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


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


Japt, 15 bytes


_ìx ¶Z²ìx «U´}a

Try it


Java 8, 113 bytes

n->{int r=0;for(;n>=0;)if((++r+"").chars().map(c->c-48).sum()==(r*r+"").chars().map(c->c-48).sum())n--;return r;}



Try it online.

n->{           // Method with integer as both parameter and return-type
  int r=0;     //  Result-integer, starting at 0
  for(;n>=0;)  //  Loop as long as `n` is zero or positive
    if((++r    //   Increase `r` by 1 first
               //   And if the sum of its digits
               //   equals the sum of the digit of its square
      n--;     //    Decrease `n` by 1
  return r;}   //  Return the result

Perl 5 -p, 53 bytes

Includes +1 for -p

1 based

#!/usr/bin/perl -p
$.++while$_-=!eval+("-($.) ".$.**2)=~s/\B/+/gr;$_=$.

Try it online!


TI-BASIC 66 62 bytes

Ans→N:While X<N:IS>(A,A::A:prgmA:Ans→B:A²:prgmA:If B=Ans:IS>(X,N:End:A

Input is \$n\$ in Ans.
Output is the 1-indexed \$n\$th term in the sequence.

Helper function generates the sum of the digits of the value in Ans.




Ans→N:While X<N:IS>(A,A::A:prgmA:Ans→B:A²:prgmA:If B=Ans:IS>(X,N:End:A ;prgmCDGF1E

Ans→N            ;store the input in N
While X<N        ;loop until the Nth term has been reached
IS>(A,A:         ;add 1 to A
                 ; (Increment A and skip the next statement if A>A)
A                ;leave A in Ans
prgmA            ;call the helper program below
Ans→B            ;store the result of the helper program in B
A²               ;square A and leave the result in Ans
prgmA            ;call the helper program below
                 ; (result is in Ans)
If B=Ans         ;if the two results are equal
IS>(X,N          ;add 1 to X
                 ; (Increment X and skip the next statement if X>N)
A                ;leave A in Ans
                 ;implicit print of Ans

sum(int(10fPart(Ans₁₀^(seq(⁻X-1,X,0,log(Ans   ;prgmA

                      seq(⁻X-1,X,0,log(Ans    ;generate a list...
                                              ; using X as the variable,
                                              ; starting at 0,
                                              ; ending at the log of Ans,
                                              ; and evaluating "⁻X-1" for each element
                                              ; (implicit increment of 1)
                   ₁₀^(                       ;raise 10 to the power of each element
                Ans                           ;multiply each element by the input
          fPart(                              ;remove the integer part from each element
        10                                    ;multiply each element by 10
    int(                                      ;round each element to the nearest integer
sum(                                          ;then sum the resulting list

Note: TI-BASIC is a tokenized language. Character count does not equal byte count.


J, 62 bytes


Try it online!

1 indexed. J once again not performing well on these "nth of" tasks, because of the excessive bookeeping mechanics.


APL(NARS), 49 chars, 98 bytes

r←h w;c

1-indexed, test:

1 9 10 18 19 45 46 55 90 99 100 145 180 189 190 198 199 289 351 361 

MathGolf, 10 bytes


Try it online!


To make this usable, I chose to present a version which calculates every number with this property below 1000, and fetches the correct item from that list. To have a solution which would work for any input size, the first byte could be replaced by ú (push 10**TOS). Since the n:th term in the sequence is always less than \$10^n\$, the script would always succeed. However, this puts a practical limit on calculation that's very low.

♪            push 1000
 ╒           range(1,n+1)
  gÆ         filter list using the next 5 operators
    ‼        apply next two commands to TOS
     Σ       sum(list), digit sum(int)
      ²      pop a : push(a*a) (square)
       Σ     sum(list), digit sum(int) (pushes the digit sum of the square)
        =    pop(a, b), push(a==b) (compares the two)
         §   get from array (returns the <input>th item from the filtered list
  • \$\begingroup\$ Maybe I should just create a chat for MathGolf.. Anyway, I have a question: are there any builtins for replace, split by, and such for strings? I have the feeling compression might save bytes here, but not sure if the builtins exist to accomplish it. \$\endgroup\$ Jun 11, 2019 at 14:29
  • \$\begingroup\$ There is a closed MathGolf chat. I tried keeping it alive, but lately I've been swamped with work, and it kept getting closed. I don't want to bother the mods every time. To answer your question, MathGolf wasn't really meant to handle string operations, but I've implemented functionality for string handling to handle some basic challenges. As you've noticed, there's still a lot to desire. If I add anything, it'll probably be something similar to what 05AB1E has, but I haven't really gotten any spare time for MathGolf development these last months. \$\endgroup\$
    – maxb
    Jun 12, 2019 at 7:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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