Least common element in given two Arithmetic sequences | C ++ program to implement the above approach ; Function to find the smallest element common in both the subsequences ; If a is equal to c ; If a exceeds c ; Check for the satisfying equation ; Least value of possible_y satisfying the given equation will yield true in the below if and break the loop ; If the value of possible_y satisfying the given equation lies in range [ 0 , b ] ; If no value of possible_y satisfies the given equation ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; long smallestCommon ( long a , long b , long c , long d ) { if ( a == c ) return a ; if ( a > c ) { swap ( a , c ) ; swap ( b , d ) ; } long first_term_diff = ( c - a ) ; long possible_y ; for ( possible_y = 0 ; possible_y < b ; possible_y ++ ) { if ( ( first_term_diff % b + possible_y * d ) % b == 0 ) { break ; } } if ( possible_y != b ) { return c + possible_y * d ; } return -1 ; } int main ( ) { long A = 2 , B = 20 , C = 19 , D = 9 ; cout << smallestCommon ( A , B , C , D ) ; return 0 ; }