We need to determine for given array of N up to 10^6, each A_i up to 10^6, whether the numbers are pairwise coprime, setwise coprime, or not coprime.
We need to compute:
-
Pairwise coprime: for all i<j, gcd(A_i, A_j)=1. That is equivalent to saying that for every prime number, at most one of the A_i's is divisible by that prime. So the set of prime factors across all numbers have no overlap. So we can count frequency of primes among the numbers. If any prime appears in at least two numbers, then it's not pairwise coprime.
-
Setwise coprime: the overall gcd of all numbers is 1, but they are not pairwise coprime. So we need to compute gcd_all = gcd(A_1,...,A_N). If gcd_all != 1 => not coprime. If gcd_all == 1, then either pairwise coprime or setwise coprime depending on the pairwise condition.
So we can solve as:
-
Compute overall_gcd = reduce gcd over array. If != 1, output "not coprime".
-
Else, check if pairwise coprime. If yes, output "pairwise coprime", else output "setwise coprime".
Now, the challenge is to check pairwise coprime efficiently for N up to 1e6 and Ai up to 1e6. A naive approach for each number factorizing and checking prime collisions can be done by using sieve to precompute smallest prime factor (SPF) up to 1e6. Then factorize each number in O(log Ai). Use an array cnt[p] to count how many numbers have prime p as a factor. While factorizing, for each distinct prime factor of A_i (but careful: if a number has repeated prime factor, we only need to count the prime once for that number, because if two numbers share prime p, gcd>1. If a number has p^2, it still only matters if p appears in another number). So we can use a set per number to avoid double counting same prime for same number.
But N=1e6, factorization per number might be okay: each number up to 1e6 has at most 7 distinct prime factors (since 2357111317=510510, and 2357111317*19=9699690 > 1e6, so max distinct primes is 7). So total operations about O(N * number of distinct primes) which is about up to 7e6, plus factorizing using SPF: each factorization step might require dividing by primes repeatedly; but we can extract distinct primes by dividing until we get all. Complexity O(N log Ai) basically.
But we need to be careful about memory and speed. Also, we need to ensure we don't count a prime multiple times per number: if we increment cnt[p] for each occurrence, but we should increment only once per number. Because if we increment multiple times for same number, we might mistakenly think there is collision when there is only one number that has p multiple times; but that's not a problem because we only need to detect if cnt[p] >= 2. However if we increment for each occurrence, then for a single number with p^k, cnt[p] would increase by k (maybe >1) and then when we check we might think cnt[p]>=2 even though only one number. That would incorrectly conclude not pairwise coprime. So we must only count each prime once per number. So we can use a boolean visited per prime for current number, or use a set, or we can factorize to get distinct primes and for each distinct prime increment cnt[p] by 1.
Alternatively, we can use an array "last_seen[p]" that stores the index of the last number that contributed to cnt[p]? But simpler: factor distinct primes, increment cnt[p] and if any cnt[p] > 1 after increment, we could early stop and conclude not pairwise. But we need to be careful: if a number has duplicate prime, we might still early stop incorrectly if we just increment for each factor step without dedup. So we need dedup.
Approach: Precompute SPF up to max A (1e6). For each A_i:
But careful: Suppose number is 12 = 2^2 * 3. The loop: p=2 (prev=0) -> cnt[2]++ becomes 1; then divide out 2's until x becomes 3; next p=3 (prev=2) different, so cnt[3]++ becomes 1. Works.
But if number is 18=23^2? Actually 18=23^2. p=2 (prev=0) cnt2++ ; then after dividing, x=9; p=3 (prev=2) cnt3++. OK.
If number has same prime repeated but we correctly skip duplicates by using prev_p.
But is it always safe? Suppose number = 4 = 2^2. First: p=2 (prev=0) cnt[2]++ ->1; then after dividing, x=1 (since 4/2=2 then again? Actually algorithm: while x>1: p=spf[x]; if p != prev: cnt[p]++; while x%p==0 x/=p; prev=p. For 4: first iteration: p=2, prev=0 => cnt[2]++. Then while loop: x%2==0 -> x=2; again x%2==0 -> x=1. Now x=1, exit. So only counted once. Good.
Thus we can detect collision early. If we find any cnt[p] > 1 after increment, we can set a flag.
But we must also compute overall gcd. We can compute overall gcd using a separate pass, e.g., g = 0; for each a: g = gcd(g, a). This is O(N log). So overall complexity O(N log max) acceptable.
However, note constraints: N up to 10^6, Ai up to 10^6. The SPF array size 10^6+1 is fine. We need to be careful about memory: cnt array of size maxA+1 (maybe 10^6+1) of ints (4 bytes) = 4 MB, okay. SPF array similarly.
Potential pitfalls: If Ai = 1. Then its prime factor set is empty, so no counts. That's fine.
Edge Cases: All numbers = 1? Then overall gcd =1, pairwise? Since 1 is coprime with 1 (gcd(1,1)=1). Usually, pairwise coprime holds because gcd(1,1)=1. So they are pairwise coprime. Our method: cnt never increments because 1 has no prime factors. So no collisions, so pairwise condition holds. So output pairwise coprime.
If overall gcd=1 but some primes appear in multiple numbers, then setwise coprime.
Now, there is a nuance: The definition of setwise coprime: " {Ai} is said to be setwise coprime when {Ai} is not pairwise coprime but GCD(A1,...,AN)=1." So if overall gcd=1 but pairwise condition fails => setwise. If overall gcd=1 and pairwise holds => pairwise. If overall gcd !=1 => not coprime.
Thus algorithm works.
But we must be careful: When overall gcd !=1, we output "not coprime", regardless of pairwise condition. But we could early exit after computing overall gcd if it's !=1. However we may also need to compute pairwise condition only when overall gcd=1. So we can first compute overall gcd, then if !=1 print not coprime and exit. Else, proceed to pairwise check.
Now, about factorization: We'll precompute SPF for up to 1e6 using sieve. Complexity O(maxA log log maxA) ~ 1e6.
But wait: Ai up to 10^6, but N can be 10^6, so total numbers factorized is high. However, each factorization takes O(number of prime factors) which is small, so it's fine.
But there is an alternative approach using the so-called "Möbius" or "gcd convolution" but not needed.
However, one must consider that if we have many numbers, and we increment cnt[p] for each distinct prime, we might hit memory or time. But it's okay.
But there is a subtlety: The pairwise condition requires that for every pair i<j, gcd(A_i, A_j)=1. This is equivalent to: For every prime p, at most one A_i is divisible by p. However, if a number has multiple primes, that's fine. So our cnt method correctly checks that.
But there's a nuance: Suppose we have a number A_i = p * q, and another number A_j = p * r. cnt[p] becomes 2 => not pairwise. Good.
But what about the case where two numbers share a composite factor but not a prime factor? e.g., A_i = 4, A_j = 6. gcd(4,6)=2, share prime 2. So prime overlap captures composite overlap. So it's correct.
Thus algorithm stands.
Now, we should be careful about large N and I/O speed. Use fast input like sys.stdin.buffer.
Now, we need to produce code accordingly.
Potential improvements: Instead of using cnt array of size 10^6+1, we could use a byte array or Python list of ints. But Python's list of ints is large (each int is 28 bytes). For 1e6 entries, that would be ~28 MB, which might be borderline but probably okay? Actually Python list of length 1e6 with integers (0 initially) will allocate 1e6 * 8 bytes for pointer? Actually Python list holds references to Python objects; each integer is a separate object. But if we initialize [0]* (maxA+1), each element is the same integer object 0? Actually Python uses shared small ints for -5 to 256, but the list holds references to the same object 0 for each slot? Wait: [0](maxA+1) creates a list where each entry is the same integer 0 object. That's fine because integer 0 is immutable, but when we increment an entry, we assign a new integer to that slot. So then memory usage will be: the list itself holds references (pointers) which is 8 bytes per entry on 64-bit? Actually list stores PyObject pointers, so 8 bytes each. So list of 1e6 ~8 MB. The integer objects themselves: each time we assign a new integer >256, a new Python int object is created (28 bytes). But we only need to store counts up to maybe a few, but if many primes appear, we might have many entries where cnt > 0. In worst case, numbers could be all the primes up to 1e6? But there are about 78k primes under 1e6. So at most 78k entries will have nonzero counts. So memory for those int objects is about 78k * 28 = ~2.2 MB. So total memory ~10 MB for cnt list, plus overhead. So okay.
But we also need spf array of size maxA+1. For spf, we could store ints as Python list. spf[i] is small (up to 1e6) and many will be same; but we assign each. spf list will have 1e6 references -> 8 MB. The integer objects: each spf entry will be a small integer maybe, but they are stored as Python ints; when building spf via sieve, we assign integers (like i for primes). For each index, we assign a Python int (maybe new object). That would create 1e6 ints, each 28 bytes -> 28 MB. That's a lot! Actually if we fill spf with ints, each entry will be a distinct integer object? Not necessarily: For small ints from -5 to 256, Python caches them, but spf values can be up to 1e6, which are not cached. So each spf[i] is a Python int object allocated in memory, 28 bytes each -> 28 MB. Plus list overhead 8 MB -> 36 MB. That's quite heavy but still maybe within typical memory limits? 256 MB? Possibly okay? But 36 MB for spf, plus cnt list (8 MB + overhead) plus other variables, total maybe ~50-60 MB. That's okay. However, some judges limit memory to 1024 MB, but AtCoder typical memory limit is 1024 MB? Actually AtCoder typical memory limit for such problems is 1024 MB or 256 MB? I've seen AtCoder problems with 1024 MB, but not sure. For "ABC 177 F" maybe? The problem is from AtCoder? Actually it's from AtCoder Beginner Contest 177? Wait no, it's from AtCoder "abc"? Let me recall: This problem "pairwise coprime" appears in AtCoder "ABC 177"? Actually ABC 177 had a problem about pairwise coprime? I'm not sure. But typical memory limit is 1024 MB. But still 36 MB is fine. However, we can reduce memory by using array.array('I') or using a list of ints but Python ints are objects, might be okay.
But there is another approach: We could use a sieve to mark primes and then factor numbers by trial division using precomputed primes list. That would use less memory? primes list length about 78k, each int object (28 bytes) -> 2.2 MB, plus boolean array for is_prime? But factorizing using trial division for each number would be O(number of primes up to sqrt(A_i)) but since Ai <= 1e6, we can precompute primes up to 1000? Actually sqrt(1e6)=1000. So each number could be factorized by dividing by primes up to 1000. But there are about 168 primes up to 1000. That's fine. For each number up to 1e6, we could factor by dividing by primes <= sqrt(A_i). That would be about 168 divisions per number in worst case, but that's 168 * 1e6 = 168e6 operations, which might be borderline in Python but possibly okay if optimized? But 168 million divisions might be too slow. So using SPF is better.
Alternatively, we can use a variant: use an array "cnt" and for each number, we can mark its prime factors by dividing using precomputed spf, as described. That's efficient.
We can also use "multiple marking" technique: For each prime p, we could count how many numbers are divisible by p, by iterating over multiples of p and checking if any A_i equals that multiple? Not directly; we have the list of numbers, we can count occurrences of each value, then for each prime p, we can sum over its multiples the count of that value. That would give the number of numbers divisible by p. This method is O(maxA log maxA) after counting frequencies, which might be simpler and avoid factorization per number. Since Ai <= 1e6, we can create an array freq of size maxA+1, count occurrences of each value. Then for each prime p up to maxA, we compute total = sum_{k=1}^{floor(maxA/p)} freq[p*k]. If total >= 2, then there are at least two numbers (maybe the same number counted twice if the same value appears multiple times? If a number appears multiple times, e.g., A_i = 6 appears twice, then freq[6] = 2, and for p=2, total will include freq[6] =2, so total>=2, indicating that there are at least two numbers that are divisible by 2, which means the numbers are not pairwise coprime because they share prime 2. However careful: If the same index counts? Actually pairwise condition: If the same value appears multiple times, then those two numbers are distinct (even if same value). Their gcd is that value, which may be >1 unless value=1. So indeed if a value >1 appears more than once, then those two numbers share all prime factors of that value. So the condition "total >= 2" correctly indicates a prime appears in at least two numbers (counting multiple occurrences of the same number as separate). So this method works. Also, we need to be careful about numbers equal to 1: freq[1] may be >1, but 1 has no prime factors, so it won't cause any total>=2 for any prime. So okay.
Thus we can compute pairwise condition without factorizing each number individually, by using the frequency array and iterating over primes and multiples. This method avoids per-number factorization and might be faster in Python due to the heavy cost of Python loops per number? But factorization per number is O(distinct primes) which is small (<=7). That's about 7 million loops, which is not huge. The frequency + sieve method requires iterating over all primes and multiples: number of operations = sum_{p prime}^{maxA} (maxA/p). This is roughly maxA * log log maxA? Actually sum_{p} 1/p diverges slowly, sum_{p <= N} 1/p ~ log log N + M. For N=1e6, sum 1/p ~ log log 1e6 + B ≈ log(13.8) + B ~ 2.6 + constant ~ maybe 2.9? So total multiples checked = maxA * sum_{p} 1/p ≈ 1e6 * 2.9 ≈ 2.9e6. But that's an underestimate because for each prime we check floor(maxA/p) multiples; sum_{p} floor(maxA/p) is about maxA * sum_{p} 1/p, plus corrections. Actually there are about 78k primes, but many of them have large p, so floor(maxA/p) is small. The total number of operations is about maxA * (1/2 + 1/3 + 1/5 + ...) but only over primes. The sum of reciprocals of primes up to 1e6 is around 2.9 as said, so operations ~ 2.9e6. That's even less than 7e6. However we also need to sum freq for each multiple; that involves memory access. That's very efficient. Also we need to compute primes up to maxA using sieve, which is O(maxA log log maxA). This seems efficient.
But we also need overall gcd. That's separate.
So approach B:
-
Read N and list A.
-
Compute overall_gcd using math.gcd in a loop.
-
If overall_gcd != 1: print "not coprime" and exit.
-
Else, we need to check pairwise.
-
Build freq array of size maxA+1 (maxA = max(A)). Initialize zeros, then for each a in A, freq[a] += 1.
-
Then we need to check for any prime p (p >= 2) such that total numbers divisible by p is >= 2.
We can do:
for p in range(2, maxA+1):
if is_prime[p]:
cnt = 0
for multiple in range(p, maxA+1, p):
cnt += freq[multiple]
if cnt >= 2:
# not pairwise
print("setwise coprime")? Wait we need to differentiate: if overall_gcd==1 and we find any prime with cnt>=2, then it's not pairwise => setwise coprime. So if we find any such prime, we can output "setwise coprime" and exit.
# else continue
If we finish the loop without finding any prime with cnt>=2, then it's pairwise coprime.
But careful: The condition for pairwise coprime is that for every prime p, at most one number is divisible by p. This method directly checks it.
But there is nuance: What if a number is 0? But Ai >=1. So fine.
However, we must also consider the case where a number is 1. 1 is not divisible by any prime, so it doesn't affect cnt.
Now, the complexity: we need to generate primes up to maxA. We can do a simple sieve to mark is_prime (boolean) array of size maxA+1. That is O(maxA log log maxA). Then iterate over primes and multiples. The total multiples sum is as above about 2.9e6, which is fine.
But we need to be careful about memory: is_prime array of booleans as Python list of bools (which are actually ints) takes ~1e6 * 28 bytes if using list of bool? Actually bool is a subclass of int, each element is a Python object (True/False) which are singletons, but the list stores references to these singletons, so 8 bytes per entry (pointer). So 8 MB. Alternatively, we could use bytearray for is_prime to save memory. But it's okay.
But we can even avoid storing is_prime explicitly: we can do a sieve to get list of primes directly, and then use it for the multiples loop. To find primes, we can use simple sieve to generate list of primes. Then for each prime, loop multiples. That's fine.
Now, but we also need to handle case where N is up to 1e6, maxA may be up to 1e6. freq array size maxA+1 is up to 1e6+1, that's okay.
Now, we also need to consider the scenario where there is a prime p > maxA? Not possible because all numbers ≤ maxA. So only primes up to maxA matter.
Thus the frequency method seems simpler and maybe faster because it avoids per-number factorization loops which may involve while loops and modulo operations per factor. However, factorization approach per number might also be okay.
Let's estimate factorization approach: For each number, we do while x>1: p=spf[x]; if p!=prev: cnt[p]++. Then while x%p==0: x//=p. The inner while loops for repeated factors may cause additional divisions. But overall total divisions roughly total number of prime factors (with multiplicity) across all numbers. In worst-case, each number could be up to 1e6, having up to ~7 distinct primes but total prime factors with multiplicity can be larger. For example, 2^20 is > 1e6, but maximum exponent? For 2^19=524288, 2^20=1048576 > 1e6, so maximum exponent for 2 is 19. But distinct primes limited, but the inner while loop to divide out all powers of a prime will perform as many divisions as the exponent. So total operations could be sum of exponents across all numbers, which could be as high as N * log2(maxA) if all numbers are powers of 2. That's up to 1e6 * 19 ≈ 19 million, still acceptable. Actually worst-case: all numbers are 2^19 = 524288, each has exponent 19, and distinct prime only one, but we will do the while loop: while x%2==0: x//=2, that's 19 divisions per number, total 19 million divisions, plus a bit. That's okay in Python? 19 million simple integer divisions might be okay (maybe 0.2 sec per 10 million? Actually Python integer division is relatively fast, but 19 million might be a few hundred milliseconds, likely fine). Also we need to consider that we also compute overall gcd, which uses math.gcd (C implementation) fast.
But the frequency method avoids per-number divisions entirely after building freq array. The loops for multiples involve integer addition and array accesses. That might be even faster.
However, the frequency method has to loop over all primes and their multiples, which is about 2.9e6 iterations, each adding freq[multiple] to a counter. That's definitely fast. Plus building freq array O(N). So overall O(maxA log log maxA + N) ~ 1e6 * small. That's great.
But there's a subtle issue: In the frequency method, if a number has multiple prime factors, it will be counted for each prime. That's fine because we only care if any prime has count >=2. If a number is, say, 6 (2*3), then for p=2, freq[6] adds to cnt, for p=3 also. So that's okay.
But we must be careful about the case where there is only one number overall? But N>=2.
Now, potential problem: The frequency method counts numbers by their exact value. Suppose we have numbers 4 and 6. freq[4]=1, freq[6]=1. For p=2, multiples: 2,4,6,8,... we add freq[4] and freq[6] => cnt=2 => condition triggered, correct.
What about when same number appears multiple times? Suppose we have two 6's: freq[6]=2. For p=2, multiple 6 gives freq[6]=2 => cnt=2 => triggered. Good.
Edge case: If there is a number that is 1, freq[1] is counted but not in multiples of any p>=2. So safe.
Now, one more nuance: The pairwise condition requires that for all i<j, gcd(A_i, A_j) = 1. If all numbers are 1, it's pairwise. Our frequency method: no prime p has total >=2, so it will deem pairwise. Good.
But is it possible that there is a prime p such that total divisible numbers >= 2 but still the numbers are pairwise coprime? Consider p=2: if we have numbers 2 and 4? gcd(2,4)=2 not 1. So no. If we have numbers 2 and 3? 2 divisible by 2, 3 not, total for p=2 is 1, fine. So condition is both necessary and sufficient.
Thus frequency method works.
Now, overall gcd check: we must compute gcd of all numbers. This is O(N) using math.gcd.
If overall gcd !=1, we output "not coprime" and exit; no need for pairwise check.
Thus algorithm steps:
-
Read N and list A.
-
Compute g = 0; for a in A: g = math.gcd(g, a). If g != 1: print("not coprime") and exit.
-
Else, find maxA = max(A).
-
Build freq array of size maxA+1 with zeros. For a in A: freq[a] += 1.
-
Generate primes up to maxA using sieve (e.g., is_prime array or directly list primes).
Approach: use a boolean list "is_prime" of length maxA+1 initialized to True for indices >=2. Then for i from 2 to sqrt(maxA): if is_prime[i]: for j from i*i to maxA step i: is_prime[j]=False.
Then iterate i from 2 to maxA: if is_prime[i]: then check.
Alternatively, we can skip building is_prime and generate primes list via sieve.
-
For each prime p from 2 to maxA:
cnt = 0
for multiple in range(p, maxA+1, p):
cnt += freq[multiple]
if cnt >= 2:
print("setwise coprime")
return
After loop, print("pairwise coprime").
Potential improvements: We can break early when we find any prime with count >=2. Also, we can limit p to maxA.
Now, we must consider the case where there is a number that is 0? Not allowed.
Now, test examples:
Example1: 3,4,5. g=1. freq: 3,4,5. maxA=5. primes: 2,3,5. For p=2: multiples 2,4 => freq[4]=1 => cnt=1. p=3: multiples 3 => cnt=1. p=5: multiples 5 => cnt=1. So no cnt>=2 -> pairwise.
Example2: 6,10,15. g=gcd(6,10)=2, gcd(2,15)=1? Actually gcd(6,10)=2; gcd(2,15)=1 => overall gcd=1. freq: 6,10,15. maxA=15. primes: 2,3,5,7,11,13. p=2: multiples 2,4,6,8,10,12,14 -> freq[6]=1, freq[10]=1 => cnt=2 -> setwise. correct.
Example3: 6,10,16. g=gcd(6,10)=2; gcd(2,16)=2 => overall gcd=2 !=1 -> not coprime. Output not coprime. correct.
Now, edge case: N=2, A=[2,3] -> g=1, freq:2,3; p=2: cnt=1; p=3: cnt=1 -> pairwise.
Edge: [2,4] -> g=2 -> not coprime.
Edge: [1,1] -> g=1; freq[1]=2; primes: no prime gets count >=2 -> pairwise.
Now, there is a nuance: The definition of pairwise coprime requires that for every pair (i,j), gcd(A_i,A_j)=1. If all numbers are 1, indeed gcd(1,1)=1. So pairwise holds.
Now, about the frequency method: what about numbers that are equal to a prime that is larger than sqrt(maxA)? For example, maxA=1e6, prime 999983 (largest prime less than 1e6). The loop for multiples of p: p, 2p, ... up to maxA. Since p> maxA/2, the only multiples are p itself (since 2p > maxA). So we check freq[p]. So fine.
Now, we need to be careful about the time for generating primes. Standard sieve O(maxA log log maxA) fine.
Now, also consider memory: freq array could be list of ints of size maxA+1. With N=1e6, maxA up to 1e6, that's 1e6+1 ints. As earlier, the list of ints of length 1e6 uses about 8 MB for references and for non-zero entries maybe allocate ints. But we will only store small counts (0,1,...). However, Python list of ints initially all zeros: [0]*(maxA+1) creates a list where each element is the same integer object 0. That's fine; each reference points to the same small int 0. When we increment an element, e.g., freq[a] += 1, Python will create a new int for that slot (1) and assign it. So we will have at most N distinct slots modified (since each A_i yields one slot). So at most 1e6 slots will have non-zero ints. The integer objects for counts are small (0- maybe up to N), but they will be separate objects. That's okay, memory maybe ~28 MB for the ints plus list overhead ~8 MB. Acceptable.
Now, we need to also consider the case where maxA is less than something, but still okay.
Now, the overall gcd step: We can compute using math.gcd. However, we must be careful that the numbers are up to 1e6, but N is up to 1e6, so gcd calculation is fine.
Now, there's one more nuance: The condition "pairwise coprime" means for every i<j, gcd(A_i, A_j) = 1. This is equivalent to for every prime p, at most one number is divisible by p. However, the frequency method using the count of numbers divisible by p counts the number of numbers that are multiples of p. But is it possible that two numbers are not coprime even though no prime divides both? That would be impossible because if gcd > 1, then there exists some prime dividing both. So it's necessary and sufficient.
Thus algorithm correct.
Now, we must think about potential performance pitfalls: The loops for primes and multiples might be heavy in Python if we use nested for loops with range increments. But 2.9e6 iterations is fine. However, we have to iterate over each prime and for each prime, iterate over multiples. The total number of multiples for all primes up to 1e6 is sum_{p <= maxA} floor(maxA/p). Let's compute approximate value: sum_{i=2}^{maxA} floor(maxA/i) for i prime? Actually for all numbers, sum_{i=1}^{N} floor(N/i) ≈ N log N. But only for primes it's less. But let's compute exact upper bound: For all numbers i from 2 to maxA, floor(maxA/i) is about maxA * (1/2 + 1/3 + ... + 1/maxA). The harmonic sum H_maxA ≈ ln(maxA)+γ ≈ 14.4. So sum over all numbers would be maxA * H_maxA ≈ 1e6 * 14.4 = 14.4e6. But we only sum over primes, which are a subset, so sum over primes <= sum over all numbers, but actually sum over primes of 1/p is much smaller. The sum of reciprocals of primes up to 1e6 is about 2.9. So sum_{p} floor(maxA/p) ≈ maxA * 2.9 ≈ 2.9e6. That's correct. So loops about 3 million, which is very fast.
But note: The loop for primes also needs to iterate over multiples and add freq[multiple]. That's 3 million additions. That's fine.
Now, we also need to generate primes list. Sieve up to 1e6 is about 1e6 operations for marking multiples, which is about 1e6 * (some constant). Actually standard sieve: for i in range(2, int(sqrt(maxA))+1): if is_prime[i]: for j in range(i*i, maxA+1, i): is_prime[j]=False. The inner loops total number of markings is about maxA * (1/2 + 1/3 + 1/5 + ...) but again approximated by maxA * log log maxA ≈ 1e6 * ~2.9 = 2.9e6? Actually sum of reciprocals of primes up to sqrt? No, marking multiples for each prime i from 2 to maxA? Standard sieve marks each composite once by its smallest prime factor, total marks ~ maxA log log maxA. For maxA=1e6, that's around 1e6 * (some small) maybe a few million. So fine.
Thus the frequency method should be efficient.
But there is a catch: The numbers can be up to 10^6, but N can be 10^6. The freq array size is 10^6+1, okay. But we also need is_prime of same size. That's also okay.
Now, we need to implement in Python.
Implementation details:
-
Use sys.stdin.buffer.read to read all input quickly.
-
Parse integers.
-
Compute overall gcd with math.gcd.
-
If overall_gcd != 1: print("not coprime") and exit.
-
else: Build freq array.
We need to know maxA to allocate freq and sieve. So we can find maxA from the list.
-
Build freq = [0]*(maxA+1). For each a in A: freq[a] += 1.
-
Generate primes using sieve:
is_prime = [True](maxA+1)
is_prime[0]=is_prime[1]=False
for i in range(2, int(maxA**0.5)+1):
if is_prime[i]:
for j in range(ii, maxA+1, i):
is_prime[j]=False
But careful: maxA can be 1, then loop range up to int(1**0.5)=1, so no iteration. But if maxA=1, then there are no primes >=2. But N>=2 and all numbers are 1? Then overall_gcd=1 and freq[1] maybe >0. Pairwise condition? Since all 1's, it's pairwise. The primes loop won't run, so we won't find any prime with cnt>=2, so we output pairwise. That's correct. So handle maxA=1 case.
Now, after generating is_prime, we iterate p from 2 to maxA:
for p in range(2, maxA+1):
if not is_prime[p]: continue
cnt = 0
for mul in range(p, maxA+1, p):
cnt += freq[mul]
if cnt >= 2:
print("setwise coprime")
return
print("pairwise coprime")
We need to be careful: When maxA is large, the inner loop for p small will have many iterations. But total is acceptable.
Potential micro-optimizations: we could break early from inner loop when cnt>=2, but we already do if cnt>=2 break out of loops.
We could also precompute list of primes and iterate over that list to avoid checking is_prime each time. That would be slightly faster.
So:
primes = []
is_prime = [True](maxA+1)
is_prime[0]=is_prime[1]=False
for i in range(2, maxA+1):
if is_prime[i]:
primes.append(i)
if ii <= maxA: # Actually we need to mark multiples
for j in range(i*i, maxA+1, i):
is_prime[j]=False
But note: If we use this method, we need to mark multiples for i up to sqrt(maxA) only to be efficient. Typically we do:
limit = int(maxA**0.5)
is_prime = [True](maxA+1)
is_prime[0]=is_prime[1]=False
for i in range(2, limit+1):
if is_prime[i]:
for j in range(ii, maxA+1, i):
is_prime[j]=False
primes = [i for i in range(2, maxA+1) if is_prime[i]]
This avoids marking for i > limit, but we still need to identify primes after limit.
Now, memory: is_prime as list of bool maybe using bytearray for better memory and speed. But it's okay.
Now, we also need to consider the case where maxA is up to 10^6, but N may be smaller. It's fine.
Now, edge case: Suppose there is a number that is 0? Not possible.
Now, test with sample.
Now, consider potential overflow: None.
Now, let's think about time: The sieve marking loops for i up to sqrt(maxA) (1000) and for each prime, multiples from i*i up to 1e6. The number of markings is roughly maxA * (1/2 + 1/3 + 1/5 + 1/7 + ... up to 1000). That's about 1e6 * (sum of reciprocals of primes up to 1000). sum 1/p for p <= 1000 approx maybe ~2.2? Actually sum_{p <= 1000} 1/p ~ log log 1000 + M ≈ log(6.9)+0.26? log log 1000 = ln(ln(1000))? ln(1000)~6.9, ln(6.9)1.93, plus M0.2619, total ~2.19. So markings about 2.2e6. Good.
The prime iteration for multiples: sum_{p <= maxA} floor(maxA/p) ≈ 2.9e6. So total operations ~ 5e6 plus overhead, fine.
Now, we need to compare with factorization method. Factorization method would require for each number up to 1e6, a loop over its prime factors. That's about up to 7 steps per number, so about 7e6 operations. But each step includes while loops and modulo operations. Might be similar. But the frequency method might be simpler because it uses fewer per-number operations (just increment freq array) and then a single pass over primes and multiples. It also avoids the need to compute SPF and do division operations for each number. So I think the frequency method is better.
But there is one nuance: The frequency method relies on iterating over all multiples of each prime. That loop may be slower in Python if done with Python-level loops. However, 3 million iterations is not many. But the nested loops: for each prime, inner loop over multiples. If we have 78k primes, many of them are large and have very few multiples (like only one). For each prime we do at least one iteration (the multiple = p). So we will have at least number of primes iterations, i.e., about 78k, plus the inner loops for small primes. So total loop overhead is about sum over primes of (number of multiples). But the overhead of the outer for loop for each prime (78k) is fine.
But maybe we can further optimize by using a "cnt" array for prime multiplicities using a sieve-like approach: For each number a, we could increment a frequency array, then we can compute for each prime the total count of numbers divisible by p by summing freq of multiples. That's exactly what we will do.
Potential memory: freq array of ints, is_prime array of bools.
Alternatively, we can avoid generating is_prime and just iterate p from 2 to maxA, but for composite p, we still would need to compute the sum over multiples, but that would be redundant because if p is composite, the condition that "at most one number divisible by p" is not necessary for pairwise coprime? Wait, if p is composite, the condition for pairwise coprime requires that for every prime, no two numbers share that prime. If two numbers share a composite factor, that implies they share a prime factor as well. So checking only primes is sufficient. Checking composites as well would be redundant and could cause extra work (but might also detect a collision earlier? Not necessary). So we need to check only primes.
But we could also do: For each prime p, compute total. So we need list of primes.
Now, one more thing: The overall gcd computed first may be 1 but the numbers might not be pairwise coprime. But we need to output "setwise coprime" only if overall gcd=1 and not pairwise. So our method: compute overall gcd, if !=1 output not coprime; else compute pairwise using frequency method: if we find any prime with count >=2, we output setwise coprime, else pairwise.
Now, check with example: [2,3,6] -> gcd(2,3,6) = 1? gcd(2,3)=1, gcd(1,6)=1 => overall gcd=1. Pairwise: 2 and 6 share 2, 3 and 6 share 3, so not pairwise. So should be setwise. Frequency: primes: 2: multiples 2,4,6 -> freq[2]=1, freq[6]=1 => cnt=2 => setwise. Good.
Now, consider [1,2,3] -> overall gcd=1, prime 2 cnt=1, 3 cnt=1, so pairwise.
Now, consider [1,1,2] -> overall gcd=1? gcd(1,1)=1, gcd(1,2)=1 -> overall=1. Pairwise: 1 and 1 okay, 1 and 2 okay, but two 1's okay. So pairwise? Actually need to check 2 and 2? There's only one 2. So pairwise condition holds. Frequency: prime 2 cnt = freq[2] = 1, so pairwise. Good.
Now, consider [2,9,25] -> gcd=1. primes: 2 cnt=1, 3 cnt? 9 divisible by 3, 25 not, so cnt 3 =1, 5 cnt=1. So pairwise? But check pairwise: gcd(2,9)=1, gcd(2,25)=1, gcd(9,25)=1. Indeed pairwise. So correct.
Now, consider [6,10,15] as before: setwise.
Now, consider [2,3,5,6] -> overall gcd=1? gcd(2,3)=1, gcd(1,5)=1, gcd(1,6)=1 =>1. But pairwise? Check 6 with 2: gcd=2 >1 so not pairwise. So setwise. Frequency: prime 2: multiples 2,4,6 -> freq[2]=1, freq[6]=1 => cnt=2 => setwise.
Now, all good.
Now, we should confirm that the condition for pairwise coprime using prime divisibility is exactly equivalent: if no prime divides two numbers, then for any two numbers, they share no prime factor, so gcd=1. Conversely, if gcd>1, they share some prime. So correct.
Now, about potential overflow: None.
Now, let's consider the case when maxA is large (1e6) and N is large (1e6). The freq array will have many zeros. That's fine.
Now, we must also consider the scenario where there is a number that is 0? Not allowed.
Now, implementation details:
We'll read input as:
import sys, math
def main():
data = sys.stdin.buffer.read().split()
N = int(data[0])
A = list(map(int, data[1:]))
# compute gcd
g = 0
for a in A:
g = math.gcd(g, a)
if g == 1: # maybe early break? But we need gcd of all, cannot break early because gcd could become 1 but later numbers might bring it back to >1? Actually if gcd becomes 1, then gcd(1, any) =1, so overall gcd will remain 1. So if at any point g becomes 1, we can break? But careful: gcd(0, a) = a; after first number, g = a. Then subsequent: if g becomes 1, then indeed any further gcd with any number will stay 1 because gcd(1, x) = 1. So we can break early when g == 1. This could speed up, but not necessary.
# However, we need to compute overall gcd correctly. If we break early at g==1, the final g is 1 regardless of remaining numbers. So we can break.
if g == 1:
# but we still need to iterate through rest? Actually we can break out of loop and ignore the rest because gcd with 1 stays 1.
# But we still need to process the rest for freq? We'll need freq for pairwise check. So we can't break if we need to build freq. So we need to read all numbers anyway to build freq. So we can't break reading numbers. But we can compute gcd and continue; breaking early doesn't save much because we already have all numbers in list.
# So just compute g fully.
if g != 1:
print("not coprime")
return
maxA = max(A)
freq = [0]*(maxA+1)
for a in A:
freq[a] += 1
# sieve to get primes up to maxA
if maxA < 2:
# no primes
print("pairwise coprime")
return
is_prime = [True]*(maxA+1)
is_prime[0] = is_prime[1] = False
import math
limit = int(math.isqrt(maxA))
for i in range(2, limit+1):
if is_prime[i]:
step = i
start = i*i
for j in range(start, maxA+1, step):
is_prime[j] = False
# iterate primes
for p in range(2, maxA+1):
if not is_prime[p]:
continue
cnt = 0
for mul in range(p, maxA+1, p):
cnt += freq[mul]
if cnt >= 2:
print("setwise coprime")
return
print("pairwise coprime")
But we can also combine the marking of primes and the check into one? Not needed.
Potential optimization: Instead of constructing is_prime and then iterating over all numbers to check is_prime, we can directly build a list of primes while sieving. E.g.:
primes = []
is_prime = bytearray(b'\x01')(maxA+1) # using bytearray for memory efficiency
is_prime[0] = is_prime[1] = 0
for i in range(2, maxA+1):
if is_prime[i]:
primes.append(i)
if ii <= maxA:
for j in range(i*i, maxA+1, i):
is_prime[j] = 0
But this marks multiples for all i up to maxA, which is less efficient because for i > sqrt(maxA) we still iterate i but we don't need to mark multiples (ii > maxA). The condition ii <= maxA ensures we only mark for i <= sqrt. Then after the loop, the numbers i > sqrt that remain is_prime[i] true are primes. So we can do:
limit = int(maxA**0.5)
is_prime = [True](maxA+1)
is_prime[0]=is_prime[1]=False
for i in range(2, limit+1):
if is_prime[i]:
for j in range(ii, maxA+1, i):
is_prime[j] = False
primes = [i for i in range(2, maxA+1) if is_prime[i]]
That's fine.
But we could also generate primes via simple sieve and then use that list for loop. That might be faster because we avoid checking is_prime for each number from 2 to maxA (which is 1e6, which is okay). But we could also iterate over primes directly: for p in primes: check multiples. So we generate primes list.
Let's generate primes list.
Implementation:
def get_primes(n):
if n < 2:
return []
is_prime = [True](n+1)
is_prime[0]=is_prime[1]=False
for i in range(2, int(n**0.5)+1):
if is_prime[i]:
step = i
start = ii
for j in range(start, n+1, step):
is_prime[j] = False
primes = [i for i, val in enumerate(is_prime) if val]
return primes
But building primes list using list comprehension over 1e6 elements is fine.
Alternatively, we could use bytearray for is_prime to save memory and maybe faster due to less overhead? Actually Python list of bools uses references, bytearray uses bytes. That might be more memory efficient and faster for marking. But okay.
Let's test with Python mental.
Now, consider potential issues: The numbers are up to 1e6, but N could be 1e6. The array A will have 1e6 integers. Reading them all at once is okay.
Now, compute gcd: using math.gcd in loop.
Now, after building freq, we loop primes and multiples. But note that for p large (close to maxA), the inner loop range(p, maxA+1, p) will have only one iteration (p itself). That's fine.
Now, we must be careful about time: The nested loops could be heavy but as reasoned it's fine.
But what if maxA is 1e6 and we have many primes? For p=2, we iterate about 500k times. For p=3, about 333k, etc. Actually p=2: multiples from 2 to 1e6 step 2 -> about 500,000 iterations. p=3: about 333,333, p=5: 200,000, p=7: 142,857, etc. Summation of floor(1e6/p) for primes p approximates 1e6 * sum_{p} 1/p. But sum_{p <= 1e6} 1/p ≈ 2.9, so total about 2.9e6. However, floor(1e6/2) = 500k, floor(1e6/3)=333k, floor(1e6/5)=200k, floor(1e6/7)=142857, floor(1e6/11)=90909, ... the sum of these for primes is around 2.9e6. So the inner loop total iterations ~ 2.9e6. That's manageable.
But there is also the overhead of the outer loop over primes (78k). So total loop operations ~ 3e6 + 78k = ~3.1e6. That's fine.
Now, we also need to allocate freq array. We'll need to allocate size maxA+1. If maxA=1e6, that's 1,000,001 entries. That's okay.
Now, there is one more nuance: The condition of pairwise coprime is that for every prime p, the count of numbers divisible by p is at most 1. But if we have a number that is 0? Not applicable.
But what about the case where a number is 1? It doesn't affect.
Now, consider if all numbers are 1's. Then freq[1]=N, but primes loops never get cnt>=2 because 1 not in any multiple. So pairwise.
Now, consider if there is a number >1 but its prime factor is p and another number also has p, cnt becomes 2. So setwise.
Now, what if there is a prime p such that p > maxA? Not possible because numbers ≤ maxA.
Now, potential micro-optimizations: Instead of iterating over all primes and their multiples, we could compute the "multiplicity" of each prime by using a technique similar to sieve of counting multiples: For each value v from 2 to maxA, if freq[v] > 0, we could factorize v and increment cnt[p] for each distinct prime p dividing v. That's the factorization method. That may be simpler to code and also efficient. But we already have the frequency method.
But we must consider the case where maxA is relatively small but N large. Both fine.
Now, I'll code using the frequency method.
Edge Cases:
-
N=2, A=[1000000, 999983] (both large). overall gcd? 1000000 = 2^65^6? Actually 1000000=2^65^6, 999983 is prime? Actually 999983 is prime? Might be. gcd=1. Pairwise? Since no common prime, pairwise. Our frequency: freq[1000000]=1, freq[999983]=1. For prime 2: multiples include 1000000? 1000000%2=0, yes. So for p=2, cnt includes freq[1000000] (1). For p=5: includes freq[1000000] (1). For p=999983: includes freq[999983] (1). So all cnt=1. So pairwise.
-
N=2, A=[1000000, 500000]. 500000= 500000= 2^? Actually 500000= 2^5 * 5^6? Actually 500000 = 5*100000? Let's compute: 1000000/2 = 500000, so both share factor 2. overall gcd not 1? gcd(1000000,500000)=500000 !=1 so not coprime. So algorithm stops early.
Now, I think it's correct.
Now, let's also consider a scenario where overall gcd = 1, but there is a prime p with cnt >= 2? That means not pairwise, so setwise.
Now, consider scenario where overall gcd = 1 and there is no prime with cnt >= 2. That's pairwise.
Now, I'll produce final code.
But wait, there is a subtlety: The condition "pairwise coprime" is equivalent to that for every prime p, at most one number is divisible by p. However, what about the case where a number is 0? Not allowed. So it's fine.
But there is another nuance: If we have two numbers that are not coprime because they share a composite factor but no prime factor? That's impossible: any composite factor has prime factors.
Thus good.
Now, confirm with some tricky cases:
Case: A = [6, 10, 15] -> overall gcd=1, p=2 cnt=2 -> setwise.
Case: A = [2,3,25] -> overall gcd=1, p=2 cnt=1, p=3 cnt=1, p=5 cnt=1 -> pairwise