Number of quadruples where the first three terms are in AP and last three terms are in GP | Java implementation of the approach ; Function to return the count of quadruples ; Hash table to count the number of occurrences ; Traverse and increment the count ; Run two nested loop for second and third element ; If they are same ; Initially decrease the count ; Find the first element using common difference ; Find the fourth element using GP y ^ 2 = x * z property ; If it is an integer ; If not equal ; Same elements ; Later increase the value for future calculations ; Driver code
import java . util . * ; class GFG { static int countQuadruples ( int a [ ] , int n ) { HashMap < Integer , Integer > mp = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) if ( mp . containsKey ( a [ i ] ) ) { mp . put ( a [ i ] , mp . get ( a [ i ] ) + 1 ) ; } else { mp . put ( a [ i ] , 1 ) ; } int count = 0 ; for ( int j = 0 ; j < n ; j ++ ) { for ( int k = 0 ; k < n ; k ++ ) { if ( j == k ) continue ; mp . put ( a [ j ] , mp . get ( a [ j ] ) - 1 ) ; mp . put ( a [ k ] , mp . get ( a [ k ] ) - 1 ) ; int first = a [ j ] - ( a [ k ] - a [ j ] ) ; int fourth = ( a [ k ] * a [ k ] ) / a [ j ] ; if ( ( a [ k ] * a [ k ] ) % a [ j ] == 0 ) { if ( a [ j ] != a [ k ] ) { if ( mp . containsKey ( first ) && mp . containsKey ( fourth ) ) count += mp . get ( first ) * mp . get ( fourth ) ; } else if ( mp . containsKey ( first ) && mp . containsKey ( fourth ) ) count += mp . get ( first ) * ( mp . get ( fourth ) - 1 ) ; } if ( mp . containsKey ( a [ j ] ) ) { mp . put ( a [ j ] , mp . get ( a [ j ] ) + 1 ) ; } else { mp . put ( a [ j ] , 1 ) ; } if ( mp . containsKey ( a [ k ] ) ) { mp . put ( a [ k ] , mp . get ( a [ k ] ) + 1 ) ; } else { mp . put ( a [ k ] , 1 ) ; } } } return count ; } public static void main ( String [ ] args ) { int a [ ] = { 2 , 6 , 4 , 9 , 2 } ; int n = a . length ; System . out . print ( countQuadruples ( a , n ) ) ; } }