Count pairs (i,j) such that (i+j) is divisible by both A and B in C++

C++Server Side ProgrammingProgramming

We are given variables N, M, A and B. The goal is to find ordered pairs of positive numbers( i, j ) such that their sum is divisible by both A and B. And 1<=i<=N and 1<=j<=M.

We will traverse using two loops for i and j. If sum (i+j)%A==0 && (i+j)%B==0. Increment count.

Let’s understand with examples.

Input 

N = 5, M = 10, A = 2, B = 3;

Output 

Ordered pairs (i,j) where (i+j) is divisible by both A & B: 9

Explanation 

Pairs will be (1,5) (2,4) (2,10) (3,3) (3,9) (4,2) (4,8) (5,1) (5,7). Total pairs is 9.

Input 

N = 10, M = 10, A = 10, B = 11;

Output 

Ordered pairs (i,j) where (i+j) is divisible by both A & B: 0

Explanation 

No such pairs possible.

Approach used in the below program is as follows

  • We take integers N, M, A, B.

  • Function sumDivisible(int n,int m,int a,int b) takes all variables and returns the count of ordered pairs with sum divisible by A and B.

  • Take the initial variable count as 0 for pairs.

  • Traverse using two for loop to find i and j.

  • Start from i=1 to i<=n and j=1 to j<=m.

  • Check if (i+j)%a==0 or (i+j)%b==0.

  • If true increment count.

  • At the end of all loops count will have a total number of such pairs.

  • Return the count as result.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int sumDivisible(int n,int m,int a,int b){
   int count = 0;
   for (int i = 1; i <= n; i++){
      for(int j = 1; j <= m; j++){
         if((i+j)%a==0 && (i+j)%b==0)
            { count++; }
      }
   }
   return count;
}
int main(){
   int N = 50, M = 100, A = 5, B = 10;
   cout <<"Ordered pairs (i,j) where (i+j) is divisible by both A & B: "<<sumDivisible(N,M,A,B);
   return 0;
}

Output

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

Ordered pairs (i,j) where (i+j) is divisible by both A & B: 500
raja
Published on 31-Oct-2020 05:11:04
Advertisements