Product of proper divisors of a number for Q queries

Updated

Given a number N find the product of proper divisors of a number mod 1000000007 for Q queries.

Examples :

Input : Q = 4, arr[] = { 4, 6, 8, 16 };
Output : 2 6 8 64
Explanation :
4 -> 1, 2 = 1 * 2 = 2
6 -> 1, 2, 3 = 1 * 2 * 3 = 6
8 -> 1, 2, 4 = 1 * 2 * 4 = 8
16 -> 1, 2, 4, 8 = 1 * 2 * 4 * 8 = 64

Input : arr[] = { 3, 6, 9, 12 }
Output : 1 6 3 144

Approach :

The idea is to precompute and store each element with its product of proper divisors in an array using modification of Sieve of Eratosthenes.

Implementation :

// C++ implementation of the approach
#include <bits/stdc++.h>
#define ll long long int
#define mod 1000000007
using namespace std;
vector<ll> ans(100002,1);

//function to precompute the product
// of proper divisors of a number at 
//it's corresponding index
void preCompute(){
    
    for(int i = 2; i <= 100000 / 2; i++)
    {
        for(int j = 2 * i; j <= 100000; j += i)
        {
            ans[j] = (ans[j] * i) % mod;
        }
    }
}

// Driver code
int main()
{
    preCompute();
    const int queries = 5;
    int a[queries] = { 4, 6, 8, 16, 36 };

    for(int i = 0; i < queries; i++){
        cout<<ans[a[i]]<<",";
    }

    return 0;
}

Output :

2,6,8,64,279936,

Time Complexity : O(nlogn)

Comment
Mithlesh Upadhyay Published 30 Nov 2026 · 1 min read

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.

Related tutorials