Problem:


Score : 500 points

Problem Statement

We have N integers. The i-th number is A_i.

\{A_i\} is said to be pairwise coprime when GCD(A_i,A_j)=1 holds for every pair (i, j) such that 1\leq i < j \leq N.

\{A_i\} is said to be setwise coprime when \{A_i\} is not pairwise coprime but GCD(A_1,\ldots,A_N)=1.

Determine if \{A_i\} is pairwise coprime, setwise coprime, or neither.

Here, GCD(\ldots) denotes greatest common divisor.

Constraints

2 \leq N \leq 10^6

1 \leq A_i\leq 10^6

Input

Input is given from Standard Input in the following format:

N
A_1 \ldots A_N

Output

If \{A_i\} is pairwise coprime, print pairwise coprime; if \{A_i\} is setwise coprime, print setwise coprime; if neither, print not coprime.

Sample Input 1

3
3 4 5

Sample Output 1

pairwise coprime

GCD(3,4)=GCD(3,5)=GCD(4,5)=1, so they are pairwise coprime.

Sample Input 2

3
6 10 15

Sample Output 2

setwise coprime

Since GCD(6,10)=2, they are not pairwise coprime. However, since GCD(6,10,15)=1, they are setwise coprime.

Sample Input 3

3
6 10 16

Sample Output 3

not coprime

GCD(6,10,16)=2, so they are neither pairwise coprime nor setwise coprime.



Sample input:
3
3 4 5


Sample output:
pairwise coprime

Submission status: Runtime Error

Solution code:
# ===============================================================================================
# importing some useful libraries.
from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from itertools import *
import bisect
from heapq import *
from math import *
from copy import *
from collections import deque
from collections import Counter as counter  # Counter(list)  return a dict with {key: count}
from itertools import combinations as comb  # if a = [1,2,3] then print(list(comb(a,2))) -----> [(1, 2), (1, 3), (2, 3)]
from itertools import permutations as permutate
from bisect import bisect_left as bl
# If the element is already present in the list,

# the left most position where element has to be inserted is returned.
from bisect import bisect_right as br
from bisect import bisect

# If the element is already present in the list,
# the right most position where element has to be inserted is returned

# ==============================================================================================
# fast I/O region

BUFSIZE = 8192


class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None


    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")


def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()


if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

# inp = lambda: sys.stdin.readline().rstrip("\r\n")

# ===============================================================================================
### START ITERATE RECURSION ###
from types import GeneratorType


def iterative(f, stack=[]):
    def wrapped_func(*args, **kwargs):
        if stack: return f(*args, **kwargs)
        to = f(*args, **kwargs)
        while True:
            if type(to) is GeneratorType:
                stack.append(to)
                to = next(to)
                continue
            stack.pop()
            if not stack: break
            to = stack[-1].send(to)
        return to

    return wrapped_func


#### END ITERATE RECURSION ####

# ===============================================================================================
# some shortcuts

mod = 1000000007


def inp(): return sys.stdin.readline().rstrip("\r\n")  # for fast input

def out(var): sys.stdout.write(str(var))  # for fast output, always take string

def lis(): return list(map(int, inp().split()))

def stringlis(): return list(map(str, inp().split()))

def sep(): return map(int, inp().split())

def strsep(): return map(str, inp().split())


def zerolist(n): return [0] * n

def nextline(): out("\n")  # as stdout.write always print sring.

def testcase(t):
    for p in range(t):
        solve()

def printlist(a):
    for p in range(0, len(a)):
        out(str(a[p]) + ' ')

def lcm(a, b): return (a * b) // gcd(a, b)

def power(x, y, p):
    res = 1  # Initialize result
    x = x % p  # Update x if it is more , than or equal to p
    if (x == 0):
        return 0
    while (y > 0):
        if ((y & 1) == 1):  # If y is odd, multiply, x with result
            res = (res * x) % p

        y = y >> 1  # y = y/2
        x = (x * x) % p
    return res

def ncr(n, r): return factorial(n) // (factorial(r) * factorial(max(n - r, 1)))

def isPrime(n):
    if (n <= 1): return False
    if (n <= 3): return True
    if (n % 2 == 0 or n % 3 == 0): return False
    i = 5
    while (i * i <= n):
        if (n % i == 0 or n % (i + 2) == 0):
            return False
        i = i + 6
    return True

import random

