# Reversed Squares

Given an integer n, your task is to determine whether it is a perfect square that when reversed, is still a perfect square. You may assume n is always positive.

When numbers such as 100 (10x10) are reversed the result may have leading zeros (001) In this case, ignore the leading zeros and treat it as 1 (1x1).

## Test cases

1 => True
4 => True
9 => True
441 => True
1234567654321 => True
100 => True

3 => False
25 => False
1784 => False
18 => False


Shortest code wins!

• May we take input as a string? Jul 1, 2023 at 23:19
• This is A061457. Jul 1, 2023 at 23:49
• @Dadsdy sure, you can use a string Jul 2, 2023 at 12:59
• @JollyJoker Personally I feel like that's a "combining unreleated challenges" thing you should avoid. In some languages, generating the nth such number is simply a case of "nth index of integer generator filtered by" while in other languages (I'm thinking Retina 0.8.2 here) it's probably longer than the actual decision problem.
– Neil
Jul 2, 2023 at 18:50
• Strongly related to, and possible duplicate, of our basic challenges for checking if a number is square and reversing the input Jul 3, 2023 at 9:56

# Nekomata + -e, 6 bytes

¢B¢bÐ√


Attempt This Online!

¢B¢bÐ√
¢B      Integer to decimal digits in the reverse order
¢b    Decimal digits to integer
Ð   Pair
√  Square root; fails if not a perfect square


-e checks if there is a solution.

# 05AB1E, 5 bytes

Â)Å²P


Prints 1 if the condition is met, 0 otherwise.

### How it works

Â    # Implicit input: n. Push n and (digit-)reversed n
)    # Concatenate stack into an array
Å²   # Is square? Element-wise
P    # Product of array. Implicit print


# Vyxalg, 30 27 bitsv2, 3.75 3.375 bytes

Ṙ"∆²


Try it Online!

## Explained

Ṙ"∆²
Ṙ"    # the list [input, input reversed]
∆²  # vectorise is square
# g flag takes the minimum which in this case is equivalent to checking if both items are truthy


# Extended Dyalog APL, 1813 11 bytes

Thanks Adám for -5 bytes!

Takes input as a string.

≡∘⌊⍨∘√⍎,⍎⍤⌽


Explanation:

≡∘⌊⍨⍤√⍎,⍎⍤⌽
,    ⍝ make a list of
⍎     ⍝ the input parsed as a number
⍎⍤⌽ ⍝ and the reversed input parsed as a number,
√      ⍝ take the square root of both,
≡∘⌊⍨        ⍝ is that list equal to itself after you floor it?

• four bytes less if this april's fools update was real, you could just do ⌽ on the input :p Jul 2, 2023 at 12:41
• 13 bytes with some golfing and taking input as string: ≡∘⌊⍨.5*⍨⍎,⍎⍤⌽
Jul 2, 2023 at 17:04
• @Adám didn't consider input as a string would be valid Jul 2, 2023 at 17:09
• @DominicvanEssen this compares the list [sqrt(89), sqrt(98)] to the list [floor(sqrt(89)), floor(sqrt(98))] Jul 4, 2023 at 16:03
• if both elements are equal (ie both are perfect squares) Match (≡) is true, if either (or both) are different across the list it is false Jul 4, 2023 at 16:04

# Brachylog, 7 bytes

↔;?~^₂ᵐ


Try it online!

### Explanation

↔;?          The list [reversed(Input), Input]
~^₂ᵐ      Each element must be the square of some number


# Ruby, 42 bytes

->n{n**0.5%1+n.digits.join.to_i**0.5%1==0}


Try it online!

• > instead of == for reversed output to save a byte? Jul 4, 2023 at 13:43

# Factor + math.unicodeproject-euler.037.private, 46 bytes

-5 bytes thanks to @chunes

[ dup reverse-digits [ √ dup ⌊ = ] both? ]


Attempt This Online!

• [ ... ] Quotation (anonymous function) taking a number
• dup Duplicate so number is on the stack twice
• reverse-digits Reverse the digits of the copy
• [ ... ] both? Apply the quotation to both and check if both return t:
• √ Square root
• dup Push a copy
• ⌊ Round down
• = Are this and the original equal?

√ dup ⌊ = seems to be the shortest way to check if a number is a perfect square, since √ integer? doesn't work.

• -5 Jul 2, 2023 at 8:10

# Thunno 2M, 4 bytes

Requires v2.2.2: Try it

Ḳ,Æ²


# Thunno 2G!, 6 bytes

