Find connected components using the distinct prime factors of each integer.
Every pair of vertices divisible by the same prime is connected by an edge. Thus, it is enough to remember one representative vertex for each prime and merge every subsequent vertex divisible by with that representative.
Precompute the smallest prime factor of every integer using a sieve. Factorize each into distinct prime factors. For every such factor , merge vertex with the recorded representative of using a disjoint-set union structure. The number has no prime factors and is not merged with any other vertex.
Every edge has a prime dividing both and , so its endpoints are merged. Conversely, each merge is between vertices sharing a prime factor, so these vertices are adjacent in the original graph. Therefore the resulting disjoint sets are exactly the connected components of the graph.
Answer each query by checking whether its endpoints have the same DSU representative. This also handles .
Let . The time complexity is , and the space complexity is .
Solution written by GPT6