Is q a quadratic residue of n?

Given two inputs q n determine if q is a quadratic residue of n.

That is, is there an x where x**2 == q (mod n) or is q a square mod n?

Input

Two integers q and n, where q and n are any integers 0 <= q < n.

Output

A truthy or a falsey.

Optionally, print any (or all) x that is x**2 == q (mod n)

Examples

True
False
True

Rules

Your code must be a program or a function. The inputs can be in any order. This is code golf, so shortest code in bytes wins.

If anything is unclear or otherwise needs fixing, please let me know.

Bonuses

• 2-byte bonus if your function accepts q as any arbitrary integer.

Catalogue

• Some existing answers are assuming that 0 <= q < n. You should probably clarify whether or not this is an acceptable assumption. – Peter Taylor Nov 30 '15 at 14:52
• I would have liked q and n to be any two integers, but so I don't break existing answers, 0 <= q < n – Sherlock9 Nov 30 '15 at 15:23
• In this case I would have considered it reasonable to "break" the existing answers on the grounds that they weren't following the existing spec and you were just clarifying that it meant what it said rather than changing it, but it's too late now. – Peter Taylor Nov 30 '15 at 16:17
• You could give a small bonus for solutions accepting arbitrary q – Bakuriu Dec 2 '15 at 17:41

Pyth, 9 bytes

}Em%*ddQQ

Try it online: Demonstration or Test Suite

Explanation:

}Em%*ddQQ   implicit: Q = first input number
m     Q   map all numbers d of [0, 1, ..., Q-1] to:
*dd       d*d
%   Q      mod Q
this gives the list of all quadratic residues
}           check, if it appears in the list of quadratic residues
• I tried putting 7 9 as inputs, and it said "False", despite the fact that 7 is equivalent to 5^2 mod 9. – Nick Matteo Dec 1 '15 at 20:57
• @kundor I read the integers in the reversed order. First n and than q. So try 9\n7 as input. – Jakube Dec 1 '15 at 21:00

Mathematica, 25 bytes

AtomQ@PowerMod[#,1/2,#2]&

Mathematica, being Mathematica, naturally has a builtin for calculating modulo nth roots, via PowerMod. If a solution exists the smallest feasible solution is returned, otherwise the original expression (plus a message).

To get an actual truthy/falsy output we pass the result to AtomQ, which checks whether an expression can be broken down. Integers are atomic, returning True, whilst the non-atomic PowerMod[q,1/2,n] returns False

Thanks to @MartinBüttner for golf tips and function hunting with me.

• Stupid argument ordering – CalculatorFeline Mar 26 '16 at 15:56
• What?! I never knew PowerMod could take a fractional argument! – Greg Martin Jan 28 '17 at 2:24

Par, 11 9 bytes

✶X[²x%)↔,

Each character uses just one byte; see here.

Explanation

X              ## Assign second to x
[              ## Map
²             ## Square
x%            ## Mod x
)              ##
↔              ## Swap
,              ## Count

Removed two bytes thanks to Jakube.

LabVIEW, 16 15 Equivalent bytes

Counted according to my meta post.

Saved 3 bytes thanks to Martin Büttner.

q#n=elem q[mod(x^2)n|x<-[1..n]]
• Also 31 bytes: q#n=any(\x->mod(x*x)n==q)[0..n] and for 30 byte: q#n=[x|x<-[0..n],mod(x*x)n==q] which returns the list of x / empty list instead of True / False. – nimi Nov 30 '15 at 16:32

Matlab, 29

This function squares all numbers from 0 to n and checks whether a square minus q is zero mod n.

@(q,n)any(~mod((0:n).^2-q,n))

Prolog (SWI), 34 bytes

Code:

Q*N:-between(0,N,X),X*X mod N=:=Q.

Explanation:
Checks if any square between 0 and N leaves Q when divided by N.

Example:

3*8.
false

15*22.
true

Try it online here

CJam, 11 bytes

{_,2f#\f%&}

This unnamed block expects q n on the stack and leaves [q] on the stack as a truthy value or "" as a falsy value.

Test it here.

Credits to Sp3000 who also came up with this solution but "couldn't be bothered posting".

Explanation

_,  e# Duplicate n and turn into range [0 1 ... n-1]
2f# e# Square each element in the range.
\f% e# Take each element in the range modulo n.
&   e# Set intersection with q to check if any square yields q (mod n).

J, 9 bytes

e.]|i.^2:

Usage:

1 (e.]|i.^2:) 5
1
3 (e.]|i.^2:) 8
0
15 (e.]|i.^2:) 22
1

Explanation:

e.]|i.^2:
i.    [0..N-1]
^   to the power of
2: 2 (constant 2 function)
]|      mod N
e.        contains Q? (0/1 result)

Some J mechanics trivia:

Functions are grouped by 3 iteratively from the right and if there is one left, as in our case (e. (] | (i. ^ 2:))), the grouped part is called with the right argument (N) and the left out function (e., "contains") called with the original left argument (Q) and the result of the grouped part.

(e.]|i.*i. and e.]|2^~i. also solves the problem with the same length.)

Try it online here.

Mathematica, 27 bytes

