Prime Factorization
We prepare the list of primes to cover up to sqrt(10,000). You can either precompute them, or just use a static array.\n\n> This is an important optimization. W
We prepare the list of primes to cover up to `sqrt(10,000)`. You can either precompute them, or just use a static array.\n\n> This is an important optimization. We check up to 65 primes for `n`, and the complexity is \u03C0(sqrt(n)).\n> If, after we try all primes, `n > 1`, then `n` is a large prime. E.g. for 99951 example, the factorization looks like (33317 is a large prime):\n> ```\n> 99951: 3 33317\n> 33320: 2 2 2 5 7 7 17\n> 42: 2 3 7 1\n> 12: 2 2 3 1\n> 7: 7\n> ```\n\nWe try to each prime and `sum` the divisors, tracking the division result in `res`. If the `sum` equal `n`, then we take on `n`. If the `sum` is zero, `n` is the large prime, and we take on `n`.\n\nOthersise, we recurse on `sum`. Note that if `res > 1`, this is a large prime and we need to recurse on `sum + res`.\n\n**C++**\n```cpp\nint p[65] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97,\n    101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199,\n    211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313};\nint smallestValue(int n) {\n    int sum = 0, res = n;\n    for (int i = 0; i < 65 && res >= p[i]; ++i)\n        while (res % p[i] == 0) {\n            sum += p[i];\n            res /= p[i];\n        }\n    return (sum == 0 || sum == n) ? n : smallestValue(sum + (res == 1 ? 0 : res));\n}\n```
[]