Works on old version of Thunno 2.

ḲNKƭ1%


Attempt This Online!

• Ḳ Bifurcate - duplicate and push reverse
• N Cast reversed to integer
• K The stack as a list
• ƭ The square root of each
• 1% Each mod 1 (0 if integer, nonzero else)
• G flag - maximum, 0 iff both are integers
• ! flag - logical not

This could be 4 bytes with m flag if we had an is_square built-in, or 5 bytes with same flag if we had an is_int built-in.

• 4 bytes (with M flag, requires v2.2.2) - sorry, I just had to show off my new site :p Jul 2, 2023 at 19:47
• @TheThonnu bravo, thanks Jul 2, 2023 at 19:52

# Lua, 26 bytes

n=...a=n^.5&n:reverse()^.5


Try it online!

Outputs using the exit code (0 is true, 1 is false).

This works because Lua can't do bitwise operators on non-integer numbers. If either n^.5 or n:reverse()^.5 is not an integer, the program will error.

# Scala, 6360 58 bytes

Saved 5 bytes thanks to the comments of @Shaggy and @Dominic van Essen

Golfed version. Try it online!

n=>(math.sqrt(n)+math.sqrt(n.toString.reverse.toLong))%1>0


Ungolfed version. Try it online!

object Main {
def main(args: Array[String]): Unit = {
def f(n: Long): Boolean = {
val sqrtOriginal = math.sqrt(n)
val sqrtReversed = math.sqrt(n.toString.reverse.toLong)

sqrtOriginal % 1 != 0 || sqrtReversed % 1 != 0
}

(0 until 10000).foreach(i => {
if (!f(i)) println(i)
})

val bigNumber = 1234567654321L
if (!f(bigNumber)) println(bigNumber)
}
}


• 60 bytes Jul 2, 2023 at 12:53
• 58 bytes (see my R answer for explanation)... Jul 4, 2023 at 13:53

# R, 5655 54 bytes

Edit: -1 byte after looking at pajonk's answer, and -1 byte by rearranging

\(x)(x^.5+(x%/%rev(z<-10^(0:log10(x)))%%10%*%z)^.5)%%1


Attempt This Online!

Outputs zero (falsy) for reversed-squares, non-zero (truthy) for other numbers.
Based on the fact that there does not exist any pair of integers x and y that are not both squares, but for which sqrt(x)+sqrt(y) is an integer: see here.

# Raku, 23 bytes

{sqrt($_|.flip)!~~/\./}  Try it online! $_ | .flip is an or-junction of the input number and its flipped string representation, which Raku treats as a number in nearly all contexts. sqrt applied to that or-junction produces another or-junction that contains the square roots of the two numbers above. Then the function returns whether it is not (!) the case that either of those square roots match (~~) the regular expression containing a period (/\./).

# Python 2, 39 bytes

lambda n:n**.5%1+int(n[::-1])**.5%1>0


Attempt This Online!

Reversed squares, reversed output. Returns False if input is a square and reversed square, True if not.

# Retina 0.8.2, 39 bytes

$¶$
O$^\G. .+$*
%A(^1|11\1)+$^¶$


Try it online! Link includes faster test cases. Explanation:

$¶$


Duplicate the input.

O$^\G.  Reverse the first copy. .+$*


Convert to unary.

%A(^1|11\1)+$ Delete square numbers. ^¶$


Check that both numbers were deleted.

# Fig, $$\8\log_{256}(96)\approx\$$ 6.585 bytes

!a%1mqw$ Try it online! $  # Inupt reversed
w   # Pair with the input (we now have [reversed(n), n])
mq    # Square root of each one
%1      # Modulo 1
a        # Any truthy (i.e. more than 0)
!         # Logical NOT


# Arturo, 42 bytes

$->n[0=+%sqrt do reverse~"|n|"1(sqrt n)%1]  Try it! $->n[                        ; a function taking an argument n
0=                       ; is zero equal to
+                        ; the sum between
%sqrt do reverse~"|n|"1  ; the square root of n reversed modulo one
(sqrt n)%1               ; and the square root of n modulo one
]                            ; end function


# Charcoal, 11 bytes

¬Σ﹪₂Ｉ⟦θ⮌θ⟧¹


Attempt This Online! Link is to verbose version of code. Outputs a Charcoal boolean, i.e. - if a member of A061457, nothing if not. Explanation: Uses floating-point arithmetic, so will go wrong on large enough inputs.

      θ     Input as a string