def primesbelow(N):
    # http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188
    #""" Input N>=6, Returns a list of primes, 2 <= p < N """
    correction = N % 6 > 1
    N = {0:N, 1:N-1, 2:N+4, 3:N+3, 4:N+2, 5:N+1}[N%6]
    sieve = [True] * (N // 3)
    sieve[0] = False
    for i in range(int(N ** .5) // 3 + 1):
        if sieve[i]:
            k = (3 * i + 1) | 1
            sieve[k*k // 3::2*k] = [False] * ((N//6 - (k*k)//6 - 1)//k + 1)
            sieve[(k*k + 4*k - 2*k*(i%2)) // 3::2*k] = [False] * ((N // 6 - (k*k + 4*k - 2*k*(i%2))//6 - 1) // k + 1)
    return [2, 3] + [(3 * i + 1) | 1 for i in range(1, N//3 - correction) if sieve[i]]

smallprimeset = set(primesbelow(100000))
_smallprimeset = 100000
def isprime(n, precision=7):
    # http://en.wikipedia.org/wiki/Miller-Rabin_primality_test#Algorithm_and_running_time
    if n < 1:
        raise ValueError("Out of bounds, first argument must be > 0")
    elif n <= 3:
        return n >= 2
    elif n % 2 == 0:
        return False
    elif n < _smallprimeset:
        return n in smallprimeset


    d = n - 1
    s = 0
    while d % 2 == 0:
        d //= 2
        s += 1

    for repeat in range(precision):
        a = random.randrange(2, n - 2)
        x = pow(a, d, n)

        if x == 1 or x == n - 1: continue

        for r in range(s - 1):
            x = pow(x, 2, n)
            if x == 1: return False
            if x == n - 1: break
        else: return False

    return True

# https://comeoncodeon.wordpress.com/2010/09/18/pollard-rho-brent-integer-factorization/
def pollard_brent(n):
    if n % 2 == 0: return 2
    if n % 3 == 0: return 3

    y, c, m = random.randint(1, n-1), random.randint(1, n-1), random.randint(1, n-1)
    g, r, q = 1, 1, 1
    while g == 1:
        x = y
        for i in range(r):
            y = (pow(y, 2, n) + c) % n

        k = 0
        while k < r and g==1:
            ys = y
            for i in range(min(m, r-k)):
                y = (pow(y, 2, n) + c) % n
                q = q * abs(x-y) % n
            g = gcd(q, n)
            k += m
        r *= 2
    if g == n:
        while True:
            ys = (pow(ys, 2, n) + c) % n
            g = gcd(abs(x - ys), n)
            if g > 1:
                break

    return g

smallprimes = primesbelow(1000) # might seem low, but 1000*1000 = 1000000, so this will fully factor every composite < 1000000
def primefactors(n, sort=False):
    factors = []

    for checker in smallprimes:
        while n % checker == 0:
            factors.append(checker)
            n //= checker
        if checker > n: break

    if n < 2: return factors

    while n > 1:
        if isprime(n):
            factors.append(n)
            break
        factor = pollard_brent(n) # trial division did not fully factor, switch to pollard-brent
        factors.extend(primefactors(factor)) # recurse to factor the not necessarily prime factor returned by pollard-brent
        n //= factor

    if sort: factors.sort()

    return factors

def factorization(n):
    factors = {}
    for p1 in primefactors(n):
        try:
            factors[p1] += 1
        except KeyError:
            factors[p1] = 1
    return factors


from functools import reduce

n=int(inp())
ar=lis()
if n<79000:
    temp=set()
    temps=0
    t=1
    for i in ar:
        k=factorization(i)
        s=set(k.keys())
        l=len(s)
        temp=temp.union(s)
        if len(temp)!=l+temps:
            t=-1
            break
        temps+=l
    if t==1:
        print("pairwise coprime")
    else:
        k=reduce(gcd,ar)
        if k==1:
            print("setwise coprime")
        else:
            print("not coprime")
else:
    k = reduce(gcd, ar)
    if k == 1:
        print("setwise coprime")
    else:
        print("not coprime")

Submission status: Runtime Error

Solution code:
import math
N = int(input())
A = list(map(int,input().split()))
ls = []
now = A[0]
for i in range(1,N):
    ls.append(math.gcd(now,A[i]))
    now = math.gcd(now,A[i])
if ls.count(1) == N-1:
    print("pairwise coprime")
else:
    if ls[N-1] == 1:
        print("setwise coprime")
    else:
        print("not coprime")

Submission status: Runtime Error

Solution code:
def eratosthenes(n):
    prime = []
    limit = n**0.5
    numbers = [i for i in range(2,n+1)]
    while True:
        p = numbers[0]
        if limit <= p:
            return prime + numbers
        prime.append(p)
        numbers = [i for i in numbers if i%p != 0]
    return prime

def eratosthenes(n):
    prime = []
    limit = n**0.5
    numbers = [i for i in range(2,n+1)]
    while True:
        p = numbers[0]
        if limit <= p:
            return prime + numbers
        prime.append(p)
        numbers = [i for i in numbers if i%p != 0]
    return prime

pl = eratosthenes(10**6)
pd = {}
for p in pl:
    pd[p] = 0

N = int(input())
A = list(map(int,input().split()))

A.sort()
d = {}
ans = 0
for i in range(N):
    if A[i] not in pd:
        primes = prime_decomposition(A[i])
        for p in primes:
            if p not in d:
                d[p] = 0
            else:
                ans = 1

if ans == 0:
    print('pairwise coprime')
else:
    def gcd(a, b):
    	while b:
    		a, b = b, a % b
    	return a
    a = A[0]
    for i in range(N):
        a = gcd(a,A[i])
    if a==1:
        print('setwise coprime')
    else:
        print('not coprime')

Submission status: Runtime Error

Solution code:
mod=10**9+7
n=int(input())
a=list(map(int,input().split()))
a.sort()
g=a[0]
for i in a:
    g=math.gcd(g,i)
d=dict()
for i in a:
    if i%2==0:
        if 2 in d:
            d[2]+=1
        else:
            d[2]=1
    while i%2==0:
        i//=2
    for j in range (3, int(math.sqrt(i))+1 ):
        if i%j==0:
            if j in d:
                d[j]+=1
            else:
                d[j]=1
            while i%j==0:
                i//=j
    if i>2:
        if i in d:
            d[i]+=1
        else:
            d[i]=1
c=1
for i in d:
    c=max(c,d[i])
if c==1:
    print("pairwise coprime")
elif g==1:
    print("setwise coprime")
else:
    print("not coprime")

Submission status: Runtime Error

Solution code:
n = int(input())
a = list(map(int,input().split()))

import math
from functools import reduce

def gcd(*numbers):
    return reduce(math.gcd, numbers)

def gcd_list(numbers):
    return reduce(math.gcd, numbers)

for i in range(n-1):
  for j in range(i+1:n):
    if gcd(a[i],a[j]) != 1:
      p = 1
      break
    else:
      p = 0
if p = 1:
  if gcd_list(a) == 1:
    p = 2
  else:
    p = 3

if p == 1:
  print("pairwise coprime")
elif p == 2:
  print("setwise coprime")
else:
  print("not coprime")

Submission status: Runtime Error

Solution code:

import math
def factorize(n):
	result = set()
	sqrt = math.floor(math.sqrt(n))
	i = 2
	while i <= sqrt:
		if n % i == 0:
			result.add(i)
			n //= i
			sqrt = math.floor(math.sqrt(n))
		else:
			i += 1
	if n > 1:
		result.add(n)
	return result

N = int(input())
A_list = list(map(int, input().split()))

m = max(A_list)

prime_flag = [True] * (m + 1)
prime_flag[1] = False
prime_table = {}

for i in range(2, m + 1):
	if prime_flag[i]:
		prime_table[i] = len(prime_table)
		for j in range(i * 2, m + 1, i):
			prime_flag[j] = False

#print(prime_table)
table = [0] * len(prime_table)

for A in A_list:
	factors = factorize(A)
	for f in factors:
		table[prime_table[f]] += 1

c = max(table)

if c == 1:
	print("pairwise coprime")
elif c == N:
	print("not coprime")
else:
	print("setwise coprime")

Submission status: Runtime Error

Solution code:
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


n = int(input())
a = list(map(int, input().split()))
def hurui(n):
    """n以下の素数のリストを返す
    """
    l = list(range(2,n+1))
    p = 2
    i = 0
    while True:
        l = [item for item in l if item==p or item%p!=0]
        i += 1
        p = l[i]
        if p*p>n:
            break
    return l
l = hurui(max(a)+1)
b = [[0]*len(l) for _ in range(n)]
def gcd(a, b):
    while b:
        a, b = b, a%b
    return a

for i in range(n):
    for j in range(len(l)):
        val = a[i]
        v = 0
        while val%l[j]==0:
            val //= l[j]
            v += 1
        b[i][j] = v
done = False
for j in range(len(l)):
    if sum((b[i][j]>0) for i in range(n))>=2:
        g = a[0]
        for i in range(1,n):
            g = gcd(g, a[i])
            if g==1:
                print("setwise coprime")
                done = True
                break
        else:
            print("not coprime")
            done = True
    if done:
        break
else:
    print("pairwise coprime")

Submission status: Runtime Error

Solution code:
def factorize(x):
    p = 2
    f = {}
    while x*x>=p:
        if x%p==0: f[p]=0
        while x%p==0:
            f[p]+=1
            x//=p
        p+=1
    if x>1: f[x]=1
    return f

N = int(input())
A = list(map(int, input().split()))

F = {}

for a in A:
    for f in set(factorize(a)):
        if f not in F: F[f] = 0
        F[f] += 1

m = max(F.values())
if m<=1:
    print('pairwise coprime')
elif m<N:
    print('setwise coprime')
else:
    print('not coprime')

Submission status: Runtime Error

Solution code:
N=int(input())
ls=[int(s) for s in input().split()]
M=max(ls)
#素数のリスト作成
prime=[1 for i in range(M+1)]
prime[0]=0
prime[1]=0
primels=[]
primedic={}
for i in range(2,M+1):
  if prime[i]==1:
    primels.append(i)
    primedic[i]=0
    a=1
    while a*i<=M:
      prime[a*i]=0
      a+=1

for e in ls:
  for p in primels:
    if e%p==0:
      primedic[p]+=1
      while e%p==0:
        e//=p
    if e==1:
      break
    
A=max(primedic.values())
if A==len(ls):
  print('not coprime')
elif A>1:
  print('setwise coprime')
else:
  print('pairwise coprime')

Submission status: Runtime Error

Solution code:
from itertools import groupby

def fast_prime_factorization_many(lst):
    # 素因数分解（ロー法、複数）
    from subprocess import Popen, PIPE
    res = Popen(["factor"] + list(map(str, lst)), stdout=PIPE).communicate()[0].split(b"\n")[:-1]
    return [list(map(int, r.split()[1:])) for r in res]

def main():
    N = int(input())
    A = list(map(int, input().split()))
    Factors = fast_prime_factorization_many(A)
    factors = Factors[0]
    st0 = set(factors)  # 0 になれば setwize
    st1 = set(factors)  # 重複しなければ pairwise
    pairwise = True
    for factors in Factors[1:]:
        for f, _ in groupby(factors):
            if f in st1:
                pairwise = False
            else:
                st1.add(f)
            if f in st0:
                st0.remove(f)
    if pairwise:
        print("pairwise coprime")
    elif not st0:
        print("setwise coprime")
    else:
        print("not coprime")

main()

Submission status: Runtime Error

Solution code:
from math import gcd
from functools import reduce
from collections import Counter
from itertools import chain


# 素因数分解
def prime_factors(n):
    i = 2
    while i * i <= n:
        if n % i:
            i += 1
        else:
            n //= i
            yield i
    if n > 1:
        yield n


def solve(A):
    d = reduce(gcd, A)
    if d != 1:
        return 'not coprime'

    c = Counter(chain.from_iterable(set(prime_factors(a)) for a in A))
    if max(c.values()) > 1:
        return 'setwise prime'
    else:
        return 'pairwise prime'


if __name__ == '__main__':
    N = int(input())
    A = list(map(int,input().split()))

    print(solve(A))

Submission status: Runtime Error

Solution code:
from sys import exit
from math import gcd
n = int(input())
a = list(map(int, input().split()))
g = gcd(a[0], a[1])
for i in range(2, n):
	g = gcd(g, a[i])
if g > 1:
	print("not coprime")
	exit()

MAX = 32
nxt = [i for i in range(MAX)]
for i in range(2, MAX):
	if nxt[i] < i:
		continue
	for j in range(i, MAX, i):
		nxt[j] = min(nxt[j], i)

fac = set()
ok = True
for x in a:
	tmp = set()
	while x > 1:
		tmp.add(nxt[x])
		x //= nxt[x]
	for p in tmp:
		if p in fac:
			ok = False
			break
		fac.add(p)
	if not ok:
		break
print("pairwise coprime" if ok else "setwise coprime")

Submission status: Runtime Error

Solution code:
import sys
readline = sys.stdin.readline

#エラトステネスの篩と素因数分解

from collections import Counter

def gcd(a,b):
    while b:
        a, b = b, a%b
    return a
M = 10**6 + 8
prime = [0]*M
for i in range(2, M):
    if prime[i]:
        continue
    for j in range(i, M, i):
        if not prime[j]:
            prime[j] = i

def pd(x):
    C = Counter()
    while x > 1:
        C[prime[x]] += 1
        x //= prime[x]
    return C


N = int(readline())
A = list(map(int, readline().split()))

D = Counter()

for a in A:
    c = pd(a)
    for k in c.keys():
        D[k] += 1


res = A[0]
for a in A:
    res = gcd(res, a)
ans = None
if max(D.values()) == 1:
    ans = 'pairwise coprime'
elif res == 1:
    ans = 'setwise coprime'
else:
    ans = 'not coprime'

print(ans)