Algorithm
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.
The only line contains two integers n and m (1≤n,m≤105) — the number of vertices and the number of edges.
If there exists no valid graph with the given number of vertices and edges then output "Impossible".
Otherwise print the answer in the following format:
The first line should contain the word "Possible".
The i-th of the next m lines should contain the i-th edge (vi,ui) of the resulting graph (1≤vi,ui≤n,vi≠ui). For each pair (v,u) there can be no more pairs (v,u) or (u,v). The vertices are numbered from 1 to n.
If there are multiple answers then print any of them.
5 6
Possible
2 5
3 2
5 1
3 4
4 1
5 4
6 12
Impossible
Here is the representation of the graph from the first example:
Code Examples
#1 Code Example with C++ Programming
Code -
C++ Programming
#include <bits/stdc++.h>
using namespace std;
int const N = 1e5 + 1;
int n, m, v;
pair<int, int> phi[N];
set<pair<int, int> > e;
void print(int x, int &cnt) {
for(int i = 1; cnt > 0 && i <= n; ++i)
if(i != x && __gcd(x, i) == 1) {
if(e.count({min(x, i), max(x, i)}) == 1)
continue;
e.insert({min(x, i), max(x, i)});
printf("%d %d\n", x, i), --cnt;
}
}
int main() {
scanf("%d %d", &n, &m);
for(int i = 1; i <= n; ++i)
phi[i].first = phi[i].second = i;
for(int p = 2; p <= n; ++p)
if(phi[p].first == p) {
phi[p].first = p - 1;
for(int i = 2 * p; i <= n; i += p)
phi[i].first = (phi[i].first / p) * (p - 1);
}
long long to = 0;
for(int i = 1; i <= n; ++i)
to += phi[i].first;
if(to - 1 < m || m < n - 1) {
puts("Impossible");
return 0;
}
puts("Possible");
for(int i = n; i > 0; --i)
if(phi[i].first == phi[i].second - 1) {
v = phi[i].second;
break;
}
for(int i = 1; i <= n; ++i) {
if(i == v)
continue;
printf("%d %d\n", v, i);
e.insert({min(v, i), max(v, i)});
}
m -= (n - 1);
sort(phi + 1, phi + n + 1);
reverse(phi + 1, phi + n + 1);
for(int i = 1; m > 0 && i <= n; ++i)
print(phi[i].second, m);
return 0;
}
Copy The Code &
Try With Live Editor
Input
Output
2 5
3 2
5 1
3 4
4 1
5 4
Demonstration
Codeforces Solution-D. Relatively Prime Graph-Solution in C, C++, Java, Python,Relatively Prime Graph,Codeforces Solution