θ   Input as a string
⮌    Reversed
⟦   ⟧  Make into a list
Ｉ       Cast to integer
₂        Take the square root
﹪         Modulo
¹ Literal integer 1
Σ          Take the sum
¬           Logical Not
Implicitly print


15 bytes for a theoretically correct version which actually has worse performance because it creates a list of length of the input:

Ｎθ¬⁻⟦θ⮌θ⟧Ｘ…·⁰θ²


Try it online! Link is to verbose version of code. Explanation:

Ｎθ              First input as a number
θ          First input
θ        First input
⮌         Reversed
⟦   ⟧       Make into a list
⁻            Set difference with
…·    Inclusive range from
⁰   Literal integer 0 to
θ  First input
Ｘ      Vectorised raise to power
² Literal integer 2
¬             Logical Not
Implicitly print


23 bytes for a version that imports Python's math.isqrt:

⬤Ｉ⟦θ⮌θ⟧⁼ιＸ▷math.isqrtι²


Attempt This Online! Link is to verbose version of code. Explanation:

   θ                    Input as a string
θ                  Input as a string
⮌                   Reversed
⟦   ⟧                 Make into a list
Ｉ                      Cast to integer
⬤                       All values satisfy
ι  Current value
▷math.isqrt   Integer square root
Ｘ              Raised to power
² Literal integer 2
⁼                Equals
ι               Current value
Implicitly print


37 bytes for a version that uses the Babylonian method to find the integer square root and so will work with arbitrarily large integers in linear time on the number of digits:

⊞υＩ⟦θ⮌θ⟧Ｗ⁼¹№υ⌊υ⊞υＥ⌊υ÷⁺κ÷§⌈υλκ²⁼⌈υＸ⌊υ²


Try it online! Link is to verbose version of code. Explanation:

⊞υＩ⟦θ⮌θ⟧


Start with the input and its reversal both as the target and the initial estimate.

Ｗ⁼¹№υ⌊υ


Repeat until the estimate converges.

⊞υＥ⌊υ÷⁺κ÷§⌈υλκ²


Get the next estimate.

⁼⌈υＸ⌊υ²


Check that the square of the final estimate gives the target.

Java 8, 83 bytes

n->Math.sqrt(n)%1==0&Math.sqrt(new Long(new StringBuilder(""+n).reverse()+""))%1==0


this lambda can be used for a functional interface such as IntPredicate

Try It Online

• I forgot that String doesn't directly have a reverse method and almost threw my laptop at a wall Jul 2, 2023 at 15:10
• StringBuilder can be StringBuffer for -1 byte. Jul 3, 2023 at 7:22
• And a general tip for TIO: you can split your program into a header, code, and footer, and only modify the code (which also shows the byte-count at the right-hand side) when you golf it further. :) Like this. Jul 3, 2023 at 7:36
• Based on @DominicVanEssen's R answer you can golf it to n->Math.sqrt(n)%1+Math.sqrt(new Long(new StringBuffer(""+n).reverse()+""))%1>0: 78 bytes (reversed output) Jul 4, 2023 at 14:12

# R, 59 58 bytes

\(n,t=10^(1:nchar(n)-1))n^.5%%1|(n%/%t%%10%*%rev(t))^.5%%1


Attempt This Online!

\(n,t=10^(1:nchar(n)-1))any(c(n,n%/%t%%10%*%rev(t))^.5%%1)


Attempt This Online!

Outputs flipped TRUE/FALSE.

# Excel, 80 bytes

=LET(
a,LEN(A1),
b,HSTACK(A1,CONCAT(MID(A1,1+a-SEQUENCE(a),1)))^0.5,
AND(INT(b)=b)
)


# MathGolf, 5 bytes

‼°x°╓


Try it online.

Or alternatively:

xαm°╓


Try it online.

Explanation:

‼     # Apply the next two operators separately on the current stack:
# (which will use the implicit input-integer)
°    #  Check if it's a perfect square
x   #  Reverse it
°  # Check if this top reversed integer is a perfect square as well
╓ # Pop both, and get the minimum of the two
# (which will be truthy if both were truthy; or falsey if either/both were falsey)
# (after which the entire stack is output implicitly as result)

x     # Reverse the (implicit) input-integer
α    # Pair the top two values, which is the (implicit) input and the reversed input
m   # Map over this pair:
°  #  Check for both whether it's a perfect square
╓ # Pop the square, and push its minimum
# (which will be truthy if both were truthy; or falsey if either/both were falsey)
# (after which the entire stack is output implicitly as result)

