C++ program to find first collision point of two series

C++Server Side ProgrammingProgramming

In this article, we will be discussing a program to find the first collision point i.e the first point that both of the series have.

In this, we would be given with five variables ‘a’, ‘b’, ‘c’, ‘d’ and ‘n’. We have to create two arithmetic progression series from these having n digits each

b, b+a, b+2a, ….b+(n-1)a
d, d+c, d+2c, ….. d+(n-1)c

And then find the first common point that both of the given series has.

To solve this, we would create the numbers in the first series. And for each number we would check if it is greater than or equal to the first number of the second series and also if the difference between that number and ‘d’ is divisible by c. If it satisfies both the conditions, than the current number in the first series would be the result.

Example

 Live Demo

#include<bits/stdc++.h>
using namespace std;
void calc_series(int a, int b, int c, int d, int n) {
   int x , flag = 0;
   //creating the numbers of first series
   for (int i = 0; i < n; i++) {
      x = b + i * a;
      //checking if it exists in second series
      if ((x - d) % c == 0 and x - d >= 0){
         cout << "First collision point : "<< x << endl;
         flag = 1;
         break;
      }
   }
   if(flag == 0) {
      cout << "No collision point exists" << endl;
   }
}
int main() {
   int a = 16;
   int b = 9;
   int c = 23;
   int d = 19;
   int n = 78;
   calc_series(a, b, c, d, n);
   return 0;
}

Output

First collision point : 249
raja
Published on 03-Oct-2019 11:42:11
Advertisements