Editorial

Prime Divisor Spell

1. Problem Understanding

We are given a number nn, and our task is to compute the sum of all its unique prime divisors. If the prime factorization of nn is given by
n=p1e1×p2e2××pkek,n = p_1^{e_1} \times p_2^{e_2} \times \cdots \times p_k^{e_k},
we need to find the sum
S=p1+p2++pk.S = p_1 + p_2 + \cdots + p_k.
An additional edge case is when n=1n = 1, which has no prime divisors; in that case, the output should be 1-1. We need to handle up to TT test cases while each nn is bounded by 1n1061 \leq n \leq 10^6.

2. Solution Analysis

A straightforward approach is to factorize nn by checking for prime factors:

  • For n=1n=1: Output 1-1 directly.
  • Check for divisibility by 2: Because 2 is the only even prime, if nn is divisible by 2, add 2 to the sum and repeatedly divide nn by 2 until it is no longer even.
  • Check for odd factors: Iterate over odd integers from 3 to n\sqrt{n}. For each odd number ii, if ii divides nn, then it is a prime divisor. Add ii to the sum and repeatedly divide nn by ii until it no longer divides nn.
  • Remaining number: After processing factors up to n\sqrt{n}, if nn is greater than 1, then the remaining nn must be a prime divisor. Add it to the sum.

An alternative approach, to improve efficiency for many test cases, is to precompute the smallest prime factor (SPF) for every number up to 10610^6 using a sieve technique. Then for each test case, use the SPF table to quickly factorize nn and sum the unique prime divisors by repeatedly dividing nn by its SPF.

3. Time and Space Complexity Analysis

  • Trial Division Approach:

    • Time Complexity: In the worst-case scenario (when nn is a prime or has large prime factors), checking divisibility up to n\sqrt{n} takes up to O(n)O(\sqrt{n}). As n106n \leq 10^6, this is roughly O(103)O(10^3) per test case. Given that there can be up to 10510^5 test cases, the overall complexity comes to O(105×103)O(10^5 \times 10^3), which is acceptable in many competitive programming environments in languages like C++ with optimized code.
    • Space Complexity: O(1)O(1) extra space per test case.
  • Precomputation with SPF Approach:

    • Time Complexity:
      • The sieve for computing SPF for all numbers up to 10610^6 runs in O(nloglogn)O(n \log \log n).
      • Factorizing each nn using the SPF table typically takes O(logn)O(\log n) time per test case.
    • Space Complexity: The SPF table requires O(106)O(10^6) space.

Author's Solution

GNU C++23