• Oh I love that usage of ‼. It's one of the things I like the most about mathgolf (despite the fact I've only ever played around with it once or twice). Best stack operator imo :p Jul 3, 2023 at 9:06

# Jelly, 6 bytes

ṚƬḌ½ḞƑ


Try it online!

ṚƬ        Reverse while unique.
Ḍ       Vectorizing convert from decimal.
½      Vectorizing square root.
Ƒ    Is the entire list of results unchanged by
Ḟ     vectorizing floor?


# Javascript, 4340 42 Bytes

Thanks to @Arnauld for -3 Bytes (-2 from backticks (which I forgot), -1 from inverse output)

n=>[...n].reverse().join**.5%1*n**.5%1>0


TIO

• Failed on 11.
– tsh
Jul 3, 2023 at 2:51

# JavaScript (V8), 40 bytes

g=x=>x**.5%1||g([...x].reverse().join)


Try it online!

Throws as true and not throw as false.

Here assumes a reasonable stack(actually <1KB is enough, number is stored in heap) so it's allowed

# C (gcc), 66 bytes

a;g(n){a=sqrt(n);a=a*a-n;}f(n){for(g(n);n;n/=10)a+=9*a+n%10;g(a);}


Try it online!

Strongly pushed Noodle9's

• I think it would be more accurate to either include the f function in your solution or to say that this returns a float for false and throws a stack overflow error (or loops forever) for true. If opting for the latter then I would strongly suggest asking whether that is an acceptable form of output. Jul 3, 2023 at 15:16

# Racket - 155 bytes

#lang racket
(define(m v)(let([r(string->number(list->string(reverse(string->list(number->string v)))))][? integer?])(and(?(sqrt v))(?(sqrt r)))))(m(read))


Try it online!

## Explanation

On line one, we have Racket's required language statement, #lang racket, This just imports all of the statements/functions used in the language (like define and read, as well as wrapping our program into a module.

The second line is where the main program lies. We define a function named m. This function received an integer v as an argument. We then reverse the integer to obtain an integer named r. We take the square roots of both v and r and see whether they are integers or not. If both checks return true, then the number is a Reversed Perfect Square.

Here's the program in all its glory. In the shortened form, I embedded reverse-number as part of main's local scope. But to make it easier to read and understand, I made it its own function:

#lang racket

(define (reverse-number value)
(string->number (list->string (reverse (string->list (number->string value))))))

(define (main value)
(let ([reversed-value (reverse-number value)])
(and (integer? (sqrt value))
(integer? (sqrt reversed-value)))))



As of right now, Racket doesn't have a reverse-string or string-reverse function. So, the only way I could reverse the number was to first convert the number to a string, then convert the string to a list, reverse the list, convert the list to a string, then convert the string to a number. But if we did have a string-reverse function, I would've written:

(string->number (string-reverse (number->string value)))


Also, while I could've used quotient and remainder, it ended up bumping the number of bytes up by a tad bit (I got 180).

Example usages of main:

;; An infinite loop that loops over all natural numbers [1..] and finds all RPSs
(for ([i (in-naturals)] #:when (main i))
(displayln i))


# Pyth, 10 9 bytes

-1 byte by realizing that v automatically vectorizes

sMI@R2v_B


Try it online!

### Explanation

sMI@R2v_BQ    # implicitly add Q
# implicitly assign Q = eval(input())
_BQ    # bifurcate Q over reversal
v       # eval (automatically vectorizes)
@R2        # map each to their square roots
I           # check for invariance over
sM            # converting the entire list into integers


# Japt, 11 bytes

[UUsÔ]m¬ev1


PD: Definitely can be golfed down

Try it

# Japt-¡, 11 bytes

¬v1 ©UsÔ¬v1


Try it

# Japt-E!, 8 bytes

Based on l4m2's solution but with correct output.

¬%1ªßUìÔ


Try it

# Wolfram Language (Mathematica), 35 bytes

AtomQ@Tr@Sqrt@{#,IntegerReverse@#}&


Try it online!

# C (gcc), 75 73 67 bytes

b;f(n){b=sqrt(n);for(b=b*b-n;n;n/=10)b+=9*b+n%10;n=sqrt(b);b-=n*n;}


Try it online!

Saved 2 8 bytes thanks to c--!!!

• 67 bytes fixing your last attempt, the only difference is n-b*b -> b*b-n, like in l4m2's answer
– c--
Jul 8, 2023 at 2:44
• @c-- Fantastic - thanks! :D Jul 9, 2023 at 11:45