Am I an Automorphic Number?

20

2

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.

Gryphon

Posted 2017-06-24T18:54:09.697

Reputation: 6 697

9Btw 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. – Dennis – 2017-06-24T19:59:49.373

Need we handle numbers that would lead to precision issues in our chosen language? – Shaggy – 2017-06-24T21:50:23.120

Provided that you don't abuse the standard loophole about that, then that would be fine. – Gryphon – 2017-06-24T22:49:35.207

Specifically, this loophole

– Gryphon – 2017-06-24T22:53:38.727

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) – Shaggy – 2017-06-24T23:40:03.053

Consider that confirmed. 10^9 (which is what I'm pretty sure your program stops working after) is good enough. I just don't want things that only work on numbers up to, say 1,000. – Gryphon – 2017-06-24T23:42:35.347

Answers

11

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

Leaky Nun

Posted 2017-06-24T18:54:09.697

Reputation: 45 011

No, it says if x is a suffix of its square. – WGroleau – 2017-06-24T23:18:57.320

2√a₁? Why not? – totallyhuman – 2017-06-25T01:12:57.297

38

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.

xnor

Posted 2017-06-24T18:54:09.697

Reputation: 115 687

9

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!

totallyhuman

Posted 2017-06-24T18:54:09.697

Reputation: 15 378

Can't you use \n*n`` to convert number into string? – Downgoat – 2017-06-24T21:33:35.447

@Downgoat That tacks an 'L' on to longer numbers. – totallyhuman – 2017-06-24T21:35:57.390

@totallyhuman Good point, I missed its use. – isaacg – 2017-06-25T00:37:12.793

5

05AB1E, 5 bytes

n.s¹å

Try it online!

Erik the Outgolfer

Posted 2017-06-24T18:54:09.697

Reputation: 38 134

6I'd upvote If I knew how it worked. – isaacg – 2017-06-25T00:37:45.510

I suppose, n is square, .s is suffixes, ¹ is the input, and å tests for membership @isaacg – Conor O'Brien – 2017-06-25T02:47:36.177

@isaacg What Conor said...didn't have time to add explanation. – Erik the Outgolfer – 2017-06-25T05:44:42.707

5

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.

Leaky Nun

Posted 2017-06-24T18:54:09.697

Reputation: 45 011

1

Uh? Aren't all these numbers valid solutions?

– Leo – 2017-06-25T18:33:04.127

@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. – Leaky Nun – 2017-06-25T22:36:18.967

Oh ok, thank you, I didn't know about p-adic numbers – Leo – 2017-06-25T22:52:49.763

4

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

nore

Posted 2017-06-24T18:54:09.697

Reputation: 436

4

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.

Martin Ender

Posted 2017-06-24T18:54:09.697

Reputation: 184 808

4

Mathematica, 31 bytes

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

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

J42161217

Posted 2017-06-24T18:54:09.697

Reputation: 15 931

3

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!

Dennis

Posted 2017-06-24T18:54:09.697

Reputation: 196 637

3

Ruby, 22 bytes

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

Try it online!

epidemian

Posted 2017-06-24T18:54:09.697

Reputation: 531

3

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

Charlie

Posted 2017-06-24T18:54:09.697

Reputation: 11 448

This returns 0 for 10, 100, ... 1 for 50, 60... 2 for 760, 3792... – Neil – 2017-06-24T23:52:59.873

@Neil fixed now, thanks! – Charlie – 2017-06-25T00:25:52.467

2I thought Charcoal was only good for ASCII art. ಠ_ಠ – totallyhuman – 2017-06-25T00:54:22.957

11 bytes – ASCII-only – 2017-07-27T04:56:20.127

@totallyhuman It still is, look at all the normal golflangs with <6 byte solutions – ASCII-only – 2017-07-27T04:57:05.893

3

C# (.NET Core), 47 bytes

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

Try it online!

kakkarot

Posted 2017-06-24T18:54:09.697

Reputation: 269

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.

– Kevin Cruijssen – 2017-06-26T09:19:11.987

1@KevinCruijssen Done! Is it possible to simplify even further? TIL you can convert an int to string using n+"". Thanks! – kakkarot – 2017-06-26T10:26:20.463

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! – Kevin Cruijssen – 2017-06-26T10:28:03.363

@KevinCruijssen Thank you! – kakkarot – 2017-06-26T10:29:30.360

You're welcome! :) Oh, and here is your TIO-link converter to use just n=>, by using a System.Func.

– Kevin Cruijssen – 2017-06-26T10:33:38.247

@KevinCruijssen Edited. Thank you! – kakkarot – 2017-06-26T10:36:57.137

2

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>

Shaggy

Posted 2017-06-24T18:54:09.697

Reputation: 24 623

This fails for 212890625 due to precision issues. – Dennis – 2017-06-24T20:22:05.257

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. – Shaggy – 2017-06-24T21:26:04.500

2

Jelly, 6 bytes

²ṚwṚ⁼1

Try it online!

Erik the Outgolfer

Posted 2017-06-24T18:54:09.697

Reputation: 38 134

Nice job outgolfing me. – Leaky Nun – 2017-06-24T19:07:32.190

@LeakyNun And I would've even tied Brachylog if I could've used ... – Erik the Outgolfer – 2017-06-24T19:08:43.133

2

Kotlin, 36 bytes

fun a(i:Int)="${i*i}".endsWith("$i")

weston

Posted 2017-06-24T18:54:09.697

Reputation: 371

2

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!

betseg

Posted 2017-06-24T18:54:09.697

Reputation: 8 493

2Can use n*n for pow(n,2) and save 5 bytes. – Noodle9 – 2017-06-25T09:06:43.160

2

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.

JAD

Posted 2017-06-24T18:54:09.697

Reputation: 2 898

2

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

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

Try it online!

Xcali

Posted 2017-06-24T18:54:09.697

Reputation: 7 671

1

Jelly, 7 bytes

²_ọæċ⁵$

Try it online!

Positive number for yes, 0 for no.

Leaky Nun

Posted 2017-06-24T18:54:09.697

Reputation: 45 011

1

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

Jörg Hülsermann

Posted 2017-06-24T18:54:09.697

Reputation: 13 026

1

Retina, 47 33 bytes

14 bytes thanks to Martin Ender.

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

Try it online!

Leaky Nun

Posted 2017-06-24T18:54:09.697

Reputation: 45 011

I need to learn $%... – Neil – 2017-06-24T23:44:28.743

1

Dyvil, 26 bytes

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

Usage:

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

Clashsoft

Posted 2017-06-24T18:54:09.697

Reputation: 835

1

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

Neil

Posted 2017-06-24T18:54:09.697

Reputation: 95 035

1

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

Jim

Posted 2017-06-24T18:54:09.697

Reputation: 1 442

1``` is convert to string. – isaacg – 2017-06-25T01:34:15.297

1

><>, 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.

Not a tree

Posted 2017-06-24T18:54:09.697

Reputation: 3 106

1

Pari/GP, 23 bytes

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

Try it online!

alephalpha

Posted 2017-06-24T18:54:09.697

Reputation: 23 988

1

Rexx (Regina), 48 bytes

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

Try it online!

theblitz

Posted 2017-06-24T18:54:09.697

Reputation: 1 201

0

Python 3, 40 35 bytes

-@Nick A saved 5 bytes: use of endswith()

lambda x:str(x*x).endswith(str(x)) 

Try it online!

Python 2, 31 bytes (Does not work for large numbers)

lambda x:`x*x`[-len(`x`):]==`x`

Try it online!

officialaimm

Posted 2017-06-24T18:54:09.697

Reputation: 2 739

1Doesn't work on 8212890625 because x*x will end with "L". You can however save two bytes by removing the f= I think. – nore – 2017-06-24T19:07:59.313

It would work in python 3 though, right? – officialaimm – 2017-06-24T19:15:50.387

1You must use f=\ not f=/... – Erik the Outgolfer – 2017-06-24T19:15:58.263

@officialaimm no, the `` syntax doesn't work in Python 3. – nore – 2017-06-24T19:17:49.167

I meant after replacing `` with str() – officialaimm – 2017-06-24T19:18:48.837

1Yes that will work then. – nore – 2017-06-24T19:19:28.860

1Would using endswith and removing s=str not be shorter for python3?: lambda x:str(x*x).endswith(str(x)) – None – 2017-06-26T10:20:29.510

0

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.

Sean

Posted 2017-06-24T18:54:09.697

Reputation: 4 136

0

Clojure, 59 bytes

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

This seems overly verbose.

NikoNyrh

Posted 2017-06-24T18:54:09.697

Reputation: 2 361

Why not just go with #(.endsWith(str(* % %))(str %)) ? – cliffroot – 2017-06-26T09:52:04.963

Oh true, it is so easy to forget about Java built-ins. – NikoNyrh – 2017-06-26T10:55:24.293

0

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

Luis Mendo

Posted 2017-06-24T18:54:09.697

Reputation: 87 464

0

Java 8, 36 bytes

n->(n.multiply(n)+"").endsWith(n+"")

Input is a java.math.BigInteger, output a boolean.

Explanation:

Try it here.

n->                   // Method with BigInteger parameter and boolean return-type 
  (n.multiply(n)+"")  //  Return if the String representation of n*n
   .endsWith(n+"")    //  ends with the String representation of n
                      // End of method (implicit / single-line body)

Kevin Cruijssen

Posted 2017-06-24T18:54:09.697

Reputation: 67 575

0

Haskell, 45 bytes

f=reverse.show
g a=and$zipWith(==)(f a)$f$a^2

Try it online!

Haskell + Data.Function, 42 bytes

g a=and$on(zipWith(==))(reverse.show)a$a^2

Try it online!

Haskell + Data.Function + Control.Monad, 40 bytes

and.ap(on(zipWith(==))$reverse.show)(^2)

Try it online!

Post Rock Garf Hunter

Posted 2017-06-24T18:54:09.697

Reputation: 55 382