<p>You are given an integer array <code>nums</code>, and you can perform the following operation <strong>any</strong> number of times on <code>nums</code>:</p>

<ul>
	<li>Swap the positions of two elements <code>nums[i]</code> and <code>nums[j]</code> if <code>gcd(nums[i], nums[j]) &gt; 1</code> where <code>gcd(nums[i], nums[j])</code> is the <strong>greatest common divisor</strong> of <code>nums[i]</code> and <code>nums[j]</code>.</li>
</ul>

<p>Return <code>true</code> <em>if it is possible to sort </em><code>nums</code><em> in <strong>non-decreasing</strong> order using the above swap method, or </em><code>false</code><em> otherwise.</em></p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> nums = [7,21,3]
<strong>Output:</strong> true
<strong>Explanation:</strong> We can sort [7,21,3] by performing the following operations:
- Swap 7 and 21 because gcd(7,21) = 7. nums = [<u><strong>21</strong></u>,<u><strong>7</strong></u>,3]
- Swap 21 and 3 because gcd(21,3) = 3. nums = [<u><strong>3</strong></u>,7,<u><strong>21</strong></u>]
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> nums = [5,2,6,2]
<strong>Output:</strong> false
<strong>Explanation:</strong> It is impossible to sort the array because 5 cannot be swapped with any other element.
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> nums = [10,5,9,3,15]
<strong>Output:</strong> true
We can sort [10,5,9,3,15] by performing the following operations:
- Swap 10 and 15 because gcd(10,15) = 5. nums = [<u><strong>15</strong></u>,5,9,3,<u><strong>10</strong></u>]
- Swap 15 and 3 because gcd(15,3) = 3. nums = [<u><strong>3</strong></u>,5,9,<u><strong>15</strong></u>,10]
- Swap 10 and 15 because gcd(10,15) = 5. nums = [3,5,9,<u><strong>10</strong></u>,<u><strong>15</strong></u>]
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 3 * 10<sup>4</sup></code></li>
	<li><code>2 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li>
</ul>

from typing import Set


class Solution:

  def eratosthenes_sieve(self, n: int) -> List[int]:
    # finds all prime numbers less then n. O(n log log n)
    prime, result, sqrt_n = [True] * n, [2], (int(n ** .5) + 1) | 1  # ensure it's odd
    for p in range(3, sqrt_n, 2):
      if prime[p]:
        result.append(p)
        prime[p * p::2 * p] = [False] * ((n - p * p - 1) // (2 * p) + 1)

    return result + [p for p in range(sqrt_n, n, 2) if prime[p]]

  def factorize(self, nums: List[int]) -> List[Set[int]]:
    primes = self.eratosthenes_sieve(int(max(nums) ** 0.5) + 3)

    res = []
    for n in nums:
      factors, i = set(), 0
      while i < len(primes) and primes[i] * primes[i] <= n:
        while n % primes[i] == 0:
          n //= primes[i]
          factors.add(primes[i])
        i += 1

      if n > 1:
        factors.add(n)

      res.append(factors)

    return res

  def get_components(self, g: Dict[int, Set[int]]) -> List[Set[int]]:
    all_nodes, components = set(g.keys()), []

    while all_nodes:
      for node in all_nodes:
        break

      frontier, seen = [node], {node}
      while frontier:
        new_frontier = []
        for node in frontier:
          for node_nxt in g[node]:
            if node_nxt not in seen:
              seen.add(node_nxt)
              new_frontier.append(node_nxt)
          frontier = new_frontier

      for node in seen:
        all_nodes.remove(node)
      components.append(seen)

    return components

  def gcdSort(self, nums: List[int]) -> bool:
    factors = self.factorize(nums)

    g = defaultdict(list)
    for i in range(len(nums)):
      for f in factors[i]:
        g[i].append(-f)
        g[-f].append(i)

    for pos in self.get_components(g):
      real_pos = sorted([v for v in pos if v >= 0])
      vals = sorted([nums[p] for p in real_pos])
      for i in range(len(real_pos)):
        nums[real_pos[i]] = vals[i]

    for i in range(1, len(nums)):
      if nums[i - 1] > nums[i]:
        return False

    return True
1377