# Challenge

So, um, it seems that, while we have plenty of challenges that work with square numbers or numbers of other shapes, we don't have one that simply asks:

Given an integer n (where n>=0) as input return a truthy value if n is a perfect square or a falsey value if not.

## Rules

• You may take input by any reasonable, convenient means as long as it's permitted by standard I/O rules.
• You need not handle inputs greater than what your chosen language can natively handle nor which would lead to floating point inaccuracies.
• Output should be one of two consistent truthy/falsey values (e.g., true or false, 1 or 0) - truthy if the input is a perfect square, falsey if it's not.
• This is so lowest byte count wins.

## Test Cases

Input:  0
Output: true

Input:  1
Output: true

Input:  64
Output: true

Input:  88
Output: false

Input:  2147483647
Output: false

• @Neil I realized my mistake. I retract that suggestion, and instead offer 18014398509481982 (2**54-2), which is representable with a double, and causes answers that use sqrt to fail. – Mego Jun 8 '17 at 12:24
• @Mego I'm probably wrong or just misunderstanding what you're saying, but I'm sure 2**54-2 is still larger than a double can safely handle, at least in JavaScript 18014398509481982 > 9007199254740991 – Tom Jun 8 '17 at 12:32
• @Mego I think the limiting value is 9007199515875288. It's not the square of 94906267, because that's not representable in a double, but if you take its square root, then you get that integer as the result. – Neil Jun 8 '17 at 12:33
• @Tom Type 2**54-2 into a JS console, and compare what you get with 18014398509481982 (the exact value). JS outputs the exact value, therefore 2**54-2 is representable with a double. If that still doesn't convince you, take the binary data 0100001101001111111111111111111111111111111111111111111111111111, interpret it as a IEEE-754 double-precision float, and see what value you get. – Mego Jun 8 '17 at 12:41
• Sorry, guys, stepped away for lunch and ... well, that escalated! And there I thought this would be a nice, simple challenge! Would adding a rule that you need not handle inputs that lead to floating point inaccuracies in your chosen language cover it? – Shaggy Jun 8 '17 at 13:17

# Neim, 2 bytes

q𝕚


Explanation:

q      Push an infinite list of squares
𝕚     Is the input in that list?


When I say 'infinite' I mean up until we hit the maximum value of longs (2^63-1). However, Neim is (slowly) transitioning to theoretically infinitely large BigIntegers.

Try it!

• Comments are not for extended discussion; this conversation has been moved to chat. – Dennis Jun 10 '17 at 15:24
• Interesting. So, does this pre-buffer the list or is it a generator / iterator that continues checking for the existence of input until it terminates? – Patrick Roberts Jun 10 '17 at 16:46
• @PatrickRoberts Can we talk in chat? – Okx Jun 10 '17 at 16:51
• Sure, just ping me on The Nineteenth Byte. I'm in there occasionally. – Patrick Roberts Jun 11 '17 at 4:59
• Well, this is ... REALLY FUNCTIONAL – Chromium Jun 15 '18 at 9:03

# Jelly, 2 bytes

Æ²


Try it online!

• Also works with Ohm. – Nick Clifford Jun 8 '17 at 12:42

# TI-Basic, 4 bytes

