-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSquare Function.cpp
86 lines (71 loc) · 1.63 KB
/
Square Function.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define M 4
ll prime[1000001] = { 0 };
// Array k[] to store the value of k for
// each element in arr[]
ll k[1000001] = { 0 };
// For value of k, Sieve function is
// implemented
void Sieve()
{
// Initialize k[i] to i
for (ll i = 1; i < 1000001; i++)
k[i] = i;
// Prime Sieve
for (ll i = 2; i < 1000001; i++) {
// If i is prime then remove all
// factors of prime from it
if (prime[i] == 0)
for (ll j = i; j < 1000001; j += i) {
// Update that j is not
// prime
prime[j] = 1;
// Remove all square divisors
// i.e. if k[j] is divisible
// by i*i then divide it by i*i
while (k[j] % (i * i) == 0)
k[j] /= (i * i);
}
}
}
// Function that return total count
// of pairs with pefect square product
ll countPairs(ll arr[], ll n)
{
// Map used to store the frequency of k
unordered_map<ll, ll> freq;
// Store the frequency of k
for (ll i = 0; i < n; i++) {
freq[k[arr[i]]]++;
}
ll sum = 0;
// The total number of pairs is the
// summation of (fi * (fi - 1))/2
for (auto i : freq) {
sum += ((i.second - 1) * i.second) / 2;
}
return sum;
}
void solve(){
ll n;
cin>>n;
ll a[n];
for(ll i=0;i<n;i++)
cin>>a[i];
ll ct=countPairs(a,n);
ll y=(n-1)*(n)/2;
ll ans=y-ct;
cout<<ans<<endl;
}
int main()
{
Sieve();
int t;
cin>>t;
while(t--){
solve();
}
return 0;
}