Given five numbers a, b, c, d and n (where a, b, c, d, n > 0). These values represent n terms of two series. The two series formed by these four numbers are b, b+a, b+2a….b+(n-1)a and d, d+c, d+2c, ….. d+(n-1)c
These two series will collide when at any single point summation values becomes exactly the same for both the series.Print the collision point.
Example: Input : a = 20, b = 2, c = 9, d = 19, n = 100 Output: 82 Explanation: Series1 = (2, 22, 42, 62, 82, 102...) Series2 = (28, 37, 46, 55, 64, 73, 82, 91..) So the first collision point is 82.
A naive approach is to calculate both the series in two different arrays, and then check for each element if it collides by running two nested loops
Time complexity: O(n * n)
Auxiliary Space: O(n)
An efficient Approach to the problem mentioned above is:
* Generate all elements of first series. Let current element be x.
* If x is also an element of second series, then following conditions should satisfy.
…..a) x should be greater than or equal to first element of second series.
…..a) Difference between x and first element should be divisible by c.
*If the above conditions are satisfied then the i-th value is the required meeting point.
Below is the implementation of the above problem :
Time complexity : O(n)
This article is contributed by Twinkle Bajaj. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Reflection of a point at 180 degree rotation of another point
- Rotation of a point about another point in C++
- Reflection of a point about a line in C++
- Distance between a point and a Plane in 3 D
- Shortest distance between a point and a circle
- Check whether the point (x, y) lies on a given line
- Finding the best fit rectangle that covers a given point
- Bitonic point in the given linked list
- Check whether given floating point number is even or odd
- Program to find the Break Even Point
- Find the Missing Point of Parallelogram
- Find Tangent at a given point on the curve
- Find normal at a given point on the curve
- Check if a point is inside, outside or on the parabola
- Perpendicular distance between a point and a Line in 2 D
Improved By : vt_m