not(fPart(√(Ans


Simply checks if the square root is an integer by looking for a nonzero fractional/decimal part.

• Can you add a TIO (or equivalent)? – Shaggy Jun 8 '17 at 13:23
• @Shaggy I don't think there are any. TI-Basic is proprietary and will only run on TI's calculators and in emulators running the ROM from a calculator, so you cannot legally use TI-Basic if you don't own a calculator. – Adám Jun 8 '17 at 13:56
• @Shaggy If you have any ROMs you can use an emulator (my preference is jstified) to try this out online. – Timtech Jun 8 '17 at 15:18

# C#, 27 bytes

n=>System.Math.Sqrt(n)%1==0


A more correct/accurate way to do this would be:

n=>System.Math.Sqrt(n)%1<=double.Epsilon*100

• double.Epsilon is useless for this type of check. tl;dr: When comparing numbers >2, Double.Epsilon is basically the same as zero. Multiplying by 100 will only delay that a bit. – Robert Fraser Jun 8 '17 at 14:17
• @RobertFraser I only went by the linked SO post and didn't read to much into it. Either way it isn't useless just not to useful at higher numbers. – TheLethalCoder Jun 8 '17 at 14:21
• ...<int>==0 is ...!<int> I think – Stan Strum Jan 13 '18 at 20:39
• @StanStrum Not in C# – TheLethalCoder Jan 13 '18 at 21:31

# JavaScript (ES6), 13 bytes

n=>!(n**.5%1)


Returns true if the square root of n is a whole number.

Snippet:

f=
n=>!(n**.5%1)

console.log(f(0));
console.log(f(1));
console.log(f(2));
console.log(f(4));
console.log(f(8));
console.log(f(16));
console.log(f(88));
console.log(f(2147483647));

# dc, 9

0?dvd*-^p


Outputs 1 for truthy and 0 for falsey.

0            # Push zero.  Stack: [ 0 ]
?           # Push input.  Stack: [ n, 0 ]
dv         # duplicate and take integer square root.  Stack: [ ⌊√n⌋, n, 0 ]
d        # duplicate.  Stack: [ ⌊√n⌋, ⌊√n⌋, n, 0 ]
*       # multiply.  Stack: [ ⌊√n⌋², n, 0 ]
-      # take difference. Stack: [ n-⌊√n⌋², 0 ]
^     # 0 to power of the result.  Stack: [ 0^(n-⌊√n⌋²) ]
p    # print.


Note dc's ^ exponentiation command gives 00=1 and 0n=0, where n>0.

• Beautiful! +1 for using dc in such ingenious fashion. – Wildcard Jun 10 '17 at 0:26

# Retina, 18 bytes

.+
$* (^1?|11\1)+$


Try it online! Shamelessly adapted from @MartinEnder's answer to Is this number triangular? but with the base conversion included at a cost of 6 bytes.

Note that Is this number triangular? wasn't for some inexplicable reason required to support zero as a triangular number, so part of the adaption was to add a ? to make the leading 1 optional, allowing the group to match the empty string, and therefore a zero input. However, having now matched the empty string, the + operator stops repeating, to avoid the infinite loop that would happen if it kept greedily matching the empty string (after all, ^1? would certainly keep matching). This means that it doesn't even try to match the other alternative in the group, thus avoiding the match of 2, 6, 12 etc. As @MartinEnder points out, a simpler way to avoid that while still matching the empty string is to anchor the match at the start while making the group optional for the same byte count: ^(^1|11\1)*$. • Looking forward to your explanation why this doesn't match 2, 6 or other numbers of the form n^2-n. ;) (A way to avoid that explanation for the same byte count would be ^(^1|11\1)*$.) – Martin Ender Jun 8 '17 at 12:54
• @MartinEnder Same reason that you couldn't use (^|1\1)+$, I think? – Neil Jun 8 '17 at 13:12 • Yeah that's right. Just thought it would probably be good to mention because most people probably haven't read my comment on the triangular answer (and in this case it's actually relevant to why the solution is correct, as opposed to just why it can't be golfed further). – Martin Ender Jun 8 '17 at 13:14 • For the record, the + would also stop looping if there was no longer an empty alternative, e.g. in the case of ((?(1)11\1|1?))+. Once there was an empty iteration, it won't try any further ones, regardless of whether they may or may not be empty. – Martin Ender Jun 8 '17 at 13:33 • @MartinEnder Indeed, I meant "having now matched" instead of "having immediately matched". Fixed. – Neil Jun 8 '17 at 14:36 # C (gcc), 30 bytes f(n){n=sqrt(n)==(int)sqrt(n);}  Try it online! # C, 34 bytes f(n){return(int)sqrt(n)==sqrt(n);}  Try it online! # C, 33 bytes #define f(n)(int)sqrt(n)==sqrt(n)  Try it online! # MATL, 5 4 bytes Thanks to Luis for reducing my one byte longer code by two bytes, making it the shortest one. t:Um  Try it online Explanation:  % Implicit input t % Duplicate it : % Range from 1 to input value U % Square the range, to get 1 4 9 ... m % ismember, Checks if the input is a member of the range of perfect squares  Old answer: X^1\~  Try it online!  % Implicit input X^ % Square root of input 1\ % Modulus 1. All perfect squares will have 0, the rest will have decimal value ~ % Negate, so the 0 becomes 1, and the decimal values become 0  • @Mego I disagree. MATL can't even do mod(2**127-, 1000). Unless the four last digits are 0.... – Stewie Griffin Jun 8 '17 at 12:02 • You can also use t:Um. That works for inputs up to 2^53, due to floating point limited precision – Luis Mendo Jun 8 '17 at 12:30 • I see now that this is similar to your edit, only a little shorter :-) – Luis Mendo Jun 8 '17 at 12:31 • Well hidden square command! U: str2num / string to array / square. I knew there had to be a square function, but I couldn't find it... – Stewie Griffin Jun 8 '17 at 12:32 • @cairdcoinheringaahing that was partially on purpose. I had two solutions, one was 5 bytes, the other one 6 bytes. Luis golfed off two bytes from the one with 6. So I saved two bytes thanks to him, but I only saved a byte on the score... – Stewie Griffin Jun 8 '17 at 20:49 # Python 3, 40 38 bytes Thanks to squid for saving 2 bytes! lambda n:n in(i*i for i in range(n+1))  Try it online! Too slow to return an answer for 2147483647 in a reasonable amount of time. (But written using a generator to save memory, since it doesn't cost any bytes.) Works in Python 2 also, though an OverflowError is a possibility due to range if you try it with huge inputs. (A MemoryError would also be likely in Python 2, also due to range.) # Perl 5, 14 bytes 13 bytes of code + -p flag. $_=sqrt!~/\./


Try it online!

Computes the square root, and looks if it's an integer (more precisely, if it doesn't contain a dot (/\./).

# 05AB1E, 4 bytes

Ln¹å


Try it online!

• Doesn't work for large numbers, for example 4111817668062926054213257208 – Emigna Jun 8 '17 at 11:28
• @Emigna Oh because it's considered a long? I thought that 05AB1E uses Python 3. – Erik the Outgolfer Jun 8 '17 at 11:29
• Fails for large inputs (the given input is 2**127-1, a Mersenne prime). – Mego Jun 8 '17 at 11:30
• It does use python 3. The problem is that square root gives rounding errors for large numbers. – Emigna Jun 8 '17 at 11:30
• @Emigna Oh...I guess I'll have to figure out another way then, shouldn't be hard. – Erik the Outgolfer Jun 8 '17 at 11:31

# Python 3, 19 bytes

lambda n:n**.5%1==0


Try it online!

• Fails for large inputs, e.g. 4111817668062926054213257208. – L3viathan Jun 8 '17 at 11:41
• Fixed in 25 bytes: lambda n:int(n**.5)**2==n – L3viathan Jun 8 '17 at 11:43
• @L3viathan That (along with any solution that involves sqrt) fails on values which are outside of the range of a double, like 2**4253-1. – Mego Jun 8 '17 at 12:30
• @totallyhuman a float after %1 is definitely <1, so your proposal would return true for all inputs. Note that n**.5 is a float. – Leaky Nun Jun 8 '17 at 13:33

## SageMath, 9 bytes

is_square


Try it online

The built-in function does exactly what it says on the tin. Since Sage uses symbolic computation, it's free of computational accuracy errors that plague IEEE-754 floats.

# Japt, 3 bytes

¬v1


Try it online!

Seems to work fine for 2**54-2 in the Japt Interpreter but fails on TIO for some reason...

• Fails for large inputs (input is 2**127-1, a Mersenne prime). – Mego Jun 8 '17 at 11:35
• @Mego, isn't the norm that solutions need not handle numbers larger than the language is capable of handling? – Shaggy Jun 8 '17 at 11:36
• @Shaggy Japt is based on JavaScript, which uses double-precision floats. 2**127-1 is well within the range of a double. – Mego Jun 8 '17 at 11:36
• @Mego Isn't the max safe int for JavaScript 2**53-1? – Tom Jun 8 '17 at 11:37
• @Mego But JavaScript's numbers only have 53 bits of precision, so JS cannot exactly represent the value 2**127-1 as a number. The closest it can get is 2**127. – ETHproductions Jun 8 '17 at 17:01

f n=elem n$map(^2)[0..n]  Try it online! Checks if n is in the list of all squares from 0 to n. • same byte count: f n=or[i*i==n|i<-[0..n]] :) – vroomfondel Jun 8 '17 at 18:10 # Prolog (SWI), 27 bytes +N:-between(0,N,I),N=:=I*I.  Try it online! ## Explanation Searches through all numbers greater or equal to 0 and less than or equal to N and tests whether that number squared is equal to N. • @DLosc done! – 0 ' Jan 15 '18 at 15:36 # MathGolf, 1 byte °  Try it online! I don't think an explanation is needed. I saw the need for an "is perfect square" operator before I saw this challenge, as the language is designed to handle math related golf challenges. Returns 0 or 1, as MathGolf uses integers to represent booleans. # PHP, 21 bytes <?=(-1)**$argn**.5<2;


If the square root is not an integer number, (-1)**$argn**.5 is NAN. • How do I run this? – Titus Jun 9 '17 at 8:40 • @Titus With the -F flag and pipeline: echo 144 | php -F script.php. – user63956 Jun 9 '17 at 8:44 • Ah I forgot that letter. Thanks. – Titus Jun 9 '17 at 8:47 # Ruby, 25 bytes Math.sqrt(gets.to_i)%1==0  There probably is a shorter way but that's all I found. Try it online! • Welcome to PPCG :) Could you add a TIO (or equivalent) to this, please? – Shaggy Jun 9 '17 at 8:18 • Thanks for adding the TIO however, this doesn't seem to return any output. – Shaggy Jun 9 '17 at 15:37 • My bad, i updated it. – Gregory Jun 9 '17 at 15:43 • Nope, still not working. – Shaggy Jul 3 '17 at 16:10 # CJam, 8 bytes ri_mQ2#=  Try it online! ### Explanation Integer square root, square, compare with original number. • I guess according to this, you don't need the first 2 bytes – Chromium Jun 15 '18 at 9:05 • And, alternatively, using the idea of this answer, you can do mq1%0=, which is also 6 bytes – Chromium Jun 15 '18 at 9:11 • @Chromium Thanks, but in that case I need {...} to make the code a function, so same byte count – Luis Mendo Jun 15 '18 at 9:21 • Actually, I'm a bit confused whether to add curly braces or not. Cuz if you don't add them, it's actually a program, which is permitted. – Chromium Jun 15 '18 at 9:23 • @Chromium A program needs to take its input, so ri is required in that case – Luis Mendo Jun 15 '18 at 9:27 # Mathematica, 13 bytes AtomQ@Sqrt@#&  Try it online! • No built in? Odd.... – TheLethalCoder Jun 8 '17 at 12:17 • You can use AtomQ instead of IntegerQ. – Martin Ender Jun 8 '17 at 13:16 • of course shaggy... – J42161217 Jun 8 '17 at 13:44 • You can still use @*. – Martin Ender Jun 8 '17 at 14:03 • AtomQ@*Sqrt is a synonym for AtomQ@Sqrt@#&. For example, AtomQ@*Sqrt@4 returns True and AtomQ@*Sqrt@5 returns False. (Because of precedence, AtomQ@*Sqrt doesn't work right, returning AtomQ@*2.) – Greg Martin Jun 8 '17 at 18:39 # APL (Dyalog), 8 bytes 0=1|*∘.5  Try it online! 0= [is] zero equal to 1| the modulus-1 (i.e. the fractional part) of *∘.5 the argument raised to the power of a half # AWK, 27+2 bytes {x=int($0^0.5);$0=x*x==$1}1


Try it online!

Add +2 bytes for using the -M flag for arbitrary precision. I originally used string comparison because large number compared equal, even though they weren't, but the sqrt was also returning imprecise values. 2^127-2 should not be a perfect square.

# T-SQL, 38 bytes

SELECT IIF(SQRT(a)LIKE'%.%',0,1)FROM t


Looks for a decimal point in the square root. IIF is specific to MS SQL, tested and works in MS SQL Server 2012.

Input is in column a of pre-existing table t, per our input rules.

# Ohm, 2 bytes

Æ²


Uses CP-437 encoding.

## Explanation

Implicit Input -> Perfect square built-in -> Implicit Output...

# Java 8, 20 bytes

n->Math.sqrt(n)%1==0


Input is an int.

Try it here.

• Not debatable: the question explicitly says "Given an integer n (where n>=0)". The shortest answer is the best. Edit: won't +1 until the shortest answer isn't the first :p – Olivier Grégoire Jun 8 '17 at 13:03
• @OlivierGrégoire Hmm, that's a good way to look at it. But you still wouldn't know whether it's an int, long, short. And with questions where they ask for an integer but the input format is flexible, I sometimes use a String input to save some bytes. Personally I think using n-> is fine, and you should just state what the type is, but apparently not everyone agrees with this. On the other hand, coming from a Java 7 answer history, going from int c(int n){return ...;} to (int n)->... makes more sense than n->... (even though I personally prefer the second since shorter of course). – Kevin Cruijssen Jun 8 '17 at 13:10
• @OlivierGrégoire Ok, I've changed it. After reading the discussion in this answer, I came to the conclusion that stating the input is an integer in Java, is no difference than stating the input is a list of two Strings in CJam or a cell array of strings in MATL. – Kevin Cruijssen Jun 9 '17 at 8:05

# R, 15

scan()^.5%%1==0


^.5 is less bytes than sqrt(). %%1, the modulus, will result in 0 if answer is an interger. scan() takes user input.

http://www.tutorialspoint.com/execute_r_online.php?PID=0Bw_CjBb95KQMSm1qVktIOUdSSDg

+?
S
%1
N
O


Try it online!

I removed the clunky function at the top and rewrote it into the body of the question to remove 11 bytes.

As the first section is already explained below, let's only find out how the new part works

S   Square root
%1  Modulo by 1. Produced 0 for integers and a decimal for floats
N   Logical NOT


## Old version, 24 bytes

D,i,@,1@%!
+?
^.5
$i,x O  Try it online! The function at the top (D,i,@,1@%!) is the main part of the program, so let's go into more detail. D, Create a function... i, ...called i... @, ...that takes 1 argument (for this example, let's say 3.162 (root 10)) 1 push 1 to the stack; STACK = [1, 3.162] @ reverse the stack; STACK = [3.162, 1] % modulo the stack; STACK = [0.162] ! logical NOT; STACK = [False] +? Add the input to accumulator (x) ^.5 Square root (exponent by 0.5)$i,x   Apply function i to x
O      Output the result


# Python 3, 28 27 25 bytes

• Thanks to @mdahmoune for 1 byte: compare int of root squared with original
• 2 bytes saved: lambda shortened
lambda x:int(x**.5)**2==x


Try it online!

• what about f=lambda x:int(x**.5)**2==x 27bytes – mdahmoune Jul 3 '17 at 15:30