Editorial
Prime Divisor Spell
1. Problem Understanding
We are given a number , and our task is to compute the sum of all its unique prime divisors. If the prime factorization of is given by
we need to find the sum
An additional edge case is when , which has no prime divisors; in that case, the output should be . We need to handle up to test cases while each is bounded by .
2. Solution Analysis
A straightforward approach is to factorize by checking for prime factors:
- For : Output directly.
- Check for divisibility by 2: Because 2 is the only even prime, if is divisible by 2, add 2 to the sum and repeatedly divide by 2 until it is no longer even.
- Check for odd factors: Iterate over odd integers from 3 to . For each odd number , if divides , then it is a prime divisor. Add to the sum and repeatedly divide by until it no longer divides .
- Remaining number: After processing factors up to , if is greater than 1, then the remaining 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 using a sieve technique. Then for each test case, use the SPF table to quickly factorize and sum the unique prime divisors by repeatedly dividing by its SPF.
3. Time and Space Complexity Analysis
-
Trial Division Approach:
- Time Complexity: In the worst-case scenario (when is a prime or has large prime factors), checking divisibility up to takes up to . As , this is roughly per test case. Given that there can be up to test cases, the overall complexity comes to , which is acceptable in many competitive programming environments in languages like C++ with optimized code.
- Space Complexity: extra space per test case.
-
Precomputation with SPF Approach:
- Time Complexity:
- The sieve for computing SPF for all numbers up to runs in .
- Factorizing each using the SPF table typically takes time per test case.
- Space Complexity: The SPF table requires space.
- Time Complexity: