Sum of factors of the product of a given array
Last Updated :
29 Dec, 2022
Given an array arr[] consisting of N positive integers, the task is to find the sum of factors of product of all array elements. Since the output can be very large, print it modulo 109 + 7.
Examples:
Input: arr[] = { 1, 2, 3, 4, 5 }
Output: 360
Explanation:
The product of all array elements = 1 * 2 * 3 * 4 * 5 = 120
All the factors of 120 are { 1, 2, 3, 4, 5, 6, 8, 10, 12, 15, 20, 24, 30, 40, 60, 120 }
Therefore, the sum of factors is 360.
Input: arr[] = { 1, 2 }
Output: 3
Explanation:
The product of all array elements = 1 * 2 = 2
All the factors of 2 are { 1, 2 }
Therefore, the sum of factors is 3.
Naive Approach: The simplest approach to solve this problem is to traverse the array and calculate the product of all elements of the array and calculate the sum of all the factors of the obtained product. But the problem with this approach is that, if the array elements are large, then the product may go out of bounds of the integer storing capacity and it will lead to wrong output.
Time Complexity: O(max(N, sqrt(product of array elements)))
Auxiliary Space: O(N)
Efficient approach: The above approach can be optimized based on the following observations:
If the product of array elements(P) = 2^a \times 3^b \times 5^c \times 7^d \times ... \times p^k
Then, the sum of factors of P = \frac{2^{a+1}-1}{2-1} \times \frac{3^{b+1}-1}{3-1} \times \frac{5^{c+1}-1}{5-1}\times ... \times \frac{p^{k+1}-1}{p-1}
Follow the steps below to solve the problem:
- Initialize an integer, say ans, to store the sum of all the factors of the product of the array.
- Initialize an array of integer, say count[], where count[i] stores the frequency of prime factors i, in product of the array elements.
- Traverse the array count[], and check if count[i] is greater than zero or not. If found to be true, then multiply ans by (i(count[i] + 1)) - 1 and multiplicative inverse of (i -1)
- Finally, print the result obtained in ans
Below is the implementation of the above approach:
C
// C program to implement
// the above approach
#include <stdio.h>
#define size 1000100
#define inverse(a) power(a, mod - 2)
typedef long long int ll;
const ll mod = ((ll)(1e9 + 7));
// Stores minimum prime
// factorization of a number
int spf[size] = { 0 };
// Function to add two numbers
static inline ll add(ll a, ll b)
{
return (a % mod + b % mod) % mod;
}
// Function to subtract two numbers
static inline ll sub(ll a, ll b)
{
return add(mod, a - b) % mod;
}
// Function to multiply two numbers
static inline ll mul(ll a, ll b)
{
return (a % mod * b % mod) % mod;
}
// Function to calculate
// x to the power y
ll power(ll x, ll y)
{
// Stores x ^ y
ll res = 1;
for (res = 1; y > 0;
x = (x * x) % mod, y >>= 1) {
// If y is odd
if (y & 1) {
// Update result
res = (res * x) % mod;
}
}
return res;
}
// Function to find the smallest prime factor
// of numbers in the range [1, 1000100]
void sieve()
{
// Update the smallest prime factor of
// all the numbers which is divisible by 2
for (int i = 2; i < size; i += 2) {
// Update spf[i]
spf[i] = 2;
}
for (int i = 3; i < size; i += 2)
spf[i] = i;
// Calculate the smallest prime factor
// of all the numbers in the range [3, 1000100]
for (int i = 3; i * i < size; i += 2)
if (spf[i] == i)
for (int j = i * i; j < size; j += i)
spf[j] = i;
}
// Function to find the sum of factors of
// product of all array elements
long long int sumof_factors(int a[], int n)
{
// Stores the sum of factors of
// product of all array elements
ll ans = 1;
// count[i]: Stores frequency of
// prime factor i in product of
// all the array elements
ll count[size] = { 0 };
// Traverse the array
for (int i = 0; i < n; i++) {
// Calculate the prime factor
// of a[i]
while (a[i] > 1) {
// Update frequency of
// prime factor spf[a[i]]
count[spf[a[i]]]++;
// Update a[i]
a[i] /= spf[a[i]];
}
}
// Traverse the array, count[]
for (ll i = 0; i < size; i++)
// If frequency of prime factor i in
// product of array elements
// greater than 0
if (count[i] > 0) {
// Calculate (i^(count[i]+1))-1 and
// multiplicative inverse of (i -1)
ll num1 = sub(power(i, count[i] + 1), 1);
ll num2 = inverse(i - 1);
ans = mul(ans, mul(num1, num2));
}
return ans;
}
// Driver Code
int main()
{
sieve();
int arr[] = { 1, 3, 2, 5, 4 };
int N = sizeof(arr) / sizeof(arr[0]);
ll res = sumof_factors(arr, N);
printf("%lld\n", res);
return 0;
}
C++
// C++ program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
#define size 1000100
#define inverse(a) power(a, mod - 2)
typedef long long int ll;
const ll mod = ((ll)(1e9 + 7));
// Stores minimum prime
// factorization of a number
int spf[size] = { 0 };
// Function to add two numbers
static inline ll add(ll a, ll b)
{
return (a % mod + b % mod) % mod;
}
// Function to subtract two numbers
static inline ll sub(ll a, ll b)
{
return add(mod, a - b) % mod;
}
// Function to multiply two numbers
static inline ll mul(ll a, ll b)
{
return (a % mod * b % mod) % mod;
}
// Function to calculate
// x to the power y
ll power(ll x, ll y)
{
// Stores x ^ y
ll res = 1;
for (res = 1; y > 0;
x = (x * x) % mod, y >>= 1) {
// If y is odd
if (y & 1) {
// Update result
res = (res * x) % mod;
}
}
return res;
}
// Function to find the smallest prime factor
// of numbers in the range [1, 1000100]
void sieve()
{
// Update the smallest prime factor of
// all the numbers which is divisible by 2
for (int i = 2; i < size; i += 2) {
// Update spf[i]
spf[i] = 2;
}
for (int i = 3; i < size; i += 2)
spf[i] = i;
// Calculate the smallest prime factor
// of all the numbers in the range [3, 1000100]
for (int i = 3; i * i < size; i += 2)
if (spf[i] == i)
for (int j = i * i; j < size; j += i)
spf[j] = i;
}
// Function to calculate sum of factors
// of product of the given array
long long int sumof_factors(int a[], int n)
{
// Stores the sum of factors of
// product of all array elements
ll ans = 1;
// count[i]: Stores frequency of
// prime factor i in product of
// all the array elements
ll count[size] = { 0 };
// Traverse the array
for (int i = 0; i < n; i++) {
// Calculate the prime factor
// of a[i]
while (a[i] > 1) {
// Update frequency of
// prime factor spf[a[i]]
count[spf[a[i]]]++;
// Update a[i]
a[i] /= spf[a[i]];
}
}
// Traverse the array, count[]
for (ll i = 0; i < size; i++)
// If frequency of prime factor i in
// product of array elements
// greater than 0
if (count[i] > 0) {
// Calculate (i^(count[i]+1))-1 and
// multiplicative inverse of (i -1)
ll num1 = sub(power(i, count[i] + 1), 1);
ll num2 = inverse(i - 1);
ans = mul(ans, mul(num1, num2));
}
return ans;
}
// Driver Code
int main()
{
sieve();
int arr[] = { 1, 3, 2, 5, 4 };
int N = sizeof(arr) / sizeof(arr[0]);
ll res = sumof_factors(arr, N);
cout << res;
return 0;
}
Java
// Java program to implement
// the above approach
import java.util.HashMap;
import java.util.Map;
class GFG {
static final long mod = (int)(1e9 + 7);
static final int size = (int)(1e6 + 100);
// Function to subtract two numbers
static final long sub(long a, long b)
{
return (mod + a % mod - b % mod) % mod;
}
// Function to multiply two numbers
static final long mul(long a, long b)
{
return (a % mod * b % mod) % mod;
}
// Function to calculate
// x to the power y
static long power(long x, long y)
{
// Stores x ^ y
long res = 1;
for (res = 1; y > 0;
x = (x * x) % mod, y >>= 1) {
// If y is odd
if ((y & 1) == 1) {
// Update result
res = (res * x) % mod;
}
}
return res;
}
// Function to find inverse
// of a mod 1e9 + 7
static long inverse(long a)
{
return power(a, mod - 2);
}
// Stores minimum prime
// factorization of a number
static int spf[] = new int[size];
// Function to find the smallest prime factor
// of numbers in the range [1, 1000100]
static void sieve()
{
for (int i = 1; i < size; i += 2)
spf[i] = i;
for (int i = 2; i < size; i += 2)
spf[i] = 2;
for (int i = 3; i * i < size; i += 2)
if (spf[i] == i)
for (int j = i * i; j < size; j += i)
spf[j] = i;
}
// Function to calculate sum of factors
// of product of the given array
static long sumof_factors(int a[], int n)
{
// Traverse the array
for (int i = 0; i < n; i++)
if (a[i] == 0)
return 0;
// Stores the sum of factors of
// product of all array elements
long ans = 1;
// count[i]: Stores frequency of
// prime factor i in product of
// all the array elements
Map<Integer, Integer> count
= new HashMap<Integer, Integer>();
// Traverse the array
for (int num : a) {
// Calculate the prime factor
// of a[i]
while (num > 1) {
int temp = 0;
try {
temp = count.get(spf[num]);
}
catch (Exception e) {
temp = 0;
}
// Update frequency of
// prime factor spf[a[i]]
count.put(spf[num], temp + 1);
// Update num
num /= spf[num];
}
}
for (Map.Entry<Integer, Integer> i :
count.entrySet()) {
// Calculate (i^(count[i]+1))-1 and
// multiplicative inverse of (i -1)
long num1 = sub(
power(i.getKey(), i.getValue() + 1), 1);
long num2 = inverse(i.getKey() - 1);
ans = mul(ans, mul(num1, num2));
}
return ans;
}
// Driver Code
public static void main(String[] args)
{
sieve();
int n = 5;
int a[] = { 1, 3, 2, 5, 4 };
System.out.println(sumof_factors(a, n));
}
}
Python3
# Python program to implement
# the above approach
from collections import defaultdict
from math import sqrt
# Function to find the smallest prime factor
# of numbers in the range [1, 1000100]
def computeSPF(size):
# Stores smallest prime
# factorization of a number
spf = [i for i in range(size)]
# Update the smallest prime factor of
# all the numbers which is divisible by 2
for i in range(2, size, 2):
spf[i] = 2
# Calculate the smallest prime factor
# of all the numbers in the range [3, 1000100]
for i in range(3, int(sqrt(size))+1, 2):
if spf[i] == i:
for j in range(i * i, size, i):
spf[j] = i
return spf
# Function to calculate sum of factors
# of product of the given array
def sumof_factors(a, n, spf, mod):
# Traverse the array
if 0 in a:
return 0
count = defaultdict(int)
# Stores the sum of factors of
# product of all array elements
ans = 1
# Traverse the array
for num in a:
# Calculate the prime factor
# of a[i]
while num > 1:
# Update frequency of
# prime factor spf[a[i]]
count[spf[num]] += 1
num //= spf[num]
# Traverse the array, count[]
for i in count:
num1 = pow(i, count[i]+1, mod) - 1
num2 = pow(i-1, mod-2, mod)
ans = (ans * num1 * num2) % mod
return ans
# Driver Code
def main():
spf = computeSPF(10**6)
mod = 10**9 + 7
n = 4
a = [1, 3, 2, 5]
ans = sumof_factors(a, n, spf, mod)
print(ans)
main()
C#
// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
class GFG {
static long mod = (int)(1e9 + 7);
static int size = (int)(1e6 + 100);
// Function to subtract two numbers
static long sub(long a, long b)
{
return (mod + a % mod - b % mod) % mod;
}
// Function to multiply two numbers
static long mul(long a, long b)
{
return (a % mod * b % mod) % mod;
}
// Function to calculate
// x to the power y
static long power(long x, long y)
{
// Stores x ^ y
long res = 1;
for (res = 1; y > 0; x = (x * x) % mod, y >>= 1) {
// If y is odd
if ((y & 1) == 1) {
// Update result
res = (res * x) % mod;
}
}
return res;
}
// Function to find inverse
// of a mod 1e9 + 7
static long inverse(long a)
{
return power(a, mod - 2);
}
// Stores minimum prime
// factorization of a number
static int[] spf = new int[size];
// Function to find the smallest prime factor
// of numbers in the range [1, 1000100]
static void sieve()
{
for (int i = 1; i < size; i += 2)
spf[i] = i;
for (int i = 2; i < size; i += 2)
spf[i] = 2;
for (int i = 3; i * i < size; i += 2)
if (spf[i] == i)
for (int j = i * i; j < size; j += i)
spf[j] = i;
}
// Function to calculate sum of factors
// of product of the given array
static long sumof_factors(int[] a, int n)
{
// Traverse the array
for (int i = 0; i < n; i++)
if (a[i] == 0)
return 0;
// Stores the sum of factors of
// product of all array elements
long ans = 1;
// count[i]: Stores frequency of
// prime factor i in product of
// all the array elements
Dictionary<int, int> count
= new Dictionary<int, int>();
// Traverse the array
for (int i = 0; i < a.Length; i++) {
// Calculate the prime factor
// of a[i]
while (a[i] > 1) {
int temp = 0;
if (count.ContainsKey(spf[a[i]]))
temp = count[spf[a[i]]];
// Update frequency of
// prime factor spf[a[i]]
count[spf[a[i]]] = temp + 1;
// Update num
a[i] /= spf[a[i]];
}
}
foreach(KeyValuePair<int, int> i in count)
{
// Calculate (i^(count[i]+1))-1 and
// multiplicative inverse of (i -1)
long num1 = sub(power(i.Key, i.Value + 1), 1);
long num2 = inverse(i.Key - 1);
ans = mul(ans, mul(num1, num2));
}
return ans;
}
// Driver Code
public static void Main(string[] args)
{
sieve();
int n = 5;
int[] a = { 1, 3, 2, 5, 4 };
Console.WriteLine(sumof_factors(a, n));
}
}
// This code is contributed by ukasp.
JavaScript
// Function to calculate mod inverse
function expmod( base, exp, mod ){
if (exp == 0) return 1;
if (exp % 2 == 0){
return Math.pow( expmod( base, (exp / 2), mod), 2) % mod;
}
else {
return (base * expmod( base, (exp - 1), mod)) % mod;
}
}
// Function to find the smallest prime factor
// of numbers in the range [1, 1000100]
function computeSPF(size) {
// Stores smallest prime
// factorization of a number
const spf = Array.from(Array(size).keys());
// Update the smallest prime factor of
// all the numbers which is divisible by 2
for (let i = 2; i < size; i += 2) {
spf[i] = 2;
}
// Calculate the smallest prime factor
// of all the numbers in the range [1, sqrt(size)]
for (let i = 3; i <= Math.sqrt(size); i += 2) {
if (spf[i] == i) {
for (let j = i * i; j < size; j += i) {
spf[j] = i;
}
}
}
return spf;
}
// Function to calculate sum of factors
// of product of the given array
function sumofFactors(a, n, spf, mod) {
// Traverse the array
if (a.includes(0)) {
return 0;
}
let count = {};
// Stores the sum of factors of
// product of all array elements
let ans = 1;
// Traverse the array
for (let num of a) {
// Calculate the prime factorization of num
let primeFactors = {};
while (num > 1) {
// Update frequency of prime factor spf[num
// Update frequency of
// prime factor spf[a[i]]
if (!count.hasOwnProperty(spf[num])) {
count[spf[num]] = 1;
} else {
count[spf[num]]++;
}
num = Math.floor(num / spf[num]);
}
}
// Traverse the array, count[]
for (let i of Object.keys(count)) {
i = parseInt(i)
let num1 = expmod(i, count[i] + 1, mod) - 1;
let num2 = expmod(i - 1, mod - 2, mod);
ans = (ans * num1 * num2) % mod;
}
return ans;
}
// Driver Code
function main() {
const spf = computeSPF(10 ** 6);
const mod = 10 ** 9 + 7;
const n = 4;
const a = [1, 3, 2, 5];
const ans = sumofFactors(a, n, spf, mod);
console.log(ans);
}
main();
Time Complexity: O(N * log(log(N)))
Auxiliary Space: O(N)
Similar Reads
Sum of the Product of digits of all Array elements
Given an array arr, the task is to find the sum of the product of digits of all array elements Example: Input: arr[]={11, 23, 41}Output: 11Explanation: 1*1 + 2*3 + 4*1 = 1 + 6 + 4 = 1111 Input: arr[]={46, 32, 78, 0}Output: 86 Approach: To solve this problem, find the product of digits of all numbers
4 min read
Product of all the pairs from the given array
Given an array arr[] of N integers, the task is to find the product of all the pairs possible from the given array such as: (arr[i], arr[i]) is also considered as a valid pair.(arr[i], arr[j]) and (arr[j], arr[i]) are considered as two different pairs. Print the resultant answer modulus 10^9+7. Exam
11 min read
Minimum sum of product of elements of pairs of the given array
Given an array arr[] of even number of element N in it. The task is to form N/2 pairs such that sum of product of elements in those pairs is minimum. Examples Input: arr[] = { 1, 6, 3, 1, 7, 8 } Output: 270 Explanation: The pair formed are {1, 1}, {3, 6}, {7, 8} Product of sum of these pairs = 2 * 9
5 min read
Sum of all ordered pair-products from a given array
Given an array arr[] of size N, the task is to find the sum of all products of ordered pairs that can be generated from the given array elements.Examples: Input: arr[] ={1, 2, 3}Output: 36Explanation:All possible pairs are {(1, 1), {1, 2}, {1, 3}, {2, 1}, {2, 2}, {2, 3}, {3, 1}, {3, 2}, {3, 3}}. The
4 min read
Maximum product of sum of two contiguous subarrays of an array
Given an array arr[] of N positive integers, the task is to split the array into two contiguous subarrays such that the product of the sum of two contiguous subarrays is maximum. Examples: Input: arr[] = {4, 10, 1, 7, 2, 9} Output: 270 All possible partitions and their product of sum are: {4} and {1
10 min read
Find the suffix factorials of a suffix sum array of the given array
Given an array arr[] consisting of N positive integers, the task is to find the suffix factorials of a suffix sum array of the given array. Examples: Input: arr[] = {1, 2, 3, 4}Output: {3628800, 362880, 5040, 24}Explanation: The suffix sum of the given array is {10, 9, 7, 4}. Therefore, suffix facto
5 min read
Sum of product of all pairs of array elements
Given an array A[] of integers find sum of product of all pairs of array elements i. e., we need to find of product after execution of following pseudo code product = 0 for i = 1:n for j = i+1:n product = product + A[i]*A[j] Examples: Input : A[] = {1, 3, 4} Output : 19 Possible Pairs : (1,3), (1,4)
12 min read
Sum of all the factors of a number
Given a number n, the task is to find the sum of all the factors.Examples : Input : n = 30 Output : 72 Dividers sum 1 + 2 + 3 + 5 + 6 + 10 + 15 + 30 = 72 Input : n = 15 Output : 24 Dividers sum 1 + 3 + 5 + 15 = 24 Recommended PracticeFactors SumTry It! A simple solution is to traverse through all di
12 min read
Sum of array elements which are prime factors of a given number
Given an array arr[] of size N and a positive integer K, the task is to find the sum of all array elements which are prime factors of K. Examples: Input: arr[] = {1, 2, 3, 5, 6, 7, 15}, K = 35Output: 12Explanation: From the given array, 5 and 7 are prime factors of 35. Therefore, required sum = 5 +
8 min read
Sum of product of all pairs of a Binary Array
Given a binary array arr[] of size N, the task is to print the sum of product of all pairs of the given array elements. Note: The binary array contains only 0 and 1. Examples: Input: arr[] = {0, 1, 1, 0, 1}Output: 3Explanation: Sum of product of all possible pairs are: {0 Ã 1 + 0 Ã 1 + 0 Ã 0 + 0 Ã 1
5 min read