c++algorithmoptimizationintegerprimes

From 1 to n, count how many integers there are with the sum of divisors being a prime number?


Let there be integer n.

Count how many numbers there are from 1 to n that has the sum of divisors being a prime number.

Example:

Input: 10

Output: 3

Explanation: There are 3 numbers with the sum of divisors being a prime: 2,4,9.

2: 1,2: Sum = 1+2 = 3.

4: 1,2,4: Sum = 1+2+4 = 7

9: 1,3,9: Sum = 1+3+9 = 13

I took this problem from a Vietnamese contest. At first I tried to solve it using a function to calculate divisors and the Sieve of Eratosthenes, but it can only run in O(n log n), which isn't plausible for n = 10^9. Does anyone have any idea what's the best solution to count how many numbers there are with the sum of divisors being a prime number?

Edit: It's from a piece of paper, there's no source of this unfortunately. If there were, I would've done so without asking.


Solution

  • When you do not know whether the sum is prime or not, then you need to actually compute it.

    However, there are general ideas that you can apply, such as:

    Such ideas can be applied to drastically reduce the number of sums whose prime-ness you are to check. If such quickening rules fail to determine for a sum whether it's prime, then you will need to do the costly prime calculation, but it would be a much rarer necessity, than without these pre-filters.