21
\$\begingroup\$

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!

\$\endgroup\$
7
  • \$\begingroup\$ May we take input as a string? \$\endgroup\$
    – Dadsdy
    Jul 1, 2023 at 23:19
  • 3
    \$\begingroup\$ This is A061457. \$\endgroup\$
    – Arnauld
    Jul 1, 2023 at 23:49
  • \$\begingroup\$ @Dadsdy sure, you can use a string \$\endgroup\$ Jul 2, 2023 at 12:59
  • 1
    \$\begingroup\$ @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. \$\endgroup\$
    – Neil
    Jul 2, 2023 at 18:50
  • 1
    \$\begingroup\$ Strongly related to, and possible duplicate, of our basic challenges for checking if a number is square and reversing the input \$\endgroup\$
    – Shaggy
    Jul 3, 2023 at 9:56

34 Answers 34

6
\$\begingroup\$

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.

\$\endgroup\$
5
\$\begingroup\$

05AB1E, 5 bytes

Â)ŲP

Prints 1 if the condition is met, 0 otherwise.

Try it online! Or verify all test cases.

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
\$\endgroup\$
4
\$\begingroup\$

Vyxal g, 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 
\$\endgroup\$
4
\$\begingroup\$

Extended Dyalog APL, 18 13 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?
\$\endgroup\$
9
  • \$\begingroup\$ four bytes less if this april's fools update was real, you could just do on the input :p \$\endgroup\$
    – RubenVerg
    Jul 2, 2023 at 12:41
  • \$\begingroup\$ 13 bytes with some golfing and taking input as string: ≡∘⌊⍨.5*⍨⍎,⍎⍤⌽ \$\endgroup\$
    – Adám
    Jul 2, 2023 at 17:04
  • \$\begingroup\$ @Adám didn't consider input as a string would be valid \$\endgroup\$
    – RubenVerg
    Jul 2, 2023 at 17:09
  • 1
    \$\begingroup\$ @DominicvanEssen this compares the list [sqrt(89), sqrt(98)] to the list [floor(sqrt(89)), floor(sqrt(98))] \$\endgroup\$
    – RubenVerg
    Jul 4, 2023 at 16:03
  • 1
    \$\begingroup\$ 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 \$\endgroup\$
    – RubenVerg
    Jul 4, 2023 at 16:04
4
\$\begingroup\$

Brachylog, 7 bytes

↔;?~^₂ᵐ

Try it online!

Explanation

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

Ruby, 42 bytes

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

Try it online!

\$\endgroup\$
1
  • 2
    \$\begingroup\$ > instead of == for reversed output to save a byte? \$\endgroup\$ Jul 4, 2023 at 13:43
3
\$\begingroup\$

Factor + math.unicode project-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.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ -5 \$\endgroup\$
    – chunes
    Jul 2, 2023 at 8:10
3
\$\begingroup\$

Thunno 2 M, 4 bytes

Requires v2.2.2: Try it

Ḳ,Ʋ

Thunno 2 G!, 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.

\$\endgroup\$
2
  • \$\begingroup\$ 4 bytes (with M flag, requires v2.2.2) - sorry, I just had to show off my new site :p \$\endgroup\$
    – The Thonnu
    Jul 2, 2023 at 19:47
  • 1
    \$\begingroup\$ @TheThonnu bravo, thanks \$\endgroup\$
    – noodle man
    Jul 2, 2023 at 19:52
3
\$\begingroup\$

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.

\$\endgroup\$
3
\$\begingroup\$

Scala, 63 60 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)
  }
}

\$\endgroup\$
2
3
\$\begingroup\$

R, 56 55 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.

\$\endgroup\$
3
\$\begingroup\$

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 (/\./).

\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

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
\$\endgroup\$
2
\$\begingroup\$

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
\$\endgroup\$
2
\$\begingroup\$

Charcoal, 11 bytes

¬Σ﹪₂I⟦θ⮌θ⟧¹

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
    I       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:

Nθ¬⁻⟦θ⮌θ⟧X…·⁰θ²

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

Nθ              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
         X      Vectorised raise to power
              ² Literal integer `2`
  ¬             Logical Not
                Implicitly print

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

⬤I⟦θ⮌θ⟧⁼ιX▷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
 I                      Cast to integer
⬤                       All values satisfy
                     ι  Current value
          ▷math.isqrt   Integer square root
         X              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:

⊞υI⟦θ⮌θ⟧W⁼¹№υ⌊υ⊞υE⌊υ÷⁺κ÷§⌈υλκ²⁼⌈υX⌊υ²

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

⊞υI⟦θ⮌θ⟧

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

W⁼¹№υ⌊υ

Repeat until the estimate converges.

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

Get the next estimate.

⁼⌈υX⌊υ²

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

\$\endgroup\$
2
\$\begingroup\$

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

\$\endgroup\$
4
  • 3
    \$\begingroup\$ I forgot that String doesn't directly have a reverse method and almost threw my laptop at a wall \$\endgroup\$
    – Jack Ammo
    Jul 2, 2023 at 15:10
  • 1
    \$\begingroup\$ StringBuilder can be StringBuffer for -1 byte. \$\endgroup\$ Jul 3, 2023 at 7:22
  • 2
    \$\begingroup\$ 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. \$\endgroup\$ Jul 3, 2023 at 7:36
  • \$\begingroup\$ 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) \$\endgroup\$ Jul 4, 2023 at 14:12
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

Excel, 80 bytes

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

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)
\$\endgroup\$
1
  • 2
    \$\begingroup\$ 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 \$\endgroup\$
    – lyxal
    Jul 3, 2023 at 9:06
2
\$\begingroup\$

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?
\$\endgroup\$
2
\$\begingroup\$

Javascript, 43 40 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

\$\endgroup\$
1
  • 2
    \$\begingroup\$ Failed on 11. \$\endgroup\$
    – tsh
    Jul 3, 2023 at 2:51
2
\$\begingroup\$

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

\$\endgroup\$
1
  • \$\begingroup\$ 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. \$\endgroup\$
    – Shaggy
    Jul 3, 2023 at 15:16
2
\$\begingroup\$

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)))))

(main (read))

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))
\$\endgroup\$
2
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

Japt, 11 bytes

[UUsÔ]m¬ev1

PD: Definitely can be golfed down

Try it


Japt , 11 bytes

¬v1 ©UsÔ¬v1

Try it

\$\endgroup\$
1
\$\begingroup\$

Japt -E!, 8 bytes

Based on l4m2's solution but with correct output.

¬%1ªßUìÔ

Try it

\$\endgroup\$
1
\$\begingroup\$

Wolfram Language (Mathematica), 35 bytes

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

Try it online!

\$\endgroup\$
1
\$\begingroup\$

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--!!!

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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