Find sum of a[i]%a[j] for all valid pairs
Given an array arr[] of size N. The task is to find the sum of arr[i] % arr[j] for all valid pairs. Answer can be large. So, output answer modulo 1000000007
Examples:
Input: arr[] = {1, 2, 3}
Output: 5
(1 % 1) + (1 % 2) + (1 % 3) + (2 % 1) + (2 % 2)
+ (2 % 3) + (3 % 1) + (3 % 2) + (3 % 3) = 5
Input: arr[] = {1, 2, 4, 4, 4}
Output: 10
Approach: Store the frequency of each element and run a nested loop on the frequency array and find the required answer.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
#define mod (int)(1e9 + 7)
int Sum_Modulo( int a[], int n)
{
int max = *max_element(a, a + n);
int cnt[max + 1] = { 0 };
for ( int i = 0; i < n; i++)
cnt[a[i]]++;
long long ans = 0;
for ( int i = 1; i <= max; i++) {
for ( int j = 1; j <= max; j++) {
ans = ans + cnt[i] * cnt[j] * (i % j);
ans = ans % mod;
}
}
return ( int )(ans);
}
int main()
{
int a[] = { 1, 2, 3 };
int n = sizeof (a) / sizeof (a[0]);
cout << Sum_Modulo(a, n);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int mod = ( int )(1e9 + 7 );
static int Sum_Modulo( int a[], int n)
{
int max = Arrays.stream(a).max().getAsInt();
int []cnt= new int [max + 1 ];
for ( int i = 0 ; i < n; i++)
cnt[a[i]]++;
long ans = 0 ;
for ( int i = 1 ; i <= max; i++)
{
for ( int j = 1 ; j <= max; j++)
{
ans = ans + cnt[i] *
cnt[j] * (i % j);
ans = ans % mod;
}
}
return ( int )(ans);
}
public static void main(String[] args)
{
int a[] = { 1 , 2 , 3 };
int n = a.length;
System.out.println(Sum_Modulo(a, n));
}
}
|
Python3
mod = 10 * * 9 + 7
def Sum_Modulo(a, n):
Max = max (a)
cnt = [ 0 for i in range ( Max + 1 )]
for i in a:
cnt[i] + = 1
ans = 0
for i in range ( 1 , Max + 1 ):
for j in range ( 1 , Max + 1 ):
ans = ans + cnt[i] * \
cnt[j] * (i % j)
ans = ans % mod
return ans
a = [ 1 , 2 , 3 ]
n = len (a)
print (Sum_Modulo(a, n))
|
C#
using System;
using System.Linq;
class GFG
{
static int mod = ( int )(1e9 + 7);
static int Sum_Modulo( int []a, int n)
{
int max = a.Max();
int []cnt = new int [max + 1];
for ( int i = 0; i < n; i++)
cnt[a[i]]++;
long ans = 0;
for ( int i = 1; i <= max; i++)
{
for ( int j = 1; j <= max; j++)
{
ans = ans + cnt[i] *
cnt[j] * (i % j);
ans = ans % mod;
}
}
return ( int )(ans);
}
public static void Main(String[] args)
{
int []a = { 1, 2, 3 };
int n = a.Length;
Console.WriteLine(Sum_Modulo(a, n));
}
}
|
Javascript
<script>
let mod = 1e9 + 7
function Sum_Modulo(a, n)
{
let max = a.sort((a, b) => b - a)[0];
let cnt = new Array(max + 1).fill(0);
for (let i = 0; i < n; i++)
cnt[a[i]]++;
let ans = 0;
for (let i = 1; i <= max; i++) {
for (let j = 1; j <= max; j++) {
ans = ans + cnt[i] * cnt[j] * (i % j);
ans = ans % mod;
}
}
return (ans);
}
let a = [1, 2, 3];
let n = a.length;
document.write(Sum_Modulo(a, n));
</script>
|
Time Complexity: O(MAX2)
Auxiliary Space: O(MAX)
Last Updated :
12 Jul, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...