We are asked: Construct an undirected graph with n vertices (labeled 1..n) and exactly m edges such that the graph is connected, has no self-loops or multiple edges, and is "relatively prime": for each edge (v,u), gcd(v,u)=1. If impossible, output "Impossible". n,m up to 1e5.
We need to produce any such graph if possible.
First, let's understand constraints. Graph must be simple (no parallel edges) and connected. Also edges must satisfy that the two vertices are coprime.
We need to decide for given n,m whether there exists a connected graph on vertices 1..n with edges only between coprime pairs, and exactly m edges.
We can think about the maximum possible number of edges in such a graph: it's the number of unordered pairs (i,j) with 1<=i<j<=n and gcd(i,j)=1. Let's denote that as Mmax(n). If m > Mmax(n), impossible. Also need connectivity: at minimum we need at least n-1 edges to be connected. So m must be between n-1 and Mmax(n). However, connectivity might impose extra constraints beyond just having enough edges? For a given set of edges, we need existence of a connected graph with exactly m edges using only allowed pairs. Since we can choose any edges among allowed pairs, as long as there is a spanning tree (n-1 edges) among allowed pairs, we can add extra edges arbitrarily (as long as they exist) to reach m, provided m <= Mmax. So the key condition is: there exists a spanning tree using only coprime edges. If such a spanning tree exists, then we can fill up to Mmax edges.
Thus problem reduces to: can we construct a connected graph with vertices 1..n using only coprime edges? That is, does the graph G_n = (V, edges where gcd=1) have a spanning tree? If yes, then for any m between n-1 and Mmax inclusive, we can output some graph. If not, then only m values that are possible are limited; but we need to decide.
We need to check if the graph G_n is connected? Actually, if G_n is not connected, then any subgraph using only allowed edges will also be disconnected, unless we restrict to a connected component? But we need to use all n vertices; thus the graph must be connected, so we need to have edges connecting all vertices. So if G_n is disconnected, it might be impossible to have any connected graph on all vertices using only coprime edges. However, perhaps we can still pick a connected subgraph that uses all vertices if the underlying allowed edges graph is disconnected? If the graph G_n is disconnected, that means there is at least one pair of vertices that are not connected by any path of coprime edges. But could we still connect them directly? No, because direct edge would be allowed only if gcd=1, but if they are in different components of G_n, then by definition there is no path, but that also means no direct edge? Actually, G_n includes all allowed edges. If two vertices are in different components of G_n, that means there is no path, but also there is no direct edge between them because if there were direct edge with gcd=1, they'd be connected. So indeed they are not directly connected, and there is no path connecting them. So any graph that uses only allowed edges will have each vertex restricted to its component. Therefore, to have a connected graph covering all vertices, the graph G_n must be connected. So a necessary condition is that the "coprime graph" on 1..n is connected.
Thus we need to determine for which n the graph G_n (vertices 1..n, edges between i,j if gcd(i,j)=1) is connected. Also we need to compute Mmax(n) = number of coprime pairs.
But note: The problem statement: "Construct a relatively prime graph with n vertices and m edges such that it is connected and it contains neither self-loops nor multiple edges." It does not require that the graph be a subgraph of G_n? Actually it does: edges must satisfy gcd(v,u)=1. So indeed edges are only allowed between coprime pairs. So the set of allowed edges is exactly E_allowed = {{i,j} | 1 <= i < j <= n, gcd(i,j)=1}. So any graph we construct must be a subgraph of that allowed graph.
Thus connectivity of the allowed graph is necessary for existence of any connected graph using all vertices.
We need to check connectivity for n up to 1e5. Also Mmax is up to about? number of coprime pairs among numbers 1..n. That's essentially the number of pairs of numbers up to n that are coprime. That can be computed as sum_{i=1}^n φ(i) - 1? Actually number of pairs (i,j) with i<j and gcd(i,j)=1 = (1/2) * (∑_{i=1}^n φ(i) * floor(n/i)?) Not exactly. Better: total unordered pairs = n(n-1)/2. Subtract pairs that share a common divisor >1. But it's easier to think that it's essentially the number of coprime pairs in the range 1..n, which is known: ~ (6/π^2) n^2. For n=1e5, Mmax ~ 0.6079 * (1e5)^2 /2? Wait compute: The probability that two random integers are coprime is 6/π^2 ≈ 0.6079. So number of coprime unordered pairs ~ (6/π^2)n(n-1)/2 ≈ 0.6079 * (1e599999)/2 ≈ 0.6079 * 5e9 ≈ 3.04e9, which is > 1e5. Actually m is up to 1e5 only, so m is relatively small compared to Mmax for n> something. So m ≤ 1e5, n ≤ 1e5, but Mmax can be huge (like O(n^2)), but m is limited to 1e5, so we don't need to consider huge Mmax values; we just need to know if m ≤ Mmax, and Mmax can be computed or estimated, but since m max is 1e5, for n >= something like 500? Actually the number of coprime pairs grows quadratically, so for n ~ 500, Mmax ~ 0.6079 * (500499)/2 ≈ 0.6079124750 ≈ 75800, which is less than 1e5? Wait compute carefully: n=500, total pairs = 500499/2 = 124750. Coprime fraction ~0.6079, so coprime pairs ~ 75800. That's < 100k. For n=600, total pairs = 600599/2 = 179700, *0.6079 ≈ 109200, which may exceed 100k. So around n~600, Mmax becomes > 1e5. But m is also up to 1e5, so for n less than about 600, Mmax may be less than 1e5, so we must check actual Mmax.
However, we can compute Mmax for n up to 1e5 by iterating? That would be O(n^2) too expensive. But we can compute Mmax exactly by inclusion-exclusion or using phi values: number of pairs (i,j) with 1≤i<j≤n and gcd(i,j)=1 = ∑_{i=1}^n φ(i) * floor(n/i) - 1? Let's derive.
Consider all ordered pairs (a,b) with 1 ≤ a,b ≤ n, gcd(a,b)=1. That count is 2 * (unordered coprime pairs) + n (since (i,i) also counted). Actually ordered pairs (a,b) with a,b ≤ n and gcd(a,b)=1: that is known to be ∑{i=1}^n φ(i) * floor(n/i)*2 - 1? Wait there is known result: ∑{k=1}^n φ(k) * floor(n/k) * floor(n/k)? Not exactly.
Better: Number of coprime pairs (i,j) with 1 ≤ i,j ≤ n is known: 1 + 2 ∑{i=2}^n φ(i). Actually that's for pairs with i ≤ j? Let's recall: For i from 1 to n, the number of j with 1≤j≤i and gcd(i,j)=1 is φ(i). So total ordered pairs (i,j) with 1 ≤ i,j ≤ n and gcd(i,j)=1 = ∑{i=1}^n φ(i) * (number of j such that gcd(i,j)=1 and 1≤j≤n). But that's circular. Actually we can use mobius: ∑{i=1}^n ∑{j=1}^n [gcd(i,j)=1] = ∑{d=1}^n μ(d) floor(n/d)^2. That's a known identity. So the number of ordered coprime pairs is S_ordered(n) = ∑{d=1}^n μ(d) * floor(n/d)^2. Then unordered pairs (i<j) are (S_ordered(n) - n)/2 because we subtract n pairs (i,i) (which are coprime? gcd(i,i)=i, which is 1 only when i=1. Actually i=i, gcd(i,i)=i, so for i>1, gcd(i,i) >1, so they are not coprime. But the ordered count includes pairs (i,i) only if gcd(i,i)=1 which only holds for i=1. Because gcd(1,1)=1. So careful: The condition gcd(i,j)=1 is for ordered pairs. For i=j, gcd(i,i)=i, so it is 1 only when i=1. So the diagonal entries (i,i) are mostly not counted. So S_ordered(n) does NOT count (i,i) for i>1 because gcd>1. So the count of ordered coprime pairs includes only the (1,1) maybe. Actually for i=j>1, gcd(i,i)=i>1, so not coprime. So the ordered count is sum over all (i,j) with gcd=1. So then the number of unordered pairs (i,j) with i<j and gcd=1 is (S_ordered(n) - [count of (i,i) that satisfy]) / 2. But the only (i,i) that satisfy is i=1. So subtract 1 if n≥1. Then divide by 2. So Mmax = (S_ordered(n) - 1) / 2 for n≥1? Let's test for n=1: vertices =1, Mmax =0 because no edge. S_ordered(1) = sum_{d=1}^1 μ(1)*1^2 = 1. Then (1-1)/2=0, correct. For n=2: vertices 1,2. Allowed edges: (1,2) since gcd(1,2)=1. So Mmax=1. Compute S_ordered(2): μ(1)floor(2/1)^2=14=4; μ(2)floor(2/2)^2 = -11^2 = -1; sum=3. Subtract 1 =>2, /2 =>1. correct. For n=3: vertices 1,2,3. Allowed edges: (1,2),(1,3) (2,3? gcd(2,3)=1) so all three pairs are coprime? Check: gcd(2,3)=1, yes. So total pairs =3. Mmax=3. S_ordered(3): d=1: floor(3)^2=9; d=2: μ(2)=-1, floor(3/2)=1 =>1; d=3: μ(3)=-1, floor(1)=1 =>1; sum=9-1-1=7. subtract 1 =>6, /2=3, correct. For n=4: pairs: (1,2),(1,3),(1,4); (2,3) gcd=1, (2,4) gcd=2 no, (3,4) gcd=1. So allowed: 1-2,1-3,1-4,2-3,3-4 =>5 edges. S_ordered(4): d=1:16; d=2: -1 * (2)^2? floor(4/2)=2 => -4; d=3: μ(3)=-1, floor(4/3)=1 => -1; d=4: μ(4)=0? Actually μ(4)=0 because square factor. So sum=16-4-1=11; subtract 1=10/2=5, correct.
Thus Mmax = (∑_{d=1}^n μ(d) * floor(n/d)^2 - 1) / 2.
We can compute Mmax up to n=1e5 using sieve to compute μ(d) up to n, then sum over d. That's O(n). So we can compute Mmax efficiently.
Now, connectivity of G_n: When is the graph of numbers 1..n with edges between coprime numbers connected? We need to analyze.
Let's think about the structure. For n=1, it's trivially connected (though no edges). For n=2, graph has vertices 1,2 and edge (1,2) because gcd=1 => connected. For n=3, all three edges exist, connected. For n=4, as above: edges: 1-2,1-3,1-4,2-3,3-4. Is it connected? Yes, vertex 2 connected to 1, vertex 3 connected to both, vertex 4 to 1 and 3. So connected. For n=5, check pairs: many edges. Typically, vertex 1 is connected to all others because gcd(1, any)=1. So vertex 1 is a universal neighbor. Therefore, for any n >= 2, vertex 1 is connected to every other vertex. That immediately makes G_n connected! Because from any vertex v, there is an edge (1,v). So the graph is a star centered at 1, at minimum. Wait, condition: edge exists if gcd(1,v)=1. Since gcd(1,v)=1 always. So indeed for any vertex v, edge (1,v) is allowed. So yes, vertex 1 is adjacent to all other vertices. Therefore G_n is always connected for n ≥ 2. For n=1, it's trivial.
Thus connectivity of G_n is always true. So the necessary condition is simply m between n-1 and Mmax inclusive.
But wait: Are there any subtle restrictions? For n=1, m must be 0, and graph is trivially connected? Usually a graph with one vertex and no edges is considered connected. So for n=1, if m=0 then "Possible", else "Impossible". And note: for n=1, there is no edge (v,u) with v≠u, so Mmax=0. So condition holds.
Thus the only constraints are:
- m must be at least n-1.
- m must be at most Mmax (total number of coprime pairs).
If these hold, we can construct a graph.
Now, we must also consider that we need to output exactly m edges, and the graph must be connected. Since vertex 1 connects to all others, we can easily build a spanning tree: connect vertex 1 to all other vertices (n-1 edges). That yields a tree (a star). Then we need to add additional edges to reach m. As long as we have remaining allowed edges (that we haven't used yet) we can add them arbitrarily, ensuring no duplicates.
Thus construction approach:
-
Compute Mmax (if needed, we can compute only when n-1 ≤ m ≤ some bound? But we need to know if m > Mmax to output Impossible. So compute Mmax.
-
If m < n-1 or m > Mmax, output Impossible.
-
Else output Possible and then edges.
Construct edges:
-
First, add all edges (1, i) for i = 2..n. That gives n-1 edges. If m == n-1, output exactly these.
-
If m > n-1, we need to add extra edges among other pairs, ensuring they are coprime and not already added.
We must avoid duplicate edges and self-loops. So we can generate all allowed edges (i,j) with i<j, gcd(i,j)=1, that are not of the form (1,i) (since those are already used). Then take the first (m - (n-1)) such edges and output them together with the star edges.
But careful: generating all allowed edges could be O(n^2), which is too large (n up to 1e5). However, m is at most 1e5. So we only need to output up to 1e5 edges. We can generate edges on the fly, iterating over pairs and checking gcd, but we need to be careful to not exceed time.
We need an algorithm to list enough coprime pairs (i,j) for i<j, that are not (1,i), up to a count of K = m - (n-1), which is at most 1e5 as well (since m ≤ 1e5). So we need to generate K edges efficiently without enumerating all O(n^2) pairs.
We can generate by iterating i from 2 to n, and for each i, iterate j from i+1 to n, but that would be too many if K is small but we still might need to scan many. But we can early stop when we have collected enough edges.
Since m ≤ 1e5, K is ≤ 1e5. So we can afford to generate edges up to that many by some systematic approach.
One approach: For each i from 2 to n (or maybe 2 to something), we can find j > i such that gcd(i,j)=1. Since vertex 1 already connects to all, we can generate extra edges among numbers >1 that are coprime. But note that many pairs (i,j) with i,j>1 may not be coprime. But we can generate enough coprime pairs.
We can also generate all pairs (i,j) where i and j are primes; primes are pairwise coprime? Wait: two distinct primes are coprime, yes. So if we take primes >1, any two distinct primes are coprime. So we could use edges between primes. For n up to 1e5, number of primes up to 1e5 is about 9592 (pi(1e5) ~ 9592). The number of unordered pairs among primes is about 46 million, which is huge, but we only need up to 1e5 edges, which is much smaller. So we could generate edges between primes: take pairs of distinct primes in increasing order until we have enough.
But we must also consider that not all vertices are primes. However, we can use any allowed edges, not only primes. Using prime pairs is safe because they are always coprime. Also edges like (prime, composite) can be coprime if the composite is not a multiple of that prime. But to keep generation simple, we can restrict to prime pairs, because we have many primes and we need at most 1e5 edges, and the number of primes up to 1e5 is 9592, which gives about 45 million pairs, far more than needed. However, we need to ensure that the set of edges we output, together with the star edges (1,i), yields a connected graph. The star already connects all vertices via vertex 1, so the graph remains connected regardless of additional edges. So we can add any extra edges among vertices >1 (including primes and composites) without affecting connectivity.
Thus we can generate extra edges as follows:
We maintain a list of vertices from 2 to n. For each i from 2 to n, we can iterate j from i+1 to n and test gcd(i,j) == 1. But that would be O(n^2) in worst case if we scan all, but we can stop once we have enough edges.
However, worst-case scenario: m = Mmax, which could be about ~0.6 * n(n-1)/2. For n=1e5, that is about 3e9, which is >1e5, but we only need to output up to 1e5 edges. So even if m is max (1e5), we need to output 1e5 edges. So we need to generate 1e5 coprime pairs (i,j) with i<j, not using (1,i). We can do this by a method that enumerates pairs in some order and stops after 1e5.
One simple way: iterate i from 2 to n, and for each i, iterate j from i+1 to n and if gcd(i,j)==1, add edge (i,j). Keep track of count; stop when we have K edges. However, for i small, the number of j with gcd(i,j)=1 is roughly φ(i)/i * (n-i). But if we iterate naively, for i=2, we check all odd numbers up to n; that's about n/2 checks, which for n=1e5 is 50000, okay. For i=3, check numbers not divisible by 3; about 2/3 * n ≈ 66666. Summing over i up to maybe a few hundred, we could accumulate many edges. Since total needed K ≤ 1e5, we could stop after scanning i up to some moderate number. But we need to guarantee we can find enough edges even when K is large (like 1e5). However, for n=1e5, there are many coprime pairs, so scanning small i yields many edges quickly.
Let's estimate: For i=2, number of coprime j>2: j odd (except maybe j=2? j>2). gcd(2, j)=1 if j is odd. Among numbers >2 up to n, about half are odd => roughly (n-2)/2 ≈ 50000. That alone gives up to 50000 edges. For i=3, numbers not divisible by 3: about 2/3*(n-3) ≈ 66666. But careful: some of those may have already been counted when i=2? No, we are generating edges (i,j) with i fixed. For i=3, j > 3. They are distinct edges. So after scanning i=2 and i=3, we would already have ~116k edges, which exceeds 100k. So we can definitely collect enough by scanning small i. However, we must ensure not to generate duplicate edges? In this scanning method, each edge (i,j) is generated exactly once because we fix i and then j>i. So duplicates not possible. So we can simply: for i from 2 upwards, for j from i+1 to n, if gcd(i,j)==1, add (i,j) to list, break when list size reaches K. Complexity: worst-case we might need to scan many j for each i, but total number of gcd checks will be about O(K + n) maybe a bit more. But consider K=100,000; we will likely stop after i=2 and some j. For i=2, we examine j from 3 to n. In worst-case, if K is small, we may only need to examine a few j for i=2. But if K is large, we may need to examine many j. However, the total number of gcd operations we perform is roughly the number of pairs we consider until we get K valid edges. Since the density of coprime pairs is about 0.6, we would need to examine roughly K/0.6 ≈ 167k pairs. This is acceptable. But is it always? Suppose n is small, like n=1000, and m is close to Mmax, say m = Mmax ~ 0.6500k = 300k? But m is capped at 1e5, so m ≤ 1e5. For n small, Mmax might be less than 1e5? Actually for n around 500, Mmax ~75k < 100k, so m max is ≤75k. For n=600, Mmax ~109k >100k, but m max is 100k. So m is at most 100k. So K = m - (n-1) ≤ 100k. So we need at most 100k valid edges. The number of pairs examined to get that many valid edges will be at most about 167k, which is fine. But careful: when n is small, say n=10, Mmax = number of coprime pairs among 1..10. Let's compute: total pairs =45; coprime pairs? list: (1,2)...(1,10) =>9; (2,3)=1, (2,5)=1,(2,7)=1,(2,9)=1? gcd(2,9)=1 yes => (2,3),(2,5),(2,7),(2,9); (3,4)=1,(3,5)=1,(3,7)=1,(3,8)=1,(3,10)=1? gcd(3,10)=1 => (3,4),(3,5),(3,7),(3,8),(3,10); (4,5)=1,(4,7)=1,(4,9)=1? gcd(4,9)=1 yes, (4,11 no) so (4,5),(4,7),(4,9); (5,6)=1,(5,7)=1,(5,8)=1,(5,9)=1? gcd(5,9)=1, (5,? ); (6,7)=1? gcd(6,7)=1, (6,?); etc. Actually there are many. Anyway, Mmax for n=10 is 31? Let's compute quickly: unordered coprime pairs for n=10: I recall formula: number of coprime pairs up to 10 is something like? I can compute S_ordered(10): d=1:100; d=2:-15^2= -25; d=3:-13^2= -9; d=5:-12^2= -4; d=7:-11^2= -1; d=... Actually need all: μ(1)=1, μ(2)=-1, μ(3)=-1, μ(4)=0, μ(5)=-1, μ(6)=1? μ(6)=1? μ(6)=1 because 6=23, squarefree even => μ(6)=1? Actually μ(6)=1? Wait μ for squarefree with even number of prime factors is 1? No: μ(n) = 0 if has squared prime factor; else = 1 if n has even number of prime factors, -1 if odd number. So 6 has two prime factors (2,3) -> even -> μ(6)=1. But careful: μ(6) = (-1)^2 = 1. So positive. So contributions: d=6: floor(10/6)=1 -> +1; d=7: μ(7)=-1, floor(1)=1 -> -1; d=8: μ(8)=0; d=9: μ(9)=0; d=10: μ(10)=1? 10=2*5 -> two primes even -> μ(10)=1, floor(1)=1 -> +1. Also d=?? Actually we should go up to 10. So sum = 100 -25 -9 -4 -1 +1 -1 +1? Plus maybe d=?? Let's compute systematically later but not needed. So S_ordered ~? Regardless, Mmax for n=10 is not huge, but still could be around 30? Actually I can compute directly: All pairs (i,j) with i<j <=10 and gcd=1. List all pairs excluding those with gcd>1: (2,4),(2,6),(2,8),(2,10); (3,6),(3,9); (4,6),(4,8),(4,10)? gcd(4,6)=2, (4,8)=4,(4,10)=2; (5,10)? gcd=5; (6,8)=2,(6,9)=3,(6,10)=2; (8,10)=2; Also (2,? already counted). Also maybe (8,9)=1? Actually (8,9)=1. So let's count coprime pairs: total pairs =45. Subtract non-coprime pairs: pairs sharing factor >1. Count them: (2,4),(2,6),(2,8),(2,10) ->4; (3,6),(3,9) ->2; (4,6),(4,8),(4,10) ->3; (5,10) ->1; (6,8),(6,9),(6,10) ->3; (8,10) ->1; (2,? ) also (2,? )? (2,? ) we included all even numbers? also (2,? ) maybe (2,? ) (2,? )? Also (3,? ) (3,? )? (3,? ) 3 & 12 out of range. Also (4,2) already counted. Also (6,? ) (6,4) etc. Also (9,? ) (9,3) counted; (9,6) counted? (9,6) gcd=3 counted as (6,9). Also (10,? ) (10,5) counted. Also (2,? ) maybe (2,? )? So total non-coprime = 4+2+3+1+3+1=14. So coprime pairs =45-14=31. So Mmax=31. So for n=10, m max is 31. Then n-1=9, so K max = 22. That's small.
So generating extra edges by scanning pairs is fine.
But we need to compute gcd for each candidate pair. Doing gcd for up to maybe 200k pairs is fine. gcd is O(log n). So total operations ~200k * log(1e5) ~ fine.
Thus simple method: For i from 2 to n:
for j from i+1 to n:
if gcd(i,j) == 1:
add edge (i,j)
if we have enough (K) break out both loops.
But this double loop could be O(n^2) if K is large but still m <= 1e5 so K <= 1e5. However, if we break early, it's fine. But need to ensure that we don't iterate through all j for each i even after we have enough. We'll break appropriately.
However, there is a nuance: Suppose n=100000 and we need K=100000 edges. As we argued, scanning i=2 gives about 50000 edges (since half of numbers >2 are odd). That's less than 100000. Then we go to i=3, we can get about 66666 edges, but we only need an extra 50000 after using i=2. So total number of pairs examined for i=2: we need to examine all odd numbers up to n to collect those 50000 edges? Actually for i=2, we need to collect all odd numbers j>2. If we need exactly 50000 edges, we would have to go through all odd j up to n. That's about 50000 checks. Then for i=3, we need to collect additional edges until we reach total K. So we may need to scan a significant portion of j for i=3 as well. But total checks will be roughly number of edges collected / density. Since density for i=2 is 0.5, to collect 50000 edges we need to check about 100000 pairs (since half are valid). Actually for i=2, we can collect edges for each j>2 with odd j. To collect 50000 edges, we need to go through all odd j from 3 to n (since each odd j gives an edge). That is about (n-2)/2 ≈ 49999 checks. So that's 50k gcd checks. Then for i=3, we need to collect more edges. But we may not need to scan all j>3; we might stop early when we have enough. So total gcd checks could be on order of 150k. That's fine.
Thus simple scanning algorithm is acceptable.
But we must be careful about time: For each i, we iterate j from i+1 to n. For i large, the range is large, but we might not need to iterate many of them because K is already satisfied early. The worst-case scenario for scanning would be when we need many edges and the early i's provide few edges? But as argued, i=2 gives many edges, i=3 gives many, etc. For n large, the number of coprime partners for each i is roughly φ(i)/i * (n-i). For i small, φ(i)/i is not too small: for i=2 it's 1/2, for i=3 it's 2/3, for i=4 it's 1/2 (since φ(4)=2, ratio 0.5), for i=5 it's 4/5=0.8, for i=6 it's φ(6)/6=2/6≈0.333, for i=7 6/7≈0.857, etc. So on average, density is about 0.6. So we will accumulate edges quickly.
Thus algorithm should be fine.
However, we also need to compute Mmax exactly to check if m > Mmax. We can compute Mmax using the mobius sum. Since n up to 1e5, we can precompute μ up to n via linear sieve. Then compute sum_{d=1}^n μ(d) * floor(n/d)^2. That sum is O(n). Then Mmax = (sum - 1) // 2.
But careful: For n large, say n=1e5, floor(n/d) changes at about sqrt(n) points. But we can just loop d from 1 to n, computing floor(n/d) each time. That's O(n) which is 1e5, fine. So we can compute Mmax efficiently.
Edge case: n=1. Then Mmax = 0. m must be 0 to be possible. And graph is trivially connected. There are no edges to output. So we handle.
Implementation steps:
- Read n,m.
- If n == 1:
- If m == 0: print "Possible" (and no edges? The problem says "The i-th of the next m lines should contain the i-th edge". So if m=0, just print "Possible" and that's it. Probably we need to output nothing after. Acceptable.)
- Else print "Impossible". Done.
- Compute Mmax.
- Precompute mu[1..n] using linear sieve.
- sum_ordered = 0
- for d = 1 to n: sum_ordered += mu[d] * (n//d) * (n//d)
- Mmax = (sum_ordered - 1) // 2
- But note: For n=0? Not needed.
- If m < n-1 or m > Mmax: print "Impossible". Return.
- Else print "Possible".
- Then output edges.
Construct edges:
- We'll have a list edges = [] (vector of pairs).
- First, add edges (1, i) for i = 2..n. This gives n-1 edges.
- If m == n-1, output these edges (order as added).
- Else we need extra K = m - (n-1) edges among other pairs (i,j) with 2 ≤ i < j ≤ n and gcd(i,j)=1.
- We'll generate by iterating i from 2 to n:
for j from i+1 to n:
if gcd(i,j) == 1:
edges.append((i,j))
if len(edges) == m: break outer loops.
if we have already collected m edges, break.
After inner loop, check if enough.
But careful: We have already added star edges to edges list. So we should start with edges list containing the star edges. Then we need to add extra until total size = m.
Pseudo:
edges = []
for i in range(2, n+1):
edges.append((1, i))
if len(edges) == m: break # but star gives exactly n-1 edges, if m == n-1 we stop after adding them. But if m < n-1 we already returned impossible. So m >= n-1.
if len(edges) < m:
K = m - len(edges)
for i in range(2, n+1):
for j in range(i+1, n+1):
if gcd(i, j) == 1:
edges.append((i, j))
if len(edges) == m: goto done
done:
But this double loop may be O(n^2) if we don't break early. However we break when edges size reaches m. Since m <= 1e5, we won't iterate too many pairs; but need to ensure that the loops don't continue after we have enough. Use a flag.
But we must also consider that we might run out of pairs before reaching m? That would mean Mmax < m, which we already checked, so there are enough.
Implementation details:
-
Use Python for convenience, but be mindful of performance. 1e5 edges and up to maybe 200k gcd checks. Python's math.gcd is fast.
-
Precompute mu up to n using linear sieve; we can also compute Mmax using sieve but we might also compute Mmax directly by counting coprime pairs using a simpler method: we could compute the number of coprime pairs by iterating i and using phi? But mobius sum is simpler and O(n). We'll implement mu sieve.
Alternatively, we can compute Mmax by generating all allowed edges and counting? That would be too heavy. So we'll use mobius.
But we also need to be careful about integer overflow? Python big ints fine.
Now, connectivity: star ensures connectivity, fine.
Now, test with given examples.
Example 1: n=5, m=6. Compute Mmax: n=5; coprime pairs: (1,2),(1,3),(1,4),(1,5),(2,3),(2,5? gcd(2,5)=1),(3,4),(3,5? gcd(3,5)=1),(4,5? gcd(4,5)=1). Let's list all: total pairs =10. Non-coprime: (2,4) gcd2, (2,? ) (2,? ) (2,? ) also (3,? ) (3,? ) (4,? ) maybe (4,2) counted, (4,? )? Actually compute: pairs: (1,2),(1,3),(1,4),(1,5); (2,3) gcd1,(2,4) gcd2,(2,5) gcd1; (3,4) gcd1,(3,5) gcd1; (4,5) gcd1. So allowed edges: (1,2),(1,3),(1,4),(1,5),(2,3),(2,5),(3,4),(3,5),(4,5). That's 9 edges. Wait also (2,? )? That's all. So Mmax=9. n-1=4. m=6 is between. So possible. Our construction: star edges: (1,2),(1,3),(1,4),(1,5) -> 4 edges. Need 2 more. Then iterate i=2: j=3: gcd(2,3)=1 -> add (2,3). Need one more. j=4: gcd(2,4)=2 skip; j=5: gcd(2,5)=1 -> add (2,5). Now have 6 edges. Output order: star edges first, then (2,3),(2,5). That's a valid graph, but the example output is different: they gave edges: 2 5, 3 2, 5 1, 3 4, 4 1, 5 4. That is also valid. So any answer works.
Second example: n=6, m=12. Compute Mmax for n=6. Let's list: total pairs=15. Coprime pairs? Compute S_ordered: d=1:36; d=2:-13^2=-9; d=3:-12^2=-4; d=4:0; d=5:-11^2=-1; d=6: μ(6)=1? 6=23 -> even number of primes -> μ(6)=1, floor(6/6)=1 => +1; sum=36-9-4-1+1=23? Actually also d=??? Wait d=5 gave -1, d=6 gave +1, d=7+? Only up to 6. So sum_ordered = 36 -9 -4 -1 +1 = 23. Then Mmax = (23-1)/2=11. So max edges = 11. m=12 > 11 -> Impossible. matches example.
So our logic matches examples.
Now, need to consider n up to 1e5, m up to 1e5. We must ensure that Mmax computation is correct for all n. Edge Cases:
-
n=2: Mmax=1, m must be 0 or 1? n-1=1, so only m=1 possible. m=0 would give disconnected (two isolated vertices). So m must be 1. So for n=2, only possible m is 1 (if m=0 would be disconnected; but check: if m=0, graph with 2 vertices and no edges is not connected. So condition m >= n-1 ensures connectivity. So m=0 is impossible for n=2, correct.
-
n=1: n-1=0, m must be 0. m>0 impossible.
Now, about generating extra edges: we must ensure that we don't accidentally include edges (1,i) again. In our iteration we start i from 2, j>i, so we won't include any edge with 1. So fine.
But we must also consider that we might generate edges (i,j) where gcd(i,j)=1 but they are already present from star? No, star only includes edges with 1, so no overlap.
Now, time complexity: For generating extra edges, the double loop can be implemented with break conditions.
But we need to be careful: if m is large and close to Mmax, we might need to generate many edges (up to 1e5). For i=2, we might generate around 50k edges. That's fine. For i=3, we might generate many more. The loops will iterate j from i+1 to n. For i=2, we iterate j=3..n, that's up to 99998 iterations, but we will break after collecting enough edges. However, if needed edges after star is exactly m = Mmax, and Mmax could be e.g., for n=60000, Mmax is huge > 1e5, but m ≤ 1e5, so K ≤ 1e5. So we will collect at most 1e5 edges total, so total iterations in the inner loops across all i will be roughly O(K / density) + maybe some extra if we go through entire range for some i? Let's consider worst-case scenario: Suppose we need K=100000 edges, and the first few i provide many edges but not enough, we might have to scan a significant portion of j for i=2 and i=3. For i=2, to collect all edges from i=2 (i.e., all odd j), we would need to scan all j from 3 to n. That's 99997 checks. That's about 1e5 checks, which is acceptable. Then for i=3, we might need to scan some j as well, maybe up to 1e5 checks. Total checks maybe 2e5 to 3e5. That's fine.
But there is a more extreme scenario: n is small, say n=1000, and m is near Mmax (which could be, say, 300k but m max 1e5, so m=1e5, but n=1000, Mmax maybe about 300k, so K = m - (n-1) = about 100k - 999 = 99k. In that case, we need to generate 99k extra edges. But number of possible edges among vertices 2..1000 is at most C(999,2) ≈ 498k. Among those, many are coprime (density ~0.6), so total coprime edges among >1 is Mmax - (n-1) (since Mmax includes edges with 1). Actually Mmax includes edges with 1, so the number of edges not involving 1 is Mmax - (n-1). For n=1000, Mmax ≈ 0.6079 * (1000*999)/2 ≈ 0.6079 * 499500 ≈ 303,500. So edges not involving 1 ≈ 303,500 - 999 = 302,501. So there are plenty. To collect 99k of them, we may need to scan a significant portion of all pairs (i,j). Could scanning up to maybe 200k pairs be enough? Density ~0.6, so 99k edges require about 165k checks. That is fine. However, the scanning algorithm as described loops i from 2 to n, and for each i loops j from i+1 to n, and breaks when enough edges collected. For n=1000, the number of possible checks if we go through all i is about 500k, but we break early after collecting 99k edges. Since density is ~0.6, we expect to stop after checking around 165k pairs, which is fine.
But for n=1000, scanning i=2 will check about 998 j's, which is <1000, not 998? Actually for i=2, j from 3..1000 => 998 checks. That yields about 499 edges (odd j). So after i=2 we have 499 edges, but we need 99k edges, so we continue. For i=3, j from 4..1000 => 997 checks, yields about 2/3997 ≈ 665 edges. Now total edges from i=2,3 is about 1164, still far from 99k. So we need to continue to larger i. For i up to maybe 200, each i contributes roughly (n-i) * density edges. The cumulative sum of (n-i) for i from 2 to some X is roughly (n-2)+(n-3)+...+(n-X) = (X-1)(2n - X - 2)/2. To get total checks of 165k, we need to go up to some X where cumulative checks ~165k. For n=1000, (n-2)=998. Sum of checks from i=2 to i=k is roughly sum_{i=2}^{k} (n-i) = (k-1)(2n - k - 2)/2. For k=200, sum = 199(2000 - 200 -2?) Actually 2n=2000, minus k=200 ->1800, minus2 =1798? Wait compute: 2n - k - 2 = 2000 - k -2 = 1998 - k? Better: sum_{i=2}^{k} (n-i) = sum_{t= n-k}^{n-2} t? Let's compute directly: number of checks for i=2: n-2; i=3: n-3; ... i=k: n-k. So total = (n-2)+(n-3)+...+(n-k) = (k-1)*n - sum_{i=2}^{k} i = (k-1)n - ( (k(k+1)/2 - 1 ) ). That's (k-1)n - (k(k+1)/2 -1) = (k-1)n - k(k+1)/2 +1. For n=1000, k=200: (199)1000=199,000 - (200201/2=20100) +1 = 199,000 -20,100 +1 = 178,901. So checks after i=200 is about 179k, which is around our needed 165k. So we would need to iterate up to i around 200. That's fine.
Thus scanning up to a few hundred i's is okay. For n=1e5, we might need to scan up to i such that cumulative checks about 165k. Since for n large, n-2 is huge (100k), but we only need to check a portion of j for i=2? Actually for i=2, we might need to scan many j to collect edges. But we break after we have enough edges, so we might not need to scan all j for i=2 if we need fewer than the total number of odd j. However, if we need a lot of edges, we might end up scanning most of the j's for i=2. For n=100k, i=2 yields up to 50k edges (if we collect all odd j). If we need K=100k, after collecting all odd j from i=2 (about 50k), we still need 50k more. So we will need to scan i=3. For i=3, we need to collect additional edges. To get 50k edges from i=3, we might need to scan a large portion of j's for i=3 (since density 2/3). The number of j for i=3 is about 100k-3=99997. So scanning all of them would be 100k checks, which is still okay. So total checks: ~50k from i=2? Actually for i=2 we would scan all j to collect all odd edges; that's 100k checks. Then for i=3, we might need to scan about (2/3)? Actually to collect 50k edges from i=3, we need to examine about 75k j's if we stop after 50k edges? But we would add edges as we go; we can break as soon as we have enough total. After finishing i=2, we have 50k edges. We need 50k more. We start i=3 and iterate j from 4 to n; each time we encounter a coprime j, we add. We need 50k such additions. The number of coprime j among numbers 4..n is about (2/3)(n-3) ≈ 66,666. So we will likely need to scan most of the j's (up to maybe 66k) to collect 50k edges. So total checks: i=2: ~100k; i=3: ~66k; total ~166k. That's fine.
Thus double loop is acceptable.
But we need to ensure we don't exceed time in Python for 200k gcd calls? gcd is fast.
Now, we also need to compute mu up to n. That's O(n) with sieve, fine.
Now, we must be careful about memory: storing edges list up to 1e5 pairs, fine.
Implementation details for mu:
We can use classic linear sieve:
mu = [0](n+1)
mu[1] = 1
primes = []
is_composite = [False](n+1)
for i in range(2, n+1):
if not is_composite[i]:
primes.append(i)
mu[i] = -1
for p in primes:
if ip > n: break
is_composite[ip] = True
if i % p == 0:
mu[ip] = 0
break
else:
mu[ip] = -mu[i]
Works.
Now compute sum_ordered = 0
for d in range(1, n+1):
f = n//d
sum_ordered += mu[d] * f * f
But careful: mu[d] could be 0, skip? Not needed. Multiply.
Then Mmax = (sum_ordered - 1) // 2
But we need to verify for n=1: sum_ordered = mu[1](1//1)^2 = 11=1; Mmax=(1-1)//2=0 OK.
For n=2: sum= mu14 + mu21 = 4 + (-1)=3; Mmax=(3-1)//2=1 OK.
Edge case: n=0 not possible.
Now, we need to consider if m can be larger than Mmax but still possible if we use edges with gcd=1? No, Mmax is absolute maximum.
Now, after computing Mmax, we check.
Now output edges:
We'll generate star edges: for i in range(2, n+1): print(1, i)
But we need to output exactly m edges. If m == n-1, just output those. If m > n-1, we need to output additional edges.
But we must ensure that we don't exceed m when printing star edges? Actually we need exactly m edges total, so if m > n-1, we output all star edges (n-1) plus some extra edges. If m == n-1, output only star edges. That's fine.
However, what if m < n-1? Already impossible.
Now, for extra edges generation, we need to be careful: We might generate extra edges that duplicate some star edge? No.
Also, note that for n=1, we don't output any edges, but we printed "Possible" only.
Now, time complexity of generating extra edges: The double loop may be a bit slow in Python if we have to check gcd for many pairs. However, 200k gcd checks is trivial. But if we have to loop over many pairs and check gcd for each, we may do more than 200k if the density is low for some i? But density is at least about 0.3 for i=6? Actually for i=6, φ(6)/6=1/3, so density is 1/3. So worst-case density around 0.3? But for many numbers it's higher. So total checks needed to collect K edges is at most K / 0.3 ~ 333k. That's still fine.
But there is a scenario: n is large but m is also large, up to 1e5. Suppose n=1e5, K=1e5. We argued we need to scan many pairs. But is there any risk that scanning j from i+1 to n in a for loop in Python could be slow if we iterate over 100k j for i=2 and then 66k for i=3? That's 166k iterations, plus maybe some more for other i. That's fine. However, we also compute gcd for each j. math.gcd is implemented in C, fast.
Thus the simple approach should pass.
But we must consider that for n up to 1e5, we might need to iterate i from 2 to some value, but the inner loop for i=2 runs over j from 3 to 100000. That's 99998 iterations. That's okay. The total time for generating edges would be roughly O( (n) * something ) but limited by early break. Worst-case could be if K is just a bit less than total number of possible edges not involving 1? Could K be close to Mmax - (n-1) and Mmax could be huge? But m ≤ 1e5, so K ≤ 1e5, and Mmax - (n-1) could be huge for large n, so we will always break early relative to full enumeration.
Now, is there any scenario where we cannot find K extra edges because we run out of pairs in our scanning order? Our scanning order covers all pairs (i,j) with i>=2. Since there are at least K such coprime pairs (since Mmax - (n-1) >= K), we will eventually encounter them, as we scan all pairs in increasing order of i and j. So it's guaranteed to collect enough edges.
Now, potential issue: For large n, the double loop may be written in Python and break when edges list length reaches m. But we must ensure that the loops are nested correctly and we break out of both loops. We can use a flag or return.
Implementation:
def solve():
import sys, math
input = sys.stdin.readline
n,m = map(int,input().split())
if n == 1:
if m == 0:
print("Possible")
else:
print("Impossible")
return
# compute mu up to n
mu = [0](n+1)
mu[1] = 1
primes = []
is_comp = [False](n+1)
for i in range(2, n+1):
if not is_comp[i]:
primes.append(i)
mu[i] = -1
for p in primes:
if ip > n: break
is_comp[ip] = True
if i % p == 0:
mu[ip] = 0
break
else:
mu[ip] = -mu[i]
sum_ord = 0
for d in range(1, n+1):
f = n // d
sum_ord += mu[d] * f * f
Mmax = (sum_ord - 1) // 2
if m < n-1 or m > Mmax:
print("Impossible")
return
print("Possible")
# output edges
# We'll write to a list of strings and then join for speed
out_lines = []
# star edges
for i in range(2, n+1):
out_lines.append(f"1 {i}")
if len(out_lines) == m: # in case m == n-1
# we will have printed exactly m edges after star
# But note: we print star edges sequentially; if m == n-1, we will add exactly n-1 lines
# so after finishing loop, len == n-1 == m, so break after loop.
pass
if len(out_lines) < m:
# need extra edges
need = m - len(out_lines)
# iterate i from 2 to n
for i in range(2, n+1):
for j in range(i+1, n+1):
if math.gcd(i, j) == 1:
out_lines.append(f"{i} {j}")
need -= 1
if need == 0:
break
if need == 0:
break
# Now output
sys.stdout.write("\n".join(out_lines))
But there is an oversight: In the star edges loop, we add edges (1,i) for i=2..n. If m == n-1, after loop, out_lines will have exactly n-1 entries, which equals m, so we don't need extra edges. However, we might have prematurely added all star edges and then later we check if len(out_lines) < m and generate extra edges, which will be false.
But if m > n-1, after star edges, out_lines length = n-1, which is less than m, so we generate extra edges. Good.
Now, we must ensure that the extra edges generation does not duplicate edges already in star. Since star edges are (1,i), and extra edges have i,j >=2, no duplication.
Potential issue: The star edges are added first; but what if we need exactly m edges and m < n-1? Already impossible, so no issue.
Now, let's test with sample.
Sample1: n=5,m=6. Mmax=9, ok. star edges: (1,2),(1,3),(1,4),(1,5). out_lines length=4. need=2. Then extra loop: i=2, j from 3..5: j=3 gcd=1 => add (2,3) need=1; j=4 gcd=2 skip; j=5 gcd=1 => add (2,5) need=0 break. Output lines: order: 1 2,1 3,1 4,1 5,2 3,2 5. That's a valid graph, albeit different from sample. Acceptable.
Sample2: n=6,m=12 -> Mmax=11 -> Impossible, prints Impossible. Good.
Now, we should test some edge cases.
Case n=2,m=1: Mmax=1, star edges: (1,2) -> output exactly one line. Good.
Case n=2,m=0: m < n-1 => Impossible. Good.
Case n=1,m=0: output Possible (no edges). Should we output a blank line after? Usually just "Possible". The problem statement: "The i-th of the next m lines should contain the i-th edge", so if m=0, we just output the first line. So that's fine.
Case n=1,m=1: Impossible.
Now, large n: test n=100000,m=100000. Compute Mmax to ensure m <= Mmax. For n=100000, Mmax is huge (~3e9). So m <= Mmax holds if m=100000. Also n-1=99999, so m=100000 is >=99999, so possible. Our algorithm: star edges: 99999 edges, then need 1 extra edge. We'll iterate i from 2, j from i+1... Need to find one coprime pair with both >=2. The first such pair is (2,3) because gcd(2,3)=1. But note: (2,3) is coprime. But our scanning order: i=2, j starts from 3; gcd(2,3)=1 so we add (2,3). Then need=0, break. So total edges: 99999 + 1 = 100000. Output lines: many lines (100k). That's fine.
But we need to ensure that we don't exceed time generating star edges: iterating from 2 to 100000 and appending to list is fine.
Now, one more nuance: The problem statement says: "The vertices are numbered from 1 to |V|." So vertices are 1..n. Our edges are fine.
Now, about Mmax computation: Using mobius sum might cause large intermediate numbers: sum_ord could be up to about n^2? For n=1e5, n^2 = 1e10, times mu sign, sum is about 0.6079 * n^2 = 6e9. That's within Python int range.
Now, memory: storing mu array of size 100001 fine.
Now, we must be cautious about time for mu computation: O(n) with linear sieve is fine for 1e5.
Thus solution seems straightforward.
But we need to double-check that there are no hidden pitfalls: For n=1, we need to skip mu computation? We'll handle n=1 separately before mu.
Also, for n=2, mu computation works.
Now, the connectivity condition: star ensures connectivity. But what about the case n=0? Not applicable.
Now, consider scenario where n is such that Mmax is less than n-1? Is that possible? Let's check n=2: Mmax=1, n-1=1 => equal. n=3: Mmax=3, n-1=2 => Mmax > n-1. n=1: Mmax=0, n-1=0. So it seems always Mmax >= n-1? Is it possible that for some n, Mmax < n-1? That would mean the allowed graph does not have enough edges to form a spanning tree. But since vertex 1 is adjacent to all, there are n-1 edges from 1 to others. Those are all allowed. So Mmax includes those n-1 edges. So Mmax >= n-1 always, because at least the star edges are included. So the condition m >= n-1 is necessary, and we have m <= Mmax.
But wait, is it always true that gcd(1,i)=1 for all i? Yes. So star edges always allowed. So Mmax >= n-1. So condition is simply n-1 ≤ m ≤ Mmax.
Thus solution stands.
Now, about generating extra edges: we must ensure that we never generate an edge (i,j) that is already used? Could there be a case where (i,j) duplicates a star edge? No. Could there be duplicates within extra edges? Our scanning order only adds each (i,j) once (i fixed, j>i). So no duplicates.
Now, consider the possibility that we need to generate a very large number of extra edges (K up to 1e5) but our scanning might be too slow if for each candidate pair we compute gcd using math.gcd, which is fast. 200k-300k gcd calls is fine.
But we must be careful about the loop structure: In Python, nested loops with many iterations may be slower due to interpreter overhead. However, 200k iterations is fine. But if K is 100k and we need to check many pairs, maybe up to 300k iterations, still fine. But suppose n=100000, and we need to collect 100k extra edges, we may have to iterate over ~166k pairs. That's fine. But there is a nuance: The inner loop for i=2 runs j from 3..100000, that's 99998 iterations. Even if we break after adding needed edges, we still have to loop through all j until we break? Actually we break when need becomes 0. But in the inner loop, after we add an edge, we check if need == 0: break. So we can break early even within the inner loop. So we don't necessarily have to scan all j for i=2 if we already have enough edges before finishing. For instance, if need=1 after star edges, we would add (2,3) and break. That's quick. So worst-case when need is large, we may need to scan many j. However, the worst-case total number of inner loop iterations is approximately the number of pairs we need to examine until we have collected K edges. Since we always break after collecting K edges, total iterations is about the index of the K-th coprime pair in the scanning order. That scanning order is not necessarily optimal, but it's the natural order by increasing i then j. The K-th coprime pair will occur at some point; we need to estimate worst-case index. Could it be as high as O(n^2)? Possibly if K is large and we have many non-coprime pairs early? But the density is around 0.6, so the K-th coprime pair index is roughly K/0.6. For K=100k, that's 166k. So that's fine.
But wait, there is a subtle scenario: What if n is small relative to K? For example, n=500, Mmax ~75k, m could be 75k. Then K = m - (n-1) ≈ 75k - 499 = 74501. So we need to collect about 74.5k extra edges. The total number of possible edges among vertices 2..500 is C(499,2) ≈ 124k. Among them, the number of coprime edges is Mmax - (n-1) ≈ 75k - 499 = 70k? Actually Mmax includes edges with 1, so Mmax = (edges with 1) + (edges among >1). Edges with 1 = n-1 = 499. So edges among >1 = 75k - 499 ≈ 74.5k. So the total coprime edges among >1 is about 74.5k, which is almost all possible edges among >1? Actually total edges among >1 (i,j>1) is C(499,2) = 124251. Coprime edges among them is 74.5k, so density ~0.6. So we need to collect almost all of those 74.5k edges to reach Mmax. In such case, K ~ 74.5k, and total number of possible pairs among >1 is 124k. So to collect 74.5k edges, we would need to scan nearly all pairs, because we need to take almost every coprime pair, and we may not stop until we've collected almost all of them. In the worst case, if we need to collect all coprime edges, we would have to examine all pairs (i,j) with i>=2 to identify all coprime ones. That would be about 124k pairs, which is still fine. Actually 124k is not huge, it's fine.
But what if n is a bit larger, say n=1000, Mmax 303k, m max is 100k, so K max = 100k - 999 = 99k. The total pairs among >1 is C(999,2) ≈ 498k. So to collect 99k coprime edges, we need to examine about 99k/0.6 ≈ 165k pairs, which is less than 498k. So we won't scan all. So worst-case scanning might be when n is small because total pairs is small but K is close to total coprime edges among >1. But even for n=500, total pairs among >1 is 124k, scanning all 124k is fine. For n=400, total pairs ~ C(399,2)= 79401, which is less than 100k? Actually C(399,2)= 399398/2= 79401. So for n=400, total pairs among >1 is 79k. If we need K=79k (i.e., m=Mmax), we would scan all 79k pairs. That's fine. So scanning all pairs among >1 for n up to 1000 is at most ~500k, which is acceptable. But what about n=2000? C(1999,2) ≈ 2 million. That's still maybe okay? But we must consider that we might be scanning many pairs in Python loops, which could be slower. 2 million iterations with gcd computation might be borderline but still possible? 2 million gcd calls in Python might be ~0.1-0.2 seconds per million? Actually math.gcd is implemented in C and quite fast; looping 2 million times in Python might take ~0.2-0.3 seconds for the loop overhead, plus gcd calls. Let's estimate: 2 million simple operations in Python loop could be about 0.1-0.2 seconds? Actually Python loops are slower; typically 10 million simple loops take about 0.5-1 second? It depends. But 2 million loops with gcd might be around 0.3-0.5 seconds. That's acceptable for typical contest time limits (2 seconds). But if n is larger, say n=10000, total pairs among >1 is C(9999,2) ≈ 50 million. That's huge; we would never scan that many because m is at most 100k, and K is at most 100k. For n=10000, we could collect 100k edges from the first few i's without needing to scan all j for large i. For instance, i=2 yields about n/2=5000 edges? Actually for i=2, number of coprime j is about n/2 = 5000, which is far less than 100k. So we need to go to many i's. But the total number of checks we need to get 100k edges is roughly K/density ≈ 166k, not 50 million. So we won't scan all pairs for large n. So scanning all pairs only happens when n is relatively small, where total pairs is manageable. For n up to maybe 1000, total pairs ~500k, which is fine. For n around 2000, total pairs ~2 million, still okay. For n around 5000, total pairs ~12.5 million; but we won't need to scan all because K is at most 100k, and we can collect 100k edges from early i's? Let's check: For n=5000, i=2 gives about 2500 edges, i=3 gives about 3333 edges, i=4 gives about 2500 edges, i=5 gives about 4000 edges, i=6 gives about 1666 edges, etc. Summing up to i maybe 30 we could get enough. The total checks for i up to 30 is sum_{i=2}^{30} (5000 - i) ≈ 295000 - sum_{i=2}^{30} i ≈ 145000 - (30*31/2 -1) = 145000 - (465-1)= 144,536. So about 145k checks. So still fine. So scanning up to i=30 yields ~145k checks. So indeed we never need to go to large i. The only case we might need to go to large i is when n is small (so i range is limited). So overall scanning is efficient.
Thus the simple approach is acceptable.
Now, we must consider memory for out_lines: storing up to 1e5 strings, each maybe small, fine.
Now, we need to ensure that we don't accidentally generate extra edges beyond m. Already handled.
Now, we should also consider that the star edges themselves might exceed m if n-1 > m, but we already checked m >= n-1.
Now, we need to think about correctness of Mmax computation with mobius sum. But maybe there is a simpler bound: we can also compute Mmax by iterating i=1..n and counting coprime j>i? Not needed.
But we must ensure the mobius sum gives correct integer result. Since sum_ordered is integer, subtract 1 and integer division by 2 yields integer. But is sum_ordered always odd? For n>=1, sum_ordered seems always odd? Let's test n=1: 1 -> odd. n=2:3 odd, n=3:7 odd, n=4:11 odd, n=5:19? Actually we computed for n=5, S_ordered: from earlier: d=1:25; d=2:-12^2? floor(5/2)=2 => -4; d=3:-11^2=-1; d=4:0; d=5:-1*1^2=-1; sum=25-4-1-1=19? plus d=?? also d=6? no. So 19 odd. n=6:23 odd. So it seems always odd. Indeed, the number of ordered coprime pairs (i,j) with 1<=i,j<=n is always odd because (1,1) is counted and all others come in symmetric pairs? Actually (i,j) and (j,i) both counted, so total ordered pairs except (i,i) are even. Adding (1,1) makes sum odd. So S_ordered is odd. So (S_ordered-1)/2 integer. Good.
Now, we should consider potential overflow in sum_ord: Python int unlimited.
Now, we need to test some random cases to ensure no errors.
I'll manually test with n=4, m=5 (max). Mmax=5. Star edges: (1,2),(1,3),(1,4) ->3 edges. need=2. Extra: i=2,j=3 -> add (2,3) need=1; j=4 gcd(2,4)=2 skip; i=3,j=4 -> gcd(3,4)=1 add (3,4) need=0. Output: 1 2,1 3,1 4,2 3,3 4. That's a connected graph with 5 edges, valid.
n=4,m=4: star edges 3 edges, need=1. Extra: i=2,j=3 -> add (2,3) need=0. Output: 1 2,1 3,1 4,2 3. Connected? Yes, 1 connected to all, graph connected.
n=3,m=3: star edges (1,2),(1,3) ->2 edges, need=1. Extra: i=2,j=3 -> gcd=1 add (2,3). Output 3 edges, connected. Good.
Now, test n=6,m=11 (max). Compute Mmax for n=6: we earlier computed sum_ordered? Let's compute exactly: using mobius: d=1:36; d=2:-9; d=3:-4; d=4:0; d=5:-1; d=6:μ(6)=1? 6=2*3 even primes => μ(6)=1, floor(6/6)=1 => +1; also d=7? no. sum=36-9-4-1+1=23? Wait also d=?? We missed d=?? Actually we have d from 1 to 6. d=1,2,3,4,5,6. sum=36 -9 -4 -1? Actually need to include d=2,3,5,6. Let's recompute carefully:
n=6.
d=1: floor(6/1)=6 => 6^2=36; μ=1 => +36.
d=2: floor=3 => 9; μ=-1 => -9.
d=3: floor=2 => 4; μ=-1 => -4.
d=4: floor=1 =>1; μ(4)=0 => 0.
d=5: floor=1 =>1; μ=-1 => -1.
d=6: floor=1 =>1; μ(6)=? 6=2*3, squarefree, 2 primes => μ(6)=1? Actually μ(6) = (+1) because even number of primes? Wait rule: μ(n)= (-1)^k if n is product of k distinct primes. So for 6, k=2 => μ(6)=(-1)^2=1. So +1.
Thus sum = 36 -9 -4 -1 +1 = 23. So Mmax = (23-1)/2 = 11. Good.
Now m=11: star edges: 5 edges (1-2,1-3,1-4,1-5,1-6). need=6. Need to generate 6 extra edges among >1. How many are available? Mmax - (n-1) = 11-5=6. So exactly all coprime edges not involving 1. So we need to output all such edges. Let's list them: vertices 2..6. Coprime pairs: (2,3),(2,5); (3,4),(3,5); (4,5); (5,6)? Actually check: (2,4) no, (2,6) gcd=2 no, (3,6) gcd=3 no, (4,6) gcd=2 no, (4,5) yes, (5,6) gcd=1? gcd(5,6)=1 yes. Also (2,? ) (2,? ) (2,3),(2,5). (3,4),(3,5). (4,5). (5,6). Also (2,? ) maybe (2,? )? (2,7) no. Also (3,? )? That's it. (2,? )? Also (2,? )? (2,? ) (2,? )? So total: (2,3),(2,5),(3,4),(3,5),(4,5),(5,6) = 6 edges. So we need to output exactly these. Our scanning order: i=2: j=3 add, j=4 skip, j=5 add, j=6 gcd(2,6)=2 skip. So after i=2 we have edges (2,3),(2,5) -> 2 edges. i=3: j=4 add, j=5 add, j=6 gcd(3,6)=3 skip. So now have (3,4),(3,5) -> total 4. i=4: j=5 add, j=6 gcd(4,6)=2 skip -> total 5. i=5: j=6 add -> total 6. So we capture all. Good.
Now check n=6,m=10: star edges 5, need 5. Our scanning order as above would add (2,3),(2,5),(3,4),(3,5),(4,5) and then stop maybe after i=4 when we have 5? Actually after i=3 we have 4 edges; need 1 more; i=4, j=5 add -> need 0, stop. So output edges: (2,3),(2,5),(3,4),(3,5),(4,5). That's 5 extra, total 10 edges. Graph connected. Good.
Now, what about edge cases where there are no extra edges needed, we already handled.
Now, possible pitfalls: In generating extra edges, we might run out of edges because need > available? But we already ensure m <= Mmax, so total edges needed is <= Mmax. After star edges, we need K = m - (n-1). Available extra edges = Mmax - (n-1) >= K. So enough.
Now, consider n=2: star edges: (1,2) gives 1 edge. If m=1, we output only star edges, no extra needed. Good.
Now, consider n=1: handled separately.
Now, check n=0? Not in input.
Thus solution appears correct.
But we must be careful about reading input: it's one line with two integers.
Now, we need to think about memory/performance of mu sieve for n up to 1e5: it's fine.
Now, one more thought: Could there be any scenario where the graph is not relatively prime because we accidentally added an edge with gcd >1? No, we check gcd before adding extra edges, and star edges are all gcd(1,i)=1. So all edges satisfy.
Now, we should also verify that the graph we output has no multiple edges. Our generation ensures each edge is added at most once: star edges unique; extra edges unique and not overlapping star edges.
Now, consider the possibility that the order of edges might matter? The problem says print any.
Now, potential performance improvement: Instead of computing mu and Mmax, we could compute Mmax by counting coprime pairs via a formula using phi: Mmax = (1 + 2 * sum_{i=2}^{n} φ(i) )? Actually I've seen that number of coprime pairs (i,j) with 1 <= i <= j <= n? Let's derive: Number of pairs (i,j) with 1<=i<=j<=n and gcd(i,j)=1 is something else. But mobius is straightforward.
But maybe there's a simpler bound: Since we only need to check if m <= Mmax, we could compute Mmax by counting number of pairs (i,j) with i<j and gcd=1 using a loop over i and using phi: For each i, number of j>i with gcd(i,j)=1 = something like φ(i) * floor(n/i) - (something). Actually there is a known identity: ∑{i=1}^n φ(i) = 1 + 2 * number of coprime pairs? Not exactly. I think the number of coprime pairs (i,j) with 1 <= i < j <= n is 1/2 ( -1 + ∑{i=1}^n φ(i) * floor(n/i) * 2? Not sure. But mobius is easier to implement correctly.
But maybe we can avoid computing Mmax altogether if we can determine that for n large enough, Mmax is definitely > m because m ≤ 1e5, and we can estimate. However, for n small, Mmax may be less than m, so we need exact check. We could also compute Mmax by iterating i=1..n, and for each i, count numbers j>i with gcd=1 using a precomputed list of primes? That would be O(n sqrt(n)) maybe, but still could be heavy. So mobius is fine.
But wait, we need to compute mu up to n, which is O(n). That's fine.
Alternatively, we could compute Mmax by enumerating all pairs and counting? Not possible.
So we stick with mobius.
Now, one nuance: In computing sum_ord, we multiply mu[d] by floor(n/d)^2. floor(n/d) is integer division. For large n and d, floor may be 1 for d > n/2, etc.
Now, careful: For n up to 1e5, we can compute mu once.
But we must note that the time for computing mu and sum_ord is negligible.
Now, we should ensure that for n=1, we avoid mu computation because we handle separately. For n=2, it's fine.
Now, we should test with maximum values.
Case n=100000, m=100000:
- Compute mu up to 100000: O(100k) fine.
- Compute sum_ord: loop 100k times, each with multiplication, fine.
- Check m <= Mmax: Mmax huge, ok.
- Print star edges: 99999 lines. This might be heavy to output but acceptable; we accumulate in list and then join. That list will have 100k strings, which is okay.
- Then need=1, generate extra edge (2,3). So total 100k lines.
Now, about output: It says "The i-th of the next m lines should contain the i-th edge". So we just output edges in order we constructed.
Now, we might need to flush output? Using sys.stdout.write with join is fine.
Now, we might consider memory for out_lines: storing 100k strings, each about "1 12345" average maybe 6-7 chars + newline? Actually we store without newline? We store f"1 {i}" which is like "1 2", "1 3", etc. In list, each string is about 4-6 bytes plus overhead. 100k strings may use several MB, but still within typical limits (maybe ~10 MB). Acceptable.
Alternatively, we could output incrementally to avoid storing all lines. But it's simpler to store and then join; it's fine.
But careful: For n=100000, star edges are 99999 strings; plus maybe extra edges, total 100k strings. That's okay.
Now, what about time to compute mu? Implementation in Python must be efficient. Linear sieve with lists of size 100001 is okay.
Now, we should test with n=1e5, m = n-1 = 99999. That's minimal connected graph. Then we output only star edges. That's fine.
Now, also test with n=1e5, m = Mmax? But Mmax is huge ~3e9 > 1e5, so m max is 1e5, so m cannot be that high due to input limit. So m is always ≤ 1e5. So K = m - (n-1) is at most 1e5 - (n-1). If n is large, say n=100000, then n-1=99999, so m can be at most 100000, so K at most 1. So we only need at most 1 extra edge. So scanning will be very quick. So the heavy scanning only occurs when n is relatively small. So overall performance is excellent.
Thus the algorithm should pass.
Now, we need to be careful about correctness of Mmax for n=1? Already handled.
Now, verify Mmax for n=1: sum_ord = mu[1] * (1//1)^2 =1 => Mmax = (1-1)//2=0.
Now, also for n=2: works.
Now, what about n=100? Let's compute quickly to ensure no overflow issues.
Now, we might also think: Is there any case where m is valid but we fail to generate enough edges due to scanning order? Could it happen that our scanning order skips some edges that are necessary to reach K because we stop early after collecting K edges? No, because we collect edges as we encounter them; when we have collected K edges we stop. That's fine.
But we must ensure that we don't accidentally stop before having K edges because we exit loops incorrectly. Our break logic: In inner loop, after adding an edge, we decrement need, check if need == 0: break. This breaks only the inner loop. Then after inner loop, we check if need == 0: break the outer loop. So correct.
But there is a subtlety: The inner loop may end naturally when j reaches n+1. Then after that, we go to next i. That's fine.
Now, we must also consider that for some i, we might add no edges, but we still iterate through all j? But we break when need == 0; if need > 0, we go through all j for that i, but only until we have enough. Actually we break inner loop when need becomes 0, so we won't go through all j if we already have enough. So scanning is efficient.
Now, we must also be careful about using math.gcd: import math.
Now, what about generating star edges: we add them unconditionally. However, for n=1, we handled separately. For n=2, star edges include (1,2). That's fine.
Now, consider n=1, m=0: we output "Possible" only, no edges. That's correct.
Now, check n=1, m=0, our code: we have separate case, prints "Possible" and returns. No further output. That matches problem? Usually there should be no extra blank lines. That's fine.
Now, test with n=3, m=2 (minimal connected). n-1=2, m=2, so possible. Our star edges: (1,2),(1,3) -> exactly 2 edges. So output "Possible" then two lines. Graph is connected (star). Valid.
Now, test with n=3, m=4: Mmax=3, so impossible.
Now, test with n=4, m=6: Mmax=5, impossible.
Now, test with n=4, m=5: max, we already did.
Now, test with n=6, m=11: max, we did.
Now, test with n=6, m=7: star 5, need 2. Our scanning yields (2,3) and (2,5) maybe. That's fine.
Now, one more potential nuance: The problem states that vertices are numbered from 1 to |V|. It does not require the graph to be simple beyond no self-loops and no multiple edges. So our graph is simple.
Now, double-check the maximum m constraint: Input says 1 ≤ n, m ≤ 10^5. So m is at most 1e5. So we are safe.
Now, about constructing the graph, there is also possibility that we could generate extra edges by using a list of all primes. That may be even faster, but not necessary.
Now, final implementation details:
We'll implement solve() as described. We'll use fast I/O.
We need to compute mu efficiently. Let's implement linear sieve:
mu = [0](n+1)
mu[1] = 1
primes = []
is_comp = [False](n+1)
for i in range(2, n+1):
if not is_comp[i]:
primes.append(i)
mu[i] = -1
for p in primes:
if i * p > n:
break
is_comp[ip] = True
if i % p == 0:
mu[ip] = 0
break
else:
mu[i*p] = -mu[i]
Now compute sum_ordered.
But we can compute Mmax only if n > 1. For n=1 we already handled.
Now, we can also precompute the mobius up to 100000 if we want, but it's fine.
Now, for small n, we may compute mu quickly.
Now, let's also check: For n=1, we don't compute mu.
Now, we might also consider that m may be 0 for n>1? For n>1, m must be at least n-1, so m=0 is impossible. So that's fine.
Now, one more nuance: The graph must be connected. A star with center 1 is connected as long as n>=2.
Thus answer.
Now, we should test on some random values to ensure no errors. But we trust.
Now, implement.
But I recall that for large n, computing mu up to n using linear sieve might be a bit slow in Python if not optimized? 100k is fine. The linear sieve will have inner loop for each i and primes until i*p > n. Typically it's about O(n). For n=100000, it's fast.
Now, we also need to compute sum_ordered: loop d=1..n, compute f = n//d, add mu[d]ff. This is O(n). Good.
Now, output edges: For star edges, we can write to out_lines. But we also need to consider that out_lines may be large; we can write directly to sys.stdout during star edge loop to reduce memory. However, storing is okay. But to be safe, we could write star edges directly to sys.stdout, then generate extra edges and write them. However, we need to ensure we don't write extra newline issues. It might be simpler to collect all and then join.
But storing 100k strings is fine. Let's estimate memory: each string object overhead is large (like 49 bytes plus characters). 100k strings could be ~5-10 MB. That's okay. But to be more efficient, we can write incrementally. Since we have to output m lines, we can output as we generate, not store all. But we need to generate extra edges after star edges. But we could output star edges first, then generate and output extra edges. That would avoid storing them. However, we need to know when to stop outputting star edges: we output all n-1 star edges if m >= n-1. Then if m > n-1, we output extra edges. So we can do:
print("Possible")
output star edges (1,i) for i=2..n, but only up to m? Actually if m == n-1, output all star edges. If m > n-1, output all star edges and then extra edges. So we can:
for i in range(2, n+1):
print(1, i)
if m == n-1:
return
else:
need = m - (n-1)
# generate extra edges and print as we go.
This avoids storing all edges. But we must ensure that we don't print extra edges if need becomes 0 before generating all. We'll generate and print on the fly.
But careful: The order of edges doesn't matter, so we can output star edges first, then extra edges. That's fine.
But there's a nuance: In the problem statement, they say "The i-th of the next m lines should contain the i-th edge". But they don't require any specific order. So any order is fine.
Thus we can output star edges first, then extra edges. That's simpler and reduces memory.
So I'll implement output without storing list:
After printing "Possible", we'll loop i from 2 to n and print(f"1 {i}") directly to sys.stdout. But we must be careful about performance: printing 100k lines individually may be slower but still acceptable (usually 100k prints is fine). However, we can use sys.stdout.write with newline for each.
But to be safe, we can accumulate star edges into a list and then write, but either is fine.
Given that we also need to generate extra edges, we can print them as we generate.
So:
import sys
input = sys.stdin.readline
print = sys.stdout.write # But careful: print adds newline automatically? Actually we can use sys.stdout.write and manually add newlines.
Better: use sys.stdout.write for each line with '\n'.
But using built-in print with default settings will also be fine, but it might be slower due to flushing? It's okay for 100k lines.
I'll just use print() function with standard behavior, but ensure that we don't have extra spaces.
Alternatively, we can collect all lines into a list and then join for faster output; that is often recommended for many lines. Since m up to 1e5, building a list and joining is fine. I'll do that for simplicity.
But if we want to avoid storing, we can do direct printing.
Let's decide: I'll use a list out to accumulate lines, then sys.stdout.write("\n".join(out)). That is efficient.
We need to ensure that we don't have a trailing newline? It's okay if there is a newline after last line, typical.
Now, in generating extra edges, we can append to out.
Thus we can store up to m strings, which is <= 100k, fine.
So I'll keep using list.
Now, test on extreme n=100000, m=100000: out list size 100k. That's fine.
Now, we need to import math for gcd.
Now, let's code.
But wait, there is a potential issue: For n very large, the mu array and is_comp array of size n+1 (100001) is fine.
Now, one more nuance: For n=1, we skip mu but we need to output "Possible" only. That's fine.
Now, double-check the condition m <= Mmax: For n=2, Mmax=1. So m can only be 1. Good.
Now, consider n=3, Mmax=3, so m can be 2 or 3. Both possible.
Now, check n=4, Mmax=5, so m can be 3,4,5. But is m=3 possible? n-1=3, so star edges exactly 3, output possible. That gives star graph, which is connected. So yes. m=4 possible? Add one extra edge among >1. That's fine.
Now, everything seems consistent.
Now, let's also confirm Mmax for n=1: 0.
Now, we must ensure that the sum_ordered - 1 is even to divide by 2. It is always odd, but just in case due to bug, we can compute Mmax = (sum_ordered - 1) // 2. Because integer division in Python will floor if odd? Actually if sum_ordered is odd, (odd-1)//2 is integer. If sum_ordered even due to bug, (even-1)//2 would floor, giving integer but possibly off by 0.5? But sum_ordered is always odd, so fine.
Now, let's compute sum_ordered for n=1: 1, odd. n=2:3 odd. n=3:7 odd. n=4:11 odd. n=5:19 odd. n=6:23 odd. So consistent.
Now, implement.
I'll write the code.
Potential improvements: We could compute Mmax by counting coprime pairs using Euler totient cumulative: Mmax = sum_{i=1}^n φ(i) - 1? Not exactly. There's a known identity: The number of pairs (i,j) with 1 ≤ i, j ≤ n and gcd(i,j)=1 is 1 + 2 * ∑{i=1}^n φ(i) - something? Actually let's derive: The number of reduced fractions a/b with 1 ≤ a ≤ b ≤ n and gcd(a,b)=1 is ∑{b=1}^n φ(b). That's the number of coprime pairs with i ≤ j? Actually if we consider pairs (i,j) with 1 ≤ i ≤ j ≤ n and gcd(i,j)=1, that's exactly the number of fractions i/j in [0,1] in simplest form? For each denominator j, numerator i with 1 ≤ i ≤ j, gcd(i,j)=1 gives φ(j) (including i=j? When i=j, gcd(j,j)=j, which is 1 only when j=1. So for j>1, i=j is not coprime. So number of pairs with i≤j and gcd(i,j)=1 is 1 (for (1,1)) + ∑{j=2}^n φ(j). That's ∑{j=1}^n φ(j) because φ(1)=1. So the number of pairs with i ≤ j and gcd=1 is S_leq = ∑{j=1}^n φ(j). Then the total ordered pairs (i,j) with gcd=1 is 2*(S_leq) - 1 (since (1,1) counted once). So S_ordered = 2*∑{j=1}^n φ(j) - 1. Then Mmax = (S_ordered - 1)/2 = (2*∑ φ(j) - 2)/2 = ∑_{j=1}^n φ(j) - 1. Wait, check: For n=5, ∑ φ(j) for j=1..5: φ(1)=1, φ(2)=1, φ(3)=2, φ(4)=2, φ(5)=4 => sum=10. Then ∑ φ(j)-1 = 9. But Mmax we computed earlier is 9? Actually earlier for n=5 we said Mmax=9? Wait we computed Mmax for n=5 earlier: from the list we thought Mmax=9? Let's recalc: For n=5, we listed edges: (1,2),(1,3),(1,4),(1,5),(2,3),(2,5),(3,4),(3,5),(4,5). That's 9 edges. Yes Mmax=9. ∑ φ(j) -1 = 10-1=9. So that matches! For n=4: ∑ φ(1..4)=1+1+2+2=6, minus 1 =5, which matches Mmax=5. For n=3: ∑ φ=1+1+2=4, minus1=3, matches. For n=2: ∑ φ=1+1=2, minus1=1, matches. For n=6: ∑ φ(1..6)=1+1+2+2+4+2=12, minus1=11, matches Mmax=11. For n=1: ∑ φ=1, minus1=0, matches.
So indeed there's a simple formula: Mmax = (∑{i=1}^n φ(i)) - 1. That is much simpler! Derivation: The number of unordered coprime pairs (i,j) with 1 ≤ i < j ≤ n equals (∑{i=1}^n φ(i)) - 1. Why? Because number of ordered pairs (i,j) with 1 ≤ i,j ≤ n and gcd(i,j)=1 = 1 + 2 * (number of unordered pairs with i<j) = 1 + 2*Mmax. Also we have identity: ∑{i=1}^n φ(i) = number of fractions i/j with 1 ≤ i ≤ j ≤ n and gcd(i,j)=1 (including i=j=1). Actually that's number of pairs with i ≤ j and gcd=1. That count = 1 + Mmax? Wait check: For i ≤ j, pairs: (1,1) and all i<j with gcd=1. So that's 1 + Mmax. Also it equals ∑{j=1}^n φ(j) because for each j, the numbers i with 1 ≤ i ≤ j and gcd(i,j)=1 are φ(j) (including i=j only when j=1? For j>1, φ(j) counts numbers i with 1 ≤ i < j and gcd(i,j)=1, not including i=j because gcd(j,j)=j>1 for j>1. So indeed ∑_{j=1}^n φ(j) counts (1,1) as φ(1)=1, and for j>1 counts φ(j) numbers i with 1≤i<j. So it counts exactly all pairs (i,j) with i ≤ j and gcd(i,j)=1. So ∑ φ(j) = 1 + Mmax. Therefore Mmax = ∑ φ(j) - 1.
Great! This is simpler than mobius. We can compute φ for all i up to n using a sieve (linear sieve or classic phi computation). That's also O(n). And then sum them.
Thus we don't need mu at all. We can compute phi array using sieve:
Initialize phi = list(range(n+1))
for i in range(2, n+1):
if phi[i] == i: # i is prime
for j in range(i, n+1, i):
phi[j] -= phi[j] // i
That's O(n log log n) which is fine for n=1e5. Or we can use linear sieve to compute both phi and primes, but the simpler sieve is okay.
Alternatively, we can compute phi via linear sieve:
primes = []
phi = [0](n+1)
phi[1] = 1
is_comp = [False](n+1)
for i in range(2, n+1):
if not is_comp[i]:
primes.append(i)
phi[i] = i-1
for p in primes:
if ip > n: break
is_comp[ip] = True
if i % p == 0:
phi[ip] = phi[i] * p
break
else:
phi[ip] = phi[i] * (p-1)
But either works.
Given we already need to compute phi for Mmax, we can just compute phi and then Mmax = sum(phi) - 1.
But careful: sum of phi from 1 to n includes phi[1]=1, so Mmax = sum_phi - 1.
Thus we can avoid mu.
Now, we also need to compute gcd for extra edges; that's separate.
Thus modify algorithm: compute phi array up to n (if n>1). Then Mmax = sum(phi) - 1.
Note: For n=1, sum_phi = 1, Mmax = 0, but we handle separately.
Now, compute phi efficiently.
We'll use the linear sieve method to compute phi because it's O(n) and also we might want to compute primes for other purposes? Not needed. But linear sieve is straightforward and gives both primes and phi. However, the simpler O(n log log n) method with the classic phi initialization is also fine for n=1e5. The inner loop for each prime p runs for multiples, total O(n log log n). For n=1e5, that's fine.
I'll implement the classic phi sieve:
phi = list(range(n+1))
for i in range(2, n+1):
if phi[i] == i: # prime
for j in range(i, n+1, i):
phi[j] -= phi[j] // i
But note: This modifies phi in place. Then phi[1] remains 1. Works.
Complexity: For each prime i, inner loop runs n/i times. Sum_{p prime ≤ n} n/p ≈ n log log n. For n=1e5, that's about n * (log log n) ≈ 1e5 * ~2.0 = 2e5 operations, very fast.
Thus we can compute phi quickly.
Alternatively, we could also compute Mmax by using the formula Mmax = n*(n-1)//2 - sum_{d=2}^n (something) but not needed.
So final plan:
- if n == 1: handle.
- Compute phi[1..n] via sieve.
- total_phi = sum(phi)
- Mmax = total_phi - 1
- Check conditions.
- Output.
Now, about phi computation: We need to allocate list of size n+1. That's fine.
Now, test with earlier values: n=5: phi:1,1,2,2,4 sum=10 Mmax=9. OK.
Now, note: For n up to 1e5, total_phi can be up to ~3e9? Actually sum of phi up to n is known to be 3n^2/π^2 + O(n log n) ≈ 0.30396355 * n^2? Actually the sum of φ(k) for k=1..n is ~ 3n^2/π^2 ≈ 0.30396355 n^2. For n=1e5, sum_phi ≈ 0.304 * 1e10 = 3.04e9. So Mmax ≈ 3.04e9, which fits in Python int.
Now, for n=1, sum_phi=1, Mmax=0.
Now, we must also consider that m ≤ 1e5, so many values will be possible.
Now, I'll implement phi sieve.
Implementation details:
def compute_phi(n):
phi = list(range(n+1))
for i in range(2, n+1):
if phi[i] == i: # prime
for j in range(i, n+1, i):
phi[j] -= phi[j] // i
return phi
But note: This modifies phi in place, fine.
Now, after computing phi, we can compute total_phi = sum(phi). However, careful: phi[0] is 0, but we don't include.
Now, for n=1: we can skip phi computation.
Now, check for n=1e5: loops: for i from 2 to 1e5, check if phi[i]==i, which is true only for primes. There are about 9592 primes. For each prime i, inner loop runs about n/i iterations. Sum_{p prime} n/p ≈ n * (log log n + M) ≈ 1e5 * (log log 1e5 ≈ 2.0) = 200k. Actually sum_{p} 1/p for primes up to x is about log log x + B, so n * (log log n) ≈ 1e5 * ~2.0 = 200k. So total operations ~200k, each performing phi[j] -= phi[j] // i, which is simple arithmetic. That's very fast.
Thus phi sieve is efficient.
Now, we need to also use gcd for extra edges. We'll import math.gcd.
Now, implement.
Edge Cases:
-
For n=1, m=0: print "Possible". That's it.
-
For n=2, m=1: star edges: 1 2. Output.
Now, check n=2, m=2: Mmax=1, so impossible.
Now, also verify that the formula Mmax = sum_phi - 1 holds for n=0? Not needed.
Now, let's write the code.
Pseudo-code:
import sys, math
def main():
import sys
input = sys.stdin.readline
n,m = map(int, input().split())
if n == 1:
if m == 0:
print("Possible")
else:
print("Impossible")
return
# compute phi up to n
phi = list(range(n+1))
for i in range(2, n+1):
if phi[i] == i: # prime
for j in range(i, n+1, i):
phi[j] -= phi[j] // i
Mmax = sum(phi) - 1 # total phi includes phi[1]=1
if m < n-1 or m > Mmax:
print("Impossible")
return
print("Possible")
out = []
# star edges
for i in range(2, n+1):
out.append(f"1 {i}")
if len(out) == m:
# in case m == n-1, we have exactly m edges
sys.stdout.write("\n".join(out))
return
# need more edges
need = m - (n-1)
for i in range(2, n+1):
for j in range(i+1, n+1):
if math.gcd(i, j) == 1:
out.append(f"{i} {j}")
need -= 1
if need == 0:
break
if need == 0:
break
sys.stdout.write("\n".join(out))
if name == "main":
main()
Now, double-check: In star edges loop, we added edges and checked if len(out) == m, then we printed and returned. However, for m > n-1, len(out) after star edges will be n-1, which is < m, so we continue to extra edges. For m == n-1, we print and return.
But we must ensure that we didn't prematurely print before finishing building out if we print inside loop? Actually we check after appending each star edge if len(out) == m; if m == n-1, after appending the last star edge (i=n), len(out) becomes n-1 which equals m, so we print and return. That works. But we must also consider that if m < n-1, we would have earlier returned impossible, so no issue.
But careful: The star edges loop runs for i from 2 to n. When i reaches n, we append (1,n). At that point len(out) = n-1. If m == n-1, we print and return. Good.
Now, if m > n-1, after loop, len(out) = n-1, need = m - (n-1). We then go to extra edges. After collecting extra edges, out length becomes m. Then we write.
Now, we used sys.stdout.write at the end. But note: In the case m == n-1, we wrote inside the loop and returned. So we need to ensure we don't also write later. That's fine.
Now, small issue: In the star edges loop, we used out.append(f"1 {i}"). That's fine.
Now, for n=1e5, m=1e5, after star edges (n-1=99999) we have out length 99999. Then need = 1. We then go to extra edges. We'll generate (2,3) likely. Append that, out length becomes 100000, then we break and write. That works.
Now, test n=3,m=3: star edges: i=2 => out = ["1 2"]; len=1 !=3; i=3 => out = ["1 2","1 3"]; len=2 !=3; after loop len=2, need=1. Then extra: i=2,j=3 -> gcd=1, append "2 3", need=0, break, write. So out = ["1 2","1 3","2 3"]; prints three lines. That's correct.
Now, test n=4,m=5: star edges: i=2,3,4 -> out len=3, need=2. extra: i=2: j=3 add "2 3", need=1; j=4 skip; i=3: j=4 add "3 4", need=0, break. Out = ["1 2","1 3","1 4","2 3","3 4"]; prints. That's a valid connected graph (edges: 1-2,1-3,1-4,2-3,3-4). Is it connected? Yes. That's good.
Now, check n=6,m=11: star edges: 5 edges, need=6. extra: as earlier we will collect all 6 edges: (2,3),(2,5),(3,4),(3,5),(4,5),(5,6). That yields out length=11. That's fine.
Now, test n=6,m=10: need=5. extra: i=2: (2,3),(2,5) ->2; i=3: (3,4),(3,5) ->2 more total 4; i=4: (4,5) ->1 more total 5; break. So out = star edges + (2,3),(2,5),(3,4),(3,5),(4,5). That's 10 edges. Connected? Yes.
Now, check that graph is connected: Star ensures connectivity, so any extra edges don't break connectivity. So all good.
Now, complexity: phi computation O(n log log n) = ~2e5 operations. Good.
Now, about Python recursion? Not used.
Now, final step: Write final answer.
We should also consider the case where n=1 and m=0; we output "Possible". Should we output a newline? print will add newline. That's fine.
Now, check formatting: The problem examples show "Possible" then lines. We'll match.
Now, edge case: n=2, m=1, we output "Possible\n1 2". That's fine.
Now, confirm that we never generate edge (1,1) or any self-loop.
Now, verify that the graph is relatively prime: all edges satisfy gcd=1 because star edges have gcd(1,i)=1, extra edges we check gcd.
Now, ensure that we don't accidentally add an edge that is not allowed: we check gcd before adding extra.
Now, we must also ensure that we don't add an edge that is already present. Since extra edges only between i>=2, they are not in star; and among extra edges, we iterate with i<j, each pair added at most once. So no duplicates.
Now, all good.
Now, I will produce final code.
But I realize one more nuance: In the star edges loop, we are checking if len(out) == m after each addition, and if so we print and return. But if m is exactly n-1, after the last addition we print. However, the printing is done via sys.stdout.write("\n".join(out)). That will output the lines without a trailing newline? Actually join returns a string with lines separated by newline, no trailing newline. That's okay; some judges accept. Usually it's fine.
But some judges expect a newline at end of file; but even if we don't have trailing newline, it's usually accepted. To be safe, we could add a newline after each line? Actually join puts newline between lines, not after last. That's typical for many problems. Alternatively, we can print each line individually using print, but that may be slower. It's fine.
But we have two places where we write: one inside the star loop for early return, and one at the end. For early return, we write and then return. For end, we write. We should ensure that we don't double-write. That's fine.
Now, test with n=1,m=0: we print "Possible" and return. But we printed using print("Possible") which adds newline. That's okay.
Now, test with n=2,m=1: star edges loop: i=2: out=["1 2"]; len=1 == m=1, so we call sys.stdout.write("\n".join(out)). But we haven't printed "Possible" yet? Actually we printed "Possible" earlier with print("Possible"). Then we go into star edges loop and after appending we write the edges. But we wrote "Possible" using print, which adds newline. Then we write the edges string. That will output:
Possible
1 2
But there is no newline between "Possible" and the edges? Actually print("Possible") will output "Possible\n". Then we write "1 2" (without newline at start). So the output will be:
Possible
1 2
That's correct. However, after writing "1 2", there is no newline at end? The join result is just "1 2". The write does not add a newline. But typically output files can end without newline; it's accepted. Many problems accept. But to be consistent with typical output, we might want to ensure a newline at the end. However, after "1 2", there may be no newline, but judges usually ignore trailing whitespace. I think it's okay. But we can modify to add a newline after the last line by writing "\n".join(out) + ("\n" if out else "")? But if out is non-empty, we may want trailing newline? Not required. Let's check sample: In sample output, they have lines after "Possible", each edge on its own line. There is no extra blank line. The file ends after the last edge line, likely with a newline. But many judges ignore. I'll not worry.
But to be safe, we can print edges using a loop with print, but that might be slower. But 1e5 prints is okay. I'll use print for each edge to avoid join complexity. Actually that's simpler: after printing "Possible", we can just iterate and print each edge. That will automatically add newlines. And we don't need to store out list. That reduces memory and complexity.
Let's adopt that:
Print "Possible". Then:
star edges
for i in range(2, n+1):
print(1, i)
m_printed = n-1
if m == n-1:
return
extra edges
need = m - (n-1)
for i in range(2, n+1):
for j in range(i+1, n+1):
if math.gcd(i,j) == 1:
print(i, j)
need -= 1
if need == 0:
return
But careful: We have printed star edges using print(1,i). That will output them. But we also need to stop printing if we reach m exactly after star edges. So after star edges, we can check: if m == n-1, we just return (since we already printed all edges). Otherwise, we need to print extra edges. That's fine.
But we must ensure that we don't print star edges beyond m? Since m >= n-1, it's safe.
Now, for n=1, we print "Possible" and no edges.
Thus we can avoid storing out list.
But there's a subtlety: The print function in Python by default adds a newline and also flushes? But that's fine.
Now, we must be careful about speed: printing 100k lines individually with print might be slower than join, but still acceptable (100k prints is okay). However, in Python, printing many lines can be slower if using standard output buffer. But it's generally fine for 100k.
I can also use sys.stdout.write with manual newline for each, but either is okay.
I'll use print for simplicity.
But we must also consider that we are using input = sys.stdin.readline, but print is built-in. That's fine.
Now, adjust code:
def solve():
import sys, math
input = sys.stdin.readline
n,m = map(int, input().split())
if n == 1:
if m == 0:
print("Possible")
else:
print("Impossible")
return
# compute phi up to n
phi = list(range(n+1))
for i in range(2, n+1):
if phi[i] == i: # prime
for j in range(i, n+1, i):
phi[j] -= phi[j] // i
Mmax = sum(phi) - 1
if m < n-1 or m > Mmax:
print("Impossible")
return
print("Possible")
# star edges
for i in range(2, n+1):
print(1, i)
# if m == n-1, we are done
if m == n-1:
return
need = m - (n-1)
for i in range(2, n+1):
for j in range(i+1, n+1):
if math.gcd(i, j) == 1:
print(i, j)
need -= 1
if need == 0:
return
But note: In the star edges loop, we printed all n-1 edges. If m > n-1, we still printed all star edges; then we print extra edges. That's correct.
But what if m == n-1, we printed star edges and then we return. That's fine.
But we must ensure that we don't print extra edges if need becomes zero early, we break out of loops and return.
Now, I realize that we are printing star edges unconditionally even when m > n-1, which is fine.
Now, test n=3,m=2: star edges printed: (1,2) and (1,3). That's 2 edges, m=2, so after star edges, m == n-1? n-1=2, so condition m == n-1 true, we return. So no extra edges. That's correct.
Now, test n=3,m=3: star edges printed (1,2),(1,3). Then m == n-1? n-1=2, but m=3, so false. So we go to extra edges. need=1. Then we print (2,3) and return. So output: "Possible", "1 2", "1 3", "2 3". That's correct.
Now, test n=6,m=11: star edges printed 5 edges. m != n-1, need=6. Then we iterate and print extra edges. We'll print all 6 edges. Good.
Now, we must also consider that printing extra edges might print many lines; but that's okay.
Now, check for n=1,m=0: we print "Possible" only. Good.
Now, we should also test n=1,m=1: prints "Impossible".
Now, test n=2,m=1: star edges printed: (1,2) -> that's 1 edge, m == n-1 true, return. Output: Possible\n1 2. Good.
Now, test n=2,m=2: impossible.
Now, test n=4,m=5: star edges printed 3 edges; need=2; extra edges printed (2,3) and (3,4) as per our scanning order? Actually scanning order: i=2: j=3 -> print (2,3) need=1; j=4 skip; i=3: j=4 -> print (3,4) need=0. So output: star edges then 2 3, 3 4. That's correct.
Now, ensure that all edges are distinct: star edges: (1,2),(1,3),(1,4). Extra: (2,3),(3,4). No duplicates.
Now, confirm connectivity: Yes.
Now, verify Mmax computation for n=4: phi:1,1,2,2 sum=6, Mmax=5. Good.
Now, all good.
Now, complexity: phi sieve is O(n log log n). extra edges scanning up to O(K / density) gcd checks. For worst-case when n is small and K is near Mmax, scanning may go through many pairs, but still O(n^2) in worst-case? For n=1000, n^2/2 = 500k, still fine. For n=2000, 2 million, still okay. For n=3000, 4.5 million, maybe borderline but still okay? But m ≤ 1e5, so K ≤ 1e5. For n=3000, total pairs among >1 is about (29992998)/2 ≈ 4.5 million. If K is near Mmax - (n-1), which for n=3000, Mmax ≈ 0.6079 * (30002999)/2 ≈ 0.6079 * 4,498,500 ≈ 2,735,000. So edges among >1 = Mmax - (n-1) ≈ 2,735,000 - 2999 ≈ 2,732,000. That's > 1e5. So K could be up to 1e5. To collect 1e5 edges, we need to scan about 166k pairs. That's far less than 4.5 million. So we won't scan all pairs. Only when n is so small that total pairs is less than ~200k might we scan all. For n=500, total pairs among >1 = ~124k; if K=74k, we may scan about 124k. That's fine. For n=300, total pairs ~ (299*298)/2= ~44,551; if K is near that, we scan all. 44k is fine. So scanning never exceeds a few hundred thousand checks.
Thus performance fine.
Now, let's consider the case n=1000, K=100k. As estimated, we may need to scan up to i around 200, which yields about 180k checks. That's fine.
Now, confirm that phi sieve is correct for n=1? We handle separately.
Now, final code.
We must import math.
Now, one more thing: The sum of phi could be large; but Python int fine.
Now, write final answer.
But I think we can even simplify Mmax check: Since m ≤ 1e5, we could compute Mmax by direct enumeration of coprime pairs using a sieve that counts number of coprime pairs? But the phi sum is simple.
Now, implement phi sieve:
def phi_up_to(n):
phi = list(range(n+1))
for i in range(2, n+1):
if phi[i] == i:
for j in range(i, n+1, i):
phi[j] -= phi[j] // i
return phi
Now, in code.
Potential optimization: We could break early in phi computation if we only need up to n, but we need all.
Now, edge case n=100000, we compute phi for all numbers. The inner loops will run for each prime. That's fine.
Now, let's test with n=100000, m=100000: phi computation takes maybe 0.05 seconds? Actually Python loops might be a bit slower; but 200k inner loop iterations? Wait, sum of n/p for primes up to n is n * sum_{p≤n} 1/p ≈ n * (log log n + B) ≈ 100000 * (log log 100000 ≈ 2.0) = 200k. So total inner loop iterations ~200k, each doing phi[j] -= phi[j] // i. That's very fast. The outer loop runs 100k times, but the if phi[i]==i check is constant time. So total operations ~300k, fast.
Thus overall fast.
Now, we need to be careful: In phi initialization, phi = list(range(n+1)) is O(n). Good.
Now, final answer ready.
But there is one more nuance: The sum of phi may be large (up to ~3e9), but Python int fine.
Now, let's produce final code.
But I recall a known property: sum_{i=1}^n φ(i) = 1 + number of pairs (i,j) with 1 ≤ i < j ≤ n and gcd(i,j)=1. Actually it's 1 + Mmax, as derived. So Mmax = sum_phi - 1.
Now, double-check for n=1: sum_phi = 1, Mmax=0. Good.
Now, final code.
We'll include fast I/O: sys.stdin.readline.
Now, I think it's correct.
But wait, there is a potential oversight: The condition for connectivity also requires that the graph be connected. Star ensures connectivity. However, what if n=1? Graph is trivially connected. So fine.
Thus answer.
Now, I will craft final response with explanation and code.
But the user asked: "Let's call an undirected graph G = (V, E) relatively prime if and only if for each edge (v, u) ∈ E GCD(v, u) = 1 (the greatest common divisor of v and u is 1). If there is no edge between some pair of vertices v and u then the value of GCD(v, u) doesn't matter. The vertices are numbered from 1 to |V|.
Construct a relatively prime graph with n vertices and m edges such that it is connected and it contains neither self-loops nor multiple edges.
If there exists no valid graph with the given number of vertices and edges then output "Impossible".
If there are multiple answers then print any of them."
We have solved.
Now, I'll provide final answer with code and brief explanation. ```python
import sys
import math
def solve() -> None:
input = sys.stdin.readline
n, m = map(int, input().split())
# Special case n = 1
if n == 1:
print("Possible" if m == 0 else "Impossible")
return
# ---------- 1. Compute φ(1..n) ----------
phi = list(range(n + 1)) # φ(i) initially i
for i in range(2, n + 1):
if phi[i] == i: # i is prime
for j in range(i, n + 1, i):
phi[j] -= phi[j] // i
# ---------- 2. Maximum possible edges ----------
max_edges = sum(phi) - 1 # = number of coprime unordered pairs
# ---------- 3. Feasibility check ----------
if m < n - 1 or m > max_edges:
print("Impossible")
return
# ---------- 4. Construction ----------
print("Possible")
# 4a. Star centered at 1 (edges (1, i) for i = 2..n)
for i in range(2, n + 1):
print(1, i)
if m == n - 1: # exactly the star
return
# 4b. Additional edges among vertices ≥ 2
need = m - (n - 1)
for i in range(2, n + 1):
for j in range(i + 1, n + 1):
if math.gcd(i, j) == 1:
print(i, j)
need -= 1
if need == 0:
return
if name == "main":
solve()