Number of GP ( Geometric Progression ) subsequences of size 3 | C # program to count GP subsequences of size 3. ; Returns count of G . P . subsequences with length 3 and common ratio r ; Hashing to maintain left and right array elements to the main count ; Stores the answer ; Traverse through the elements ; Keep the count in the hash ; Traverse through all elements and find out the number of elements as k1 * k2 ; Keep the count of left and right elements left is a [ i ] / r and right a [ i ] * r ; If the current element is divisible by k , count elements in left hash . ; Decrease the count in right hash ; Number of right elements ; Calculate the answer ; left count of a [ i ] ; Returns answer ; Driver Code
using System ; using System . Collections . Generic ; class GFG { static long subsequences ( int [ ] a , int n , int r ) { Dictionary < int , int > left = new Dictionary < int , int > ( ) , right = new Dictionary < int , int > ( ) ; long ans = - 1 ; for ( int i = 0 ; i < n ; i ++ ) if ( right . ContainsKey ( a [ i ] ) ) right [ a [ i ] ] = right [ a [ i ] ] + 1 ; else right . Add ( a [ i ] , 1 ) ; for ( int i = 0 ; i < n ; i ++ ) { long c1 = 0 , c2 = 0 ; if ( a [ i ] % r == 0 ) if ( left . ContainsKey ( a [ i ] / r ) ) c1 = right [ a [ i ] / r ] ; else c1 = 0 ; if ( right . ContainsKey ( a [ i ] ) ) right [ a [ i ] ] = right [ a [ i ] ] ; else right . Add ( a [ i ] , - 1 ) ; if ( right . ContainsKey ( a [ i ] * r ) ) c2 = right [ a [ i ] * r ] ; else c2 = 0 ; ans += ( c1 * c2 ) ; if ( left . ContainsKey ( a [ i ] ) ) left [ a [ i ] ] = 0 ; else left . Add ( a [ i ] , 1 ) ; } return ans - 1 ; } public static void Main ( String [ ] args ) { int [ ] a = { 1 , 2 , 6 , 2 , 3 , 6 , 9 , 18 , 3 , 9 } ; int n = a . Length ; int r = 3 ; Console . WriteLine ( subsequences ( a , n , r ) ) ; } }