Minimum possible value of D which when added to or subtracted from K repeatedly obtains every array element | C ++ program for the above approach ; Recursive function tox previous gcd of a and b ; Function to find the maximum value of D such that every element in the array can be obtained by performing K + D or K - D ; Traverse the array arr [ ] ; Update arr [ i ] ; Stores GCD of the array ; Iterate over the range [ 1 , N ] ; Update the value of D ; Print the value of D ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int gcd ( int a , int b ) { if ( b == 0 ) return a ; return gcd ( b , a % b ) ; } int findMaxD ( int arr [ ] , int N , int K ) { for ( int i = 0 ; i < N ; i ++ ) { arr [ i ] = abs ( arr [ i ] - K ) ; } int D = arr [ 0 ] ; for ( int i = 1 ; i < N ; i ++ ) { D = gcd ( D , arr [ i ] ) ; } return D ; } int main ( ) { int arr [ ] = { 1 , 7 , 11 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 3 ; cout << findMaxD ( arr , N , K ) ; return 0 ; }