#SQDANCE. Square dance

Square dance

You are hired by french NSA to break the RSA code used on the Pink Card. The easiest way to do that is to factor the public modulus and you have found the fastest algorithm to do that, except that you have to solve a subproblem that can be modeled in the following way.
Let $ cal P$ $ = {p_1,p_2,...,p_n}$be a set of prime numbers. If $ S = {s_1,s_2,...,s_u}$ and $ T = {t_1,...,t_v}$ are formed with elements of $ cal P$, then S*T will denote the quantity

$displaystyle s_1*s_2*cdot cdot cdot *s_u*t_1*t_2*cdot cdot cdot *t_v.$

We call relation a set of two primes p,q, where p and q are distinct elements of $ cal P$. You dispose of a collection of R relations $ S_i = {p_i,q_i}$ and you are interested in finding sequences of these, $ S_{i_1}, S_{i_2}, ..., S_{i_k}$ such that

$displaystyle S_{i_1}*S_{i_2}*cdot cdot cdot *S_{i_k}$

is a perfect square.

The way you look for these squares is the following. The ultimate goal is to count squares that appear in the process. Relations arrive one at a time. You maintain a collection $ cal C$ of relations that do not contain any square subproduct. This is easy: at first, $ cal C$ is empty. Then a relation arrives and $ cal C$ begins to grow. Suppose a new relation $ {p,q}$ arrives. If no square appears when adding $ {p,q}$ to $ cal C$, then $ {p,q}$ is added to the collection. Otherwise, a square is about to appear, we increase the number of squares, but we do not store this relation, hence $ cal C$ keeps the desired property.
Let us consider an example. First arrives $ S_1 = {2,3}$ and we put it in $ cal C$; then arrives $ S_2 = {5,11},S_3 = {3,7}$ and they are stored in $ cal C$. Now enters the relation $ S_4 = {2,7}$. This relation could be used to form the square:

$displaystyle S_1*S_3*S_4 = (2*3)*(3*7)*(2*7) = (2*3*7)^2.$

So we count 1 and do not store $ S_4$ in $ cal C$. Now we consider $ S_5 = {5,11}$ that could make a square with $ S_2$, so we count 1 square more. Then $ S_6 = {2,13}$ is put into $ cal C$. Now $ S_7 = {7,13}$ could make the square $ S_1*S_3*S_6*S_7$. Eventually, we get 3 squares.