20
\$\begingroup\$

An Automorphic number is a number which is a suffix of its square in base 10. This is sequence A003226 in the OEIS.

Your Task:

Write a program or function to determine whether an input is an Automorphic number.

Input:

An integer between 0 and 10^12 (inclusive), that may or may not be an Automorphic number.

Output:

A truthy/falsy value indicating whether or not the input is an Automorphic number.

Examples:

0           -> truthy
1           -> truthy
2           -> falsy
9376        -> truthy
8212890625  -> truthy

Scoring:

This is , lowest score in bytes wins.

\$\endgroup\$
  • 9
    \$\begingroup\$ Btw the limit of 1e12 means submissions will need to handle numbers up to 1e24, which is an 80-bit number. If handling numbers that large is a hard requirement, many of the exiting answers are invalid. \$\endgroup\$ – Dennis Jun 24 '17 at 19:59
  • \$\begingroup\$ Need we handle numbers that would lead to precision issues in our chosen language? \$\endgroup\$ – Shaggy Jun 24 '17 at 21:50
  • \$\begingroup\$ Provided that you don't abuse the standard loophole about that, then that would be fine. \$\endgroup\$ – Gryphon - Reinstate Monica Jun 24 '17 at 22:49
  • \$\begingroup\$ Specifically, this loophole \$\endgroup\$ – Gryphon - Reinstate Monica Jun 24 '17 at 22:53
  • \$\begingroup\$ It's been a loooong day and I am very, very tired but your comments read to me as validating my JS solution. Could you confirm that? (No issue deleting if not) \$\endgroup\$ – Shaggy Jun 24 '17 at 23:40

33 Answers 33

11
\$\begingroup\$

Brachylog, 5 bytes

~√a₁?

Try it online!

How it works

~√a₁?
~√      the input is the square root of a number
  a₁    whose suffix is
    ?   the input
\$\endgroup\$
  • \$\begingroup\$ No, it says if x is a suffix of its square. \$\endgroup\$ – WGroleau Jun 24 '17 at 23:18
  • 2
    \$\begingroup\$ √a₁? Why not? \$\endgroup\$ – totallyhuman Jun 25 '17 at 1:12
38
\$\begingroup\$

Python 2, 24 bytes

lambda n:`n*1L`in`n**2L`

Try it online!

For the first time in history, Python 2's appending an L to the repr of longs is a feature rather than a bug.

The idea is to check if say, 76^2=5776 ends in 76 by checking if 76L is a substring of 5776L. To make the L appear for non-huge numbers, we multiply by 1L or have 2L as the exponent, since an arithmetic operation with a long with produces a long.

\$\endgroup\$
9
\$\begingroup\$

Python 2, 31 bytes

Out-golfed by xnor... (this happens every single time) >< But hey, it's surprisingly Pythonic for .

People don't tend to remember Python has str.endswith()...

lambda n:str(n*n).endswith(`n`)

Try it online!

\$\endgroup\$
  • \$\begingroup\$ Can't you use `n*n` to convert number into string? \$\endgroup\$ – Downgoat Jun 24 '17 at 21:33
  • \$\begingroup\$ @Downgoat That tacks an 'L' on to longer numbers. \$\endgroup\$ – totallyhuman Jun 24 '17 at 21:35
  • \$\begingroup\$ @totallyhuman Good point, I missed its use. \$\endgroup\$ – isaacg Jun 25 '17 at 0:37
5
\$\begingroup\$

05AB1E, 5 bytes

n.s¹å

Try it online!

\$\endgroup\$
  • 6
    \$\begingroup\$ I'd upvote If I knew how it worked. \$\endgroup\$ – isaacg Jun 25 '17 at 0:37
  • \$\begingroup\$ I suppose, n is square, .s is suffixes, ¹ is the input, and å tests for membership @isaacg \$\endgroup\$ – Conor O'Brien Jun 25 '17 at 2:47
  • \$\begingroup\$ @isaacg What Conor said...didn't have time to add explanation. \$\endgroup\$ – Erik the Outgolfer Jun 25 '17 at 5:44
5
\$\begingroup\$

Retina, 44 bytes

$
;918212890625;81787109376;0;1;
^(\d+;).*\1

Try it online!

