Kilonova - Sum of divisors

Authors: Mihnea Brebenel, Harshit Lohar

Table of Contents

ExplanationImplementation

Explanation

For an integer AA, the sum of all divisors of the AA can be efficiently computed using the divisor function.

The formula states that if d1p1d2p2...dkpkd_1^{p_1} \cdot d_2^{p_2} \cdot ... \cdot d_k^{p_k} is the prime factorization of AA, then the divisors' sum is S=i=1kdipi+11di1S = \prod_{i=1}^{k}\frac{d_i^{p_i+1} - 1}{d_i -1}.

For this problem we need to compute sum of divisors of ABA^B. If the prime factorization of AA is d1p1d2p2...dkpkd_1^{p_1} \cdot d_2^{p_2} \cdot ... \cdot d_k^{p_k} then the prime factorization of ABA^B will be d1Bp1d2Bp2...dkBpkd_1^{B\cdot p_1} \cdot d_2^{B\cdot p_2} \cdot ... \cdot d_k^{B\cdot p_k} and we can compute the sum of divisors using the above formula, S=i=1kdiBpi+11di1S = \prod_{i=1}^{k}\frac{d_i^{B\cdot p_i+1} - 1}{d_i -1}.

To compute the above sum we will have to find multiplicative inverse of (di1)(d_i-1) modulo 109+710^9+7, for cases when (di1)(d_i-1) is not relatively prime with 109+710^9+7 we can notice that we wish to find the value of the following series modulo 109+710^9+7,

for each 1ik1 \le i \le k, diBpi+11di1=1+di+di2+...+diBpi\frac{d_i^{B\cdot p_i+1} - 1}{d_i -1} = 1+d_i + d_i^2 + ... + d_i^{B\cdot p_i}.

which is equal to (Bpi+1)%(109+7)(B\cdot p_i+1)\%(10^9+7), whenever, di%(109+7)=0d_i\%(10^9+7)=0

We do need to compute the prime factors of AA, but thankfully this can be done in O(A)\mathcal{O}(\sqrt{A}) time.

Since, BB can be as large as 101810^{18}, to avoid overflows we can use Euler's totient function and binary exponentiation to compute the powers modulo 109+710^9+7.

Implementation

Time Complexity: O(AlogB)\mathcal{O}(\sqrt{A}\cdot logB)

C++

#include <fstream>
using namespace std;
#define ll long long
const int MOD = 1e9 + 7;
Code Snippet: Modular Inverse and Binary Exponentiation functions (Click to expand)

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!