Given four positive numbers A, B, C, D, such that A and B are the first term and the common difference of first Arithmetic sequence respectively, while C and D represent the same for the second Arithmetic sequence respectively as shown below:
First Arithmetic Sequence: A, A + B, A + 2B, A + 3B, ……. Second Arithmetic Sequence: C, C + D, C + 2D, C + 3D, …….
The task is to find the least common element from the above AP sequences. If no such number exists, then print -1.
Since any term of the given two sequences can be expressed as A + x*B and C + y*D, therefore, to solve the problem, we need to find the smallest values of x and y for which the two terms are equal. Follow the steps below to solve the problem:
In order to find the smallest value common in both the AP sequences, the idea is to find the smallest integer values of x and y satisfying the following equation:
A + x*B = C + y*D
=> The above equation can be rearranged as x*B = C – A + y*D => The above equation can be further rearranged as x = (C – A + y*D) / B
Check if there exists any integer value y such that (C – A + y*D) % B is 0 or not. If it exists, then the smallest number is (C + y*D).
Check whether (C + y*D) is the answer or not, where y will be in a range (0, B) because from i = B, B+1, …. the remainder values will be repeated.
If no such number is obtained from the above steps, then print -1.
Below is the implementation of the above approach:
Please Login to comment...