1+ // Link to Submission: https://codeforces.com/contest/1225/submission/355410192
2+
3+ /*
4+ Problem Statement:
5+ You are given n positive integers a1, …, an, and an integer k ≥ 2.
6+ Count the number of pairs i, j such that 1 ≤ i < j ≤ n, and there exists an integer x such that ai ⋅ aj = x^k.
7+ */
8+
9+ /*
10+ Brief Explanation:
11+ To avoid TLE we avoid comparing each combination of elements, rather we calculate the reduced form of each element in the array.
12+ The reduced form of an element can be calculated as -> A = q^x * p^y... ~ q^(x % k) * p^(y %k)...
13+ We then get the complement i.e. Ac ~ q^((k - (x % k)) % k) * p^((k - (y % k)) % k)
14+ While iterating through the array, we maintain a frequency map of reduced forms.
15+ For each element, we count how many previously seen reduced forms equal its complement and add that to the pair count.
16+ */
17+
18+ import java .util .*;
19+
20+ public class Solution2 {
21+ static long [] reducedAndComplement (long x , int k ) {
22+ long rf = 1 ;
23+ long comp = 1 ;
24+
25+ for (long p = 2 ; p * p <= x ; p ++) {
26+ int count = 0 ;
27+
28+ while (x % p == 0 ) {
29+ x /= p ;
30+ count ++;
31+ }
32+
33+ count %= k ;
34+
35+ for (int i = 0 ; i < count ; i ++)
36+ rf *= p ;
37+
38+ int req = (k - count ) % k ;
39+ for (int i = 0 ; i < req ; i ++)
40+ comp *= p ;
41+ }
42+
43+ if (x > 1 ) {
44+ rf *= x ;
45+ int req = (k - 1 ) % k ;
46+ for (int i = 0 ; i < req ; i ++)
47+ comp *= x ;
48+ }
49+
50+ return new long []{rf , comp };
51+ }
52+
53+ public static void main (String [] args ) {
54+ Scanner sc = new Scanner (System .in );
55+ HashMap <Long , Integer > freq = new HashMap <>();
56+ int n = sc .nextInt ();
57+ int k = sc .nextInt ();
58+
59+ long fc = 0 ;
60+
61+ for (int i = 0 ; i < n ; i ++) {
62+ long a = sc .nextLong ();
63+ long [] rc = reducedAndComplement (a , k );
64+ long r = rc [0 ];
65+ long c = rc [1 ];
66+
67+ fc += freq .getOrDefault (c , 0 );
68+
69+ freq .put (r , freq .getOrDefault (r , 0 ) + 1 );
70+ }
71+
72+ System .out .println (fc );
73+
74+ sc .close ();
75+ }
76+ }
77+
78+ // Time Complexity: O(n * sqr.root(A))
79+ // Space Complexity: O(n)
0 commit comments