PowerModList[#,1/2,#2]!={}&

Usage:

In[1]:= PowerModList[#,1/2,#2]!={}&[1,5]

Out[1]= True

Javascript ES6, 42 bytes

(q,n)=>[...Array(n)].some((x,y)=>y*y%n==q)

Credits to @apsilers for serious bytes saved!

• What is the ...Array syntax? I still don't get it. – Tomáš Zato - Reinstate Monica Dec 1 '15 at 12:40
• Hope this edit is better for you. – Mama Fun Roll Dec 1 '15 at 14:47
• [...Array(5)] produces array of undefined, same as Array(5) alone. I am totally confused, because removing the weird syntax and using just Array(5) breaks the code. Is there any documentation for this? my console screenshot – Tomáš Zato - Reinstate Monica Dec 1 '15 at 14:57
• @TomášZato Array(5) is an array with no own-properties except length. The array-spread [...x] fills in missing numerical properties up to length. The map function can only operate on extant properties, which Array(5) alone doesn't have. For example, try Array(5).hasOwnProperty(0) (false) versus [...Array(5)].hasOwnProperty(0) (true). – apsillers Dec 1 '15 at 21:07
• Also, using some is shorter and (I think) equivalent: (q,n)=>[...Array(n)].some((x,y)=>y*y%n==q) – apsillers Dec 1 '15 at 21:22

Seriously, 20 bytes

,;R@,;╗@%╝ª╜@%╛=MΣ

Takes input on two lines: q, then n. Outputs a 0 if q is not a quadratic residue of n, else a positive number representing how many x in [1, q] (inclusive) satisfy x^2 = q (mod n).

Try it online (permalinks are having more issues, but you can copy and paste the code into a blank page in the meantime)

Explanation:

,;R      get q input, duplicate, push range(1, q+1)
@,;╗     move the list to the back of the stack, get n input, dupe, save in reg 0
@%╝      calculate q mod n and save to reg 1
ª╜@%╛= push this function:
ª╜@%     square top of stack, push reg 0 value (n), swap, and mod
╛=       push reg 1 value (q mod n), compare equality (1 if equal else 0)
MΣ       map the function across the range, add results

Python 3, 41 40 bytes

Takes q and n and determines if q is in a list of squares from 0 squared to n-1 squared.

lambda q,n:q in[i*i%n for i in range(n)]

Ruby, 33 31 bytes

Saved two bytes thanks to Vasu Adari.

->q,n{(1..n).any?{|e|e*e%n==q}}

As usual Ruby's not going to beat any of the golfing languages, but it makes a good showing here.

• You can lose the braces and make it ->q,n{}. – Vasu Adari Dec 3 '15 at 8:00
• @VasuAdari Cool, I did not know that. Thank you. – Reinstate Monica -- notmaynard Dec 3 '15 at 16:11

Julia, 30 bytes

f(q,n)=q∈[i^2%n for i=0:n-1]

This is a function f that accepts two integers and returns a boolean.

Ungolfed:

function f(q::Integer, n::Integer)
# Generate an array of quadratic residues
x = [i^2 % n for i = 0:n-1]

# Determine whether q is one of these values
return q ∈ x
end

JavaScript (ES6), 43 bytes

(q,n)=>eval('for(x=n,r=0;x--;)r+=x*x%n==q')

Explanation

(q,n)=>
eval(              // eval allows us to use a for loop without {} or return
for(x=n,r=0;x--;) // iterate over all possible values of x
r+=x*x%n==q     // r = the number of matching x values
)                  // implicit: return r

Test

q = <input type="number" id="Q" /><br />
n = <input type="number" id="N" /><br />
<button onclick="result.innerHTML=(

(q,n)=>eval('for(x=n,r=0;x--;)r+=x*x%n==q')

)(+Q.value,+N.value)">Go</button><pre id="result"></pre>

• This is a very interesting take on the truthy/falsey condition @user81655. Excellent work! – Sherlock9 Dec 1 '15 at 17:37

𝔼𝕊𝕄𝕚𝕟, 13 chars / 25 bytes

⟦Ѧí]ĉ⇀_²%í≔î)

Try it here (Firefox only).

• I tested your code with 15 22 and it said false. – Sherlock9 Dec 1 '15 at 0:01
• @Sherlock9 Fixed. – Mama Fun Roll Dec 1 '15 at 3:24
• No custom codepage? This is not a golfing language! – CalculatorFeline Mar 26 '16 at 15:58
• There is now, but the code page was made long after the challenge. – Mama Fun Roll Mar 26 '16 at 18:48

Japt, 10 bytes

Vo d_²%V¥U

My first official Japt golf ever! Thanks to @ETHProductions for saving a byte!

Ungolfed / Explanation

Vo d_  ²  %V¥ U
Vo dZ{Zp2 %V==U}  // implicit: U,V = inputs
Vo                // Create a range from 0 to n-1
dZ{         }  // Check if any element Z in the range satisfies the condition:
Zp2        // Is Z squared...
%V     // modulo n...
==U  // equal to q?
// implicit output

Try it online!

• Nice! Hint: 0oV is equivalent to Vo. – ETHproductions Dec 2 '15 at 22:53
• Didn't know that. Thanks! – Mama Fun Roll Dec 2 '15 at 23:14

C# 6 (.Net Framework 4.6) in LinqPad, 60 Bytes

bool b(int q,int n)=>Enumerable.Range(1,n).Any(y=>y*y%n==q);

Milky Way 1.0.2, 41 bytes

:>&{~1-:2h<:>n>;:>;<<b?{_a0_^}~;?{_0_1}}!

This expects q and n to be solely on the stack. It outputs a 1 or 0 for the truth and false values, respectively.

Pari/GP, 25 bytes

(q,n)->issquare(Mod(q,n))

Try it online!

JavaScript (Node.js), 33 bytes

q=>n=>f=(t=n)=>t&&f(t-1)|t*t%n==q

Try it online!

Why no one do this