Count pairs of numbers from 1 to N with Product divisible by their Sum in C++

C++Server Side ProgrammingProgramming

We are given a number N. The goal is to find the pairs of numbers from 1 to N such that the product of pairs is equal to the sum of pairs.

Let us understand with examples.

Input − N=11

Output − Count of pairs of no. from 1 to N with Product divisible by their Sum are − 1

Explanation − Numbers 3 and 6 have product 18 and their sum 9 fully divides 18.

Input − N=30

Output − Count of pairs of no. from 1 to N with Product divisible by their Sum are − 12

Explanation − Pairs are − (3, 6), (4,12), (5, 20), (6, 12), (6, 30), (8, 24), (9, 18), (10, 15), (12, 24), (15, 30), (20, 30), (21, 28)

Count of pairs − 12

The approach used in the below program is as follows

We will traverse from 1 to N using FOR loop twice. For every, i search for j such that the product of (i,j) is divisible by sum i+j. Increment count for suc i,j pairs such that i!=j.

  • Take a number N as input.

  • Function Sum_N(N) takes N and returns the count of pairs such that the product of numbers is divisible by sum of numbers.

  • Traverse from i=1 to i<N.

  • Travers from j=i+1 to j<=N.

  • Take the initial count as 0.

  • For each i and j calculate temp= (i*j)%(i+j).

  • If temp is 0 then sum fully divides the product. Increment count.

  • After the end of all iterations, the count will have a total number of such pairs.

  • Return count as result.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int Sum_N(int N){
   int count = 0;
   for (int i = 1; i < N; i++){
      for (int j = i + 1; j <= N; j++){
         int temp = (j * i) % (j + i);
         if (!temp){
            count++;
         }
      }
   }
   return count;
}
int main(){
   int N = 20;
   cout<<"Count of pairs of numbers from 1 to N with Product divisible by their Sum are: "<<Sum_N(N);
   return 0;
}

Output

If we run the above code it will generate the following output −

Count of pairs of numbers from 1 to N with Product divisible by their Sum are: 6
raja
Published on 02-Dec-2020 15:47:57
Advertisements