There are exactly 4 solutions to the 10-adic equation x*x = x.

\$\endgroup\$
  • 1
    \$\begingroup\$ Uh? Aren't all these numbers valid solutions? \$\endgroup\$ – Leo Jun 25 '17 at 18:33
  • \$\begingroup\$ @Leo No, they aren't. Obviously 5*5 != 5. However, you can notice some pattern in the numbers you linked to. The 4 solutions are: 0, 1, ...59918212890625, ...40081787109376 (p-adic numbers go infinitely to the left). The numbers you linked to are suffixes of the 4 numbers. \$\endgroup\$ – Leaky Nun Jun 25 '17 at 22:36
  • \$\begingroup\$ Oh ok, thank you, I didn't know about p-adic numbers \$\endgroup\$ – Leo Jun 25 '17 at 22:52
4
\$\begingroup\$

Alice, 17 bytes

/o.z/#Q/
@in.*.L\

Try it online!

Outputs nothing (which is falsy in Ordinal mode) or Jabberwocky (which is non-empty and therefore truthy in Ordinal mode; it's also the canonical truthy string value).

Explanation

/.../#./
....*..\

This is a slight modification of the general framework for linear Ordinal mode programs. The / in the middle is used to have a single operator in Cardinal mode in between (the *) and then we need the # to skip it in Ordinal mode on the way back. The linear program is then:

i..*.QLzno@

Let's go through that:

i    Read all input as a string and push it to the stack.
..   Make two copies.
*    This is run in Cardinal mode, so it implicitly converts the top two
     copies to their integer value and multiplies them to compute the square.
.    Implicitly convert the square back to a string and make a copy of it.
Q    Reverse the stack to bring the input on top of the two copies of its square.
L    Shortest common supersequence. This pops the input and the square from
     the top of the stack and pushes the shortest string which begins with
     the square and ends with the input. Iff the square already ends with the
     input, this gives us the square, otherwise it gives us some longer string.
z    Drop. Pop the SCS and the square. If the square contains the SCS (which
     would mean they're equal), this removes everything up to the SCS from
     the square. In other words, if the SCS computation left the square
     unchanged, this gives us an empty string. Otherwise, it gives us back
     the square.
n    Logical not. Turns the empty string into "Jabberwocky" and everything
     else into an empty string.
o    Print the result.
@    Terminate the program.
\$\endgroup\$
4
\$\begingroup\$

Mathematica, 31 bytes

Mod[#^2,10^IntegerLength@#]==#&

Try it online! Mathics prints an extra message but the answer is correct

\$\endgroup\$
4
\$\begingroup\$

Python 2, 37 33 30 29 bytes

lambda n:n*~-n%10**len(`n`)<1

Saved 4 bytes thanks to @LeakyNun. Saved 3 bytes by noticing that the input is lower than 10^12 so n doesn't end with an "L". Saved 1 byte thanks to @Dennis because I miscounted in the first place.

Try it online! (TIO link courtesy of @Dennis).

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

C (gcc), 57 bytes

f(__int128 n){n=n*n%(long)pow(10,printf("%u",n))==n;}

Based on @betseg's answer, this is a function that returns 1 or 0. It produces garbage output to STDOUT, which is allowed by default.

The score contains +4 bytes for the compiler flag -lm.

Try it online!

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

Ruby, 22 bytes

->n{"#{n*n}"=~/#{n}$/}

Try it online!

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

C# (.NET Core), 47 bytes

n=>$"{BigInteger.Multiply(n,n)}".EndsWith(n+"")

Try it online!

\$\endgroup\$
  • \$\begingroup\$ Isn't is possible to change $"{n}" to n+""? Also, could you perhaps add a TryItOnline-link? Oh, and this is a snippet, not a function/program. So you should add n=> in front of it. \$\endgroup\$ – Kevin Cruijssen Jun 26 '17 at 9:19
  • 1
    \$\begingroup\$ @KevinCruijssen Done! Is it possible to simplify even further? TIL you can convert an int to string using n+"". Thanks! \$\endgroup\$ – kakkarot Jun 26 '17 at 10:26
  • \$\begingroup\$ You don't need the bool f(long n) or trailing semi-colon for lambda answers in C#, Java, etc. Just n=>$"{BigInteger.Multiply(n,n)}".EndsWith(n+"") is enough. :) And I almost forgot: Welcome to PPCG! \$\endgroup\$ – Kevin Cruijssen Jun 26 '17 at 10:28
  • \$\begingroup\$ @KevinCruijssen Thank you! \$\endgroup\$ – kakkarot Jun 26 '17 at 10:29
  • \$\begingroup\$ You're welcome! :) Oh, and here is your TIO-link converter to use just n=>, by using a System.Func. \$\endgroup\$ – Kevin Cruijssen Jun 26 '17 at 10:33
3
\$\begingroup\$

Charcoal, 12 11 bytes

I¬⌕⮌IXIθ²⮌θ

Try it online!

Returns False as falsey and True as truthy.

  • 1 byte saved thanks to ASCII-only! (How could I miss the Power function?)
\$\endgroup\$
  • \$\begingroup\$ This returns 0 for 10, 100, ... 1 for 50, 60... 2 for 760, 3792... \$\endgroup\$ – Neil Jun 24 '17 at 23:52
  • \$\begingroup\$ @Neil fixed now, thanks! \$\endgroup\$ – Charlie Jun 25 '17 at 0:25
  • 2
    \$\begingroup\$ I thought Charcoal was only good for ASCII art. ಠ_ಠ \$\endgroup\$ – totallyhuman Jun 25 '17 at 0:54
  • \$\begingroup\$ 11 bytes \$\endgroup\$ – ASCII-only Jul 27 '17 at 4:56
  • \$\begingroup\$ @totallyhuman It still is, look at all the normal golflangs with <6 byte solutions \$\endgroup\$ – ASCII-only Jul 27 '17 at 4:57
2
\$\begingroup\$

JavaScript (ES6), 23 bytes

n=>`${n*n}`.endsWith(n)

Try it

Wrote this Snippet up on my phone, so please edit if it's not working correctly.

f=
n=>`${n*n}`.endsWith(n)
oninput=_=>o.innerText=f(+i.value);o.innerText=f(i.value=1)
<input id=i type=number><pre id=o>

\$\endgroup\$
  • \$\begingroup\$ This fails for 212890625 due to precision issues. \$\endgroup\$ – Dennis Jun 24 '17 at 20:22
  • \$\begingroup\$ Thanks for pointing that out, @Dennis; this was a quicky while on a smoke break so I (stupidly) only checked the test cases. Will ask for clarification on precision errors and delete when I get back to a computer, if necessary. \$\endgroup\$ – Shaggy Jun 24 '17 at 21:26
2
\$\begingroup\$

Jelly, 6 bytes

²ṚwṚ⁼1

Try it online!

\$\endgroup\$
  • \$\begingroup\$ Nice job outgolfing me. \$\endgroup\$ – Leaky Nun Jun 24 '17 at 19:07
  • \$\begingroup\$ @LeakyNun And I would've even tied Brachylog if I could've used ... \$\endgroup\$ – Erik the Outgolfer Jun 24 '17 at 19:08
2
\$\begingroup\$

Kotlin, 36 bytes

fun a(i:Int)="${i*i}".endsWith("$i")
\$\endgroup\$
2
\$\begingroup\$

C, 77 + 4 (-lm) = 81 bytes

#import<tgmath.h>
i;f(long double n){i=fmod(n*n,pow(10,(int)log10(n)+1))==n;}

Try it online!

\$\endgroup\$
  • 2
    \$\begingroup\$ Can use n*n for pow(n,2) and save 5 bytes. \$\endgroup\$ – Noodle9 Jun 25 '17 at 9:06
2
\$\begingroup\$

R, 28 bytes

pryr::f(x^2%%10^nchar(x)==x)

Creates a function:

function (x) 
x^2%%10^nchar(x) == x

Takes the modulus of x^2 such that we keep the last digits, which we compare to x.

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

Perl 5, 15 + 1 (-p) = 16 bytes

$_=$_**2=~/$_$/

Try it online!

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

Jelly, 7 bytes

²_ọæċ⁵$

Try it online!

Positive number for yes, 0 for no.

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

Retina, 47 33 bytes

14 bytes thanks to Martin Ender.

.+
$*
$
¶$`
\G1
$%_
M%`1
(.+)¶\1$

Try it online!

\$\endgroup\$
  • \$\begingroup\$ I need to learn $%... \$\endgroup\$ – Neil Jun 24 '17 at 23:44
1
\$\begingroup\$

PHP, 41 bytes

<?=preg_match("#$argn$#",bcpow($argn,2));

PHP Sandbox Online

PHP, 42 bytes

without Regex

<?=strtr(bcpow($argn,2),[$argn=>X])[-1]>A;

PHP, 44 bytes

Use the levenshtein distance

<?=!levenshtein($argn,bcpow($argn,2),0,1,1);
\$\endgroup\$
1
\$\begingroup\$

Dyvil, 26 bytes

x=>"\(x*x)".endsWith"\(x)"

Usage:

let f: int->boolean = x=>"\(x*x)".endsWith"\(x)"
print(f 20) // false
\$\endgroup\$
1
\$\begingroup\$

Batch, 122 bytes

@set/an=%1,t=f=1
:l
@set/at+=t,f*=5,n/=10
@if %n% gtr 0 goto l
@cmd/cset/a"(!(%1%%t)|!(~-%1%%t))&(!(%1%%f)|!(~-%1%%f))

Algorithm is limited only by the integer type used for variables. In the case of Batch, this is 32-bit signed integers, so the maximum is 2147483647. Works by testing both n and n-1 for necessary powers of 2 and 5 as factors. (Except when n is 0 or 1, n and n-1 will have one factor each.)

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

><>, 30 bytes

1&0}\{n;
:&(?\:::*&a*:&%={+}:&

Try it online, or watch it at the fish playground!

Assumes the input number x is already on the stack.

Explanation: The fish takes the quotient of x2 by increasing powers of 10, and counts how many times this equals x. When the power of 10 gets larger than x, it prints the count and halts. The count will be 1 if x is automorphic, and 0 if it isn't.

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

Pari/GP, 23 bytes

n->n^2%10^#digits(n)==n

Try it online!

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

Pyth, 10 9 bytes

-1 byte thanks to isaacg.

x_`^vz2_z

Returns 0 when the number is automorphic, anything else if it is not.

Test it online!

Explanations

x_`^vz2_z

   ^vz2      # Evaluate the input to a number, compute the square
  `          # Convert the squared number to a string
 _           # Reverse it
x      _z    # Find the index of the first occurrence of the reversed input in the reversed square. That's basically equivalent of doing an endswith() in Python
             # Implicit input of the index. If 0, then the reversed square starts with the reversed input
\$\endgroup\$
  • 1
    \$\begingroup\$ ` is convert to string. \$\endgroup\$ – isaacg Jun 25 '17 at 1:34
1
\$\begingroup\$

Rexx (Regina), 48 bytes

numeric digits 25
arg n
say right(n*n,length(n))=n

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Perl 6, 15 bytes

{$^x²~~/$^x$/}

Try it online!

Returns a truthy Match object for automorphic inputs, and a falsy Nil value for other numbers.

\$\endgroup\$
0
\$\begingroup\$

Clojure, 59 bytes

#(apply = true(map =(reverse(str %))(reverse(str(* % %)))))

This seems overly verbose.

\$\endgroup\$
  • \$\begingroup\$ Why not just go with #(.endsWith(str(* % %))(str %)) ? \$\endgroup\$ – cliffroot Jun 26 '17 at 9:52
  • \$\begingroup\$ Oh true, it is so easy to forget about Java built-ins. \$\endgroup\$ – NikoNyrh Jun 26 '17 at 10:55
0
\$\begingroup\$

MATL, 10 bytes

UUVG36hXXn

This works for numbers up to floor(sqrt(2^53)), as per double precision limitations.

Output is a positive number (which is truthy) if automorphic, or empty (which is falsy) if not.

Try it online!

Explanation

Funny that this answer uses the two overloaded versions of U: with string input it evaluates as a number, and with number input it computes the square.

U      % Implicitly input a string. Evaluate as a number
U      % Square of number
V      % Convert number to string representation
G      % Push input string again
36h    % Post-pend '$'
XX     % Regexp match. Gives cell array of matching substrings.
n      % Number of elements. Implicitly display
\$\endgroup\$

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.