Convert given array to Arithmetic Progression by adding an element | Function to return the number to be added ; If difference of the current consecutive elements is different from the common difference ; If number has already been chosen then it 's not possible  to add another number ; If the current different is twice the common difference then a number can be added midway from current and previous element ; Number has been chosen ; It 's not possible to maintain  the common difference ; Return last element + common difference if no element is chosen and the array is already in AP ; Else return the chosen number ; Driver code
function getNumToAdd ( arr , n ) { arr . sort ( function ( a , b ) { return a - b } ) ; var d = arr [ 1 ] - arr [ 0 ] ; var numToAdd = - 1 ; var numAdded = false ; for ( var i = 2 ; i < n ; i ++ ) { var diff = arr [ i ] - arr [ i - 1 ] ; if ( diff != d ) { if ( numAdded ) return - 1 ; if ( diff == 2 * d ) { numToAdd = arr [ i ] - d ; numAdded = true ; } else return - 1 ; } } if ( numToAdd == - 1 ) return ( arr [ n - 1 ] + d ) ; return numToAdd ; } var arr = [ 1 , 3 , 5 , 7 , 11 , 13 , 15 ] ; var n = arr . length ; document . write ( getNumToAdd ( arr , n ) ) ;