Minimum elements inserted in a sorted array to form an Arithmetic progression | Function to find the greatest common divisor of two numbers ; Function to find the minimum the minimum number of elements required to be inserted into array ; Difference array of consecutive elements of the array ; GCD of the difference array ; Loop to calculate the minimum number of elements required ; Driver Code ; Function calling
function gcdFunc ( a , b ) { if ( b == 0 ) return a ; return gcdFunc ( b , a % b ) ; } function findMinimumElements ( a , n ) { let b = new Array ( n - 1 ) ; for ( let i = 1 ; i < n ; i ++ ) { b [ i - 1 ] = a [ i ] - a [ i - 1 ] ; } let gcd = b [ 0 ] ; for ( let i = 0 ; i < n - 1 ; i ++ ) { gcd = gcdFunc ( gcd , b [ i ] ) ; } let ans = 0 ; for ( let i = 0 ; i < n - 1 ; i ++ ) { ans += ( b [ i ] / gcd ) - 1 ; } return ans ; } let arr1 = [ 1 , 6 , 8 , 10 , 14 , 16 ] ; let n1 = arr1 . length ; document . write ( findMinimumElements ( arr1 , n1 ) + " " ) ;