find all squares modulo a prime number

This post is a wiki. Anyone with karma >750 is welcome to improve it.

I have been using PARI-GP to find the squares of a prime number. For example

for(JJ=0,7,print1(JJ^2%8"\t"))


in PARI gives

0       1       4       1       0       1       4       1


from which I know that the squares modulo 8 are 1 and 4. Now that I need to find the squares modulo large prime, I was wondering is there a way SAGE can give me a complete list without repeating the values.

edit retag close merge delete

Sort by » oldest newest most voted

This answer sort of cheats, but:

sage: p = 17
[0, 1, 2, 4, 8, 9, 13, 15, 16]


This is, after all, a well-known concept.

This works for your example too, even though 8 isn't prime

sage: quadratic_residues?
Docstring:
Return a sorted list of all squares modulo the integer n in the
range 0<= x < |n|.

more

Thanks for pointing this out ! Actually the source code is almost the same except that

• the set is turned into a sorted list
• the loop ends at p//2+1
• instead of p^2 it uses p*p which is a bit faster
( 2016-09-13 08:37:09 -0500 )edit

Yeah, and there is an easy theoretical reason for the second bullet point.

( 2016-09-14 09:39:35 -0500 )edit

Given that $(n + p)^2 = n^2 + 2np + p^2 = n^2 \mbox{ mod } p$, you just have to compute the numbers $n^2 \mbox{ mod } p$ for all integers between $0$ and $p-1$. If you want to avoid repetitions, you just have to put them in a set. Here is how:

sage: p = 17
sage: S = {n^2 % p for n in range(p)}
sage: S
{0, 1, 2, 4, 8, 9, 13, 15, 16}

sage: p = 123457
sage: S = {n^2 % p for n in range(p)}
sage: len(S)
61729

more

@tmonteil thank you. your answer is very helpful to me. Can I do the same for non-squares? How to obtain the set of non-squares from the code?

( 2016-09-06 04:44:23 -0500 )edit

Well, everything else would be a non-square, right? So perhaps not (n^2 % p)?

( 2016-09-06 08:01:05 -0500 )edit

@kcrisman I tried both of this command but it did not work. Instead it gave me a "False" answer.

S={not(n^2%p) for n in range(p)}
S=not {n^2%p for n in range(p)}

( 2016-09-12 20:46:24 -0500 )edit

Sorry, I thought you were somehow getting True or False. You would want to look for n such that it was not in this list. Anyway, an easier way to do this with Thierry's syntax is just set(range(p)).difference(S). You need the set because then you get set difference.

( 2016-09-13 07:22:25 -0500 )edit