Mike and Foam (Codeforces 547C)
Tags: Math, bitmasks

Mike is a bartender at Rico's bar. At Rico's, they put beer glasses in a special shelf. There are n kinds of beer at Rico's numbered from 1 to n. i-th kind of beer has ai milliliters of foam on it.  Maxim is Mike's boss. Today he told Mike to perform q queries. Initially the shelf is empty. In each request, Maxim gives him a number x. If beer number x is already in the shelf, then Mike should remove it from the shelf, otherwise he should put it in the shelf.After each query, Mike should tell him the score of the shelf. Bears are geeks. So they think that the score of a shelf is the number of pairs (i, j) of glasses in the shelf such that i < j and  where  is the greatest common divisor of numbers a and b.Mike is tired. So he asked you to help him in performing these requests.

Input: The first line of input contains numbers n and q (1 ≤ n, q ≤ 2 × 105), the number of different kinds of beer and number of queries.The next line contains n space separated integers, a1, a2, ... , an (1 ≤ ai ≤ 5 × 105), the height of foam in top of each kind of beer.The next q lines contain the queries. Each query consists of a single integer integer x (1 ≤ x ≤ n), the index of a beer that should be added or removed from the shelf.

Output: For each query, print the answer for that query in one line.


Sample Inputs:
5 6
1 2 3 4 6
1
2
3
4
5
1

Sample Outputs:
0
1
3
5
6
2

Solution (Python):
import sys
from collections import defaultdict
readline = sys.stdin.readline

class Prime:

    def __init__(self, N):
        assert N <= 10 ** 8
        self.smallest_prime_factor = [None] * (N + 1)
        for i in range(2, N + 1, 2):
            self.smallest_prime_factor[i] = 2
        n = int(N ** 0.5) + 1
        for p in range(3, n, 2):
            if self.smallest_prime_factor[p] == None:
                self.smallest_prime_factor[p] = p
                for i in range(p ** 2, N + 1, 2 * p):
                    if self.smallest_prime_factor[i] == None:
                        self.smallest_prime_factor[i] = p
        for p in range(n, N + 1):
            if self.smallest_prime_factor[p] == None:
                self.smallest_prime_factor[p] = p
        self.primes = [p for p in range(N + 1) if p == self.smallest_prime_factor[p]]

    def Factorize(self, N):
        assert N >= 1
        factorize = defaultdict(int)
        if N <= len(self.smallest_prime_factor) - 1:
            while N != 1:
                factorize[self.smallest_prime_factor[N]] += 1
                N //= self.smallest_prime_factor[N]
        else:
            for p in self.primes:
                while N % p == 0:
                    N //= p
                    factorize[p] += 1
                if N < p * p:
                    if N != 1:
                        factorize[N] += 1
                    break
                if N <= len(self.smallest_prime_factor) - 1:
                    while N != 1:
                        factorize[self.smallest_prime_factor[N]] += 1
                        N //= self.smallest_prime_factor[N]
                    break
            else:
                if N != 1:
                    factorize[N] += 1
        return factorize

    def Divisors(self, N):
        assert N > 0
        divisors = [1]
        for (p, e) in self.Factorize(N).items():
            A = [1]
            for _ in range(e):
                A.append(A[-1] * p)
            divisors = [i * j for i in divisors for j in A]
        return divisors

    def Is_Prime(self, N):
        return N == self.smallest_prime_factor[N]

    def Totient(self, N):
        for p in self.Factorize(N).keys():
            N *= p - 1
            N //= p
        return N

    def Mebius(self, N):
        fact = self.Factorize(N)
        for e in fact.values():
            if e >= 2:
                return 0
        else:
            if len(fact) % 2 == 0:
                return 1
            else:
                return -1
(N, Q) = map(int, readline().split())
P = Prime(5 * 10 ** 5)
mebius = [0] + [P.Mebius(i) for i in range(1, 5 * 10 ** 5 + 1)]
cnt = [0] * (5 * 10 ** 5 + 1)
ans = 0
A = list(map(int, readline().split()))
used = [False] * N
for _ in range(Q):
    q = int(readline()) - 1
    prime = list(P.Factorize(A[q]).keys())
    l = len(prime)
    for bit in range(1 << l):
        s = 1
        for i in range(l):
            if bit >> i & 1:
                s *= prime[i]
        if used[q]:
            cnt[s] -= 1
            ans -= cnt[s] * mebius[s]
        else:
            ans += cnt[s] * mebius[s]
            cnt[s] += 1
    if used[q]:
        used[q] = False
    else:
        used[q] = True
    print(ans)

Solution (Python):
import bisect
import copy
import decimal
import fractions
import functools
import heapq
import itertools
import math
import random
import sys
from collections import Counter, deque, defaultdict
from functools import lru_cache, reduce
from heapq import heappush, heappop, heapify, heappushpop, _heappop_max, _heapify_max

def _heappush_max(heap, item):
    heap.append(item)
    heapq._siftdown_max(heap, 0, len(heap) - 1)

def _heappushpop_max(heap, item):
    if heap and item < heap[0]:
        (item, heap[0]) = (heap[0], item)
        heapq._siftup_max(heap, 0)
    return item
from math import gcd as GCD
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines

class Prime:

    def __init__(self, N):
        assert N <= 10 ** 8
        self.smallest_prime_factor = [None] * (N + 1)
        for i in range(2, N + 1, 2):
            self.smallest_prime_factor[i] = 2
        n = int(N ** 0.5) + 1
        for p in range(3, n, 2):
            if self.smallest_prime_factor[p] == None:
                self.smallest_prime_factor[p] = p
                for i in range(p ** 2, N + 1, 2 * p):
                    if self.smallest_prime_factor[i] == None:
                        self.smallest_prime_factor[i] = p
        for p in range(n, N + 1):
            if self.smallest_prime_factor[p] == None:
                self.smallest_prime_factor[p] = p
        self.primes = [p for p in range(N + 1) if p == self.smallest_prime_factor[p]]

    def Factorize(self, N):
        assert N >= 1
        factorize = defaultdict(int)
        if N <= len(self.smallest_prime_factor) - 1:
            while N != 1:
                factorize[self.smallest_prime_factor[N]] += 1
                N //= self.smallest_prime_factor[N]
        else:
            for p in self.primes:
                while N % p == 0:
                    N //= p
                    factorize[p] += 1
                if N < p * p:
                    if N != 1:
                        factorize[N] += 1
                    break
                if N <= len(self.smallest_prime_factor) - 1:
                    while N != 1:
                        factorize[self.smallest_prime_factor[N]] += 1
                        N //= self.smallest_prime_factor[N]
                    break
            else:
                if N != 1:
                    factorize[N] += 1
        return factorize

    def Divisors(self, N):
        assert N > 0
        divisors = [1]
        for (p, e) in self.Factorize(N).items():
            A = [1]
            for _ in range(e):
                A.append(A[-1] * p)
            divisors = [i * j for i in divisors for j in A]
        return divisors

    def Is_Prime(self, N):
        return N == self.smallest_prime_factor[N]

    def Totient(self, N):
        for p in self.Factorize(N).keys():
            N *= p - 1
            N //= p
        return N

    def Mebius(self, N):
        fact = self.Factorize(N)
        for e in fact.values():
            if e >= 2:
                return 0
        else:
            if len(fact) % 2 == 0:
                return 1
            else:
                return -1
(N, Q) = map(int, readline().split())
P = Prime(5 * 10 ** 5)
mebius = [0] + [P.Mebius(i) for i in range(1, 5 * 10 ** 5 + 1)]
cnt = [0] * (5 * 10 ** 5 + 1)
ans = 0
A = list(map(int, readline().split()))
used = [False] * N
for _ in range(Q):
    q = int(readline()) - 1
    prime = list(P.Factorize(A[q]).keys())
    l = len(prime)
    for bit in range(1 << l):
        s = 1
        for i in range(l):
            if bit >> i & 1:
                s *= prime[i]
        if used[q]:
            cnt[s] -= 1
            ans -= cnt[s] * mebius[s]
        else:
            ans += cnt[s] * mebius[s]
            cnt[s] += 1
    if used[q]:
        used[q] = False
    else:
        used[q] = True
    print(ans)

Solution (Python):
from io import BytesIO, IOBase
import sys
import os
import bisect
import math
import random
from collections import Counter, defaultdict, deque
from copy import deepcopy
from functools import cmp_to_key, lru_cache, reduce
from heapq import heapify, heappop, heappush, heappushpop, nlargest, nsmallest
from itertools import accumulate, combinations, permutations, count
from operator import add, iand, ior, itemgetter, mul, xor
from string import ascii_lowercase, ascii_uppercase
from typing import *

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')
BUFSIZE = 4096

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 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))

    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()
sys.stdin = IOWrapper(sys.stdin)
sys.stdout = IOWrapper(sys.stdout)
input = lambda : sys.stdin.readline().rstrip('\r\n')

def I():
    return input()

def II():
    return int(input())

def MII():
    return map(int, input().split())

def LI():
    return list(input().split())

def LII():
    return list(map(int, input().split()))

def GMI():
    return map(lambda x: int(x) - 1, input().split())

def LGMI():
    return list(map(lambda x: int(x) - 1, input().split()))
inf = float('inf')

def getMu(n):
    mu = [0] * (n + 1)
    flg = [0] * (n + 1)
    p = [0] * (n + 1)
    tot = 0
    mu[1] = 1
    for i in range(2, n + 1):
        if flg[i] == 0:
            tot = tot + 1
            p[tot] = i
            mu[i] = -1
        j = 1
        while j <= tot and i * p[j] <= n:
            flg[i * p[j]] = 1
            if i % p[j] == 0:
                mu[i * p[j]] = 0
                break
            mu[i * p[j]] = -mu[i]
            j = j + 1
    return mu

class PrimeTable:

    def __init__(self, n: int) -> None:
        self.n = n
        self.primes = []
        self.max_div = list(range(n + 1))
        self.max_div[1] = 1
        self.phi = list(range(n + 1))
        for i in range(2, n + 1):
            if self.max_div[i] == i:
                self.primes.append(i)
                for j in range(i, n + 1, i):
                    self.max_div[j] = i
                    self.phi[j] = self.phi[j] // i * (i - 1)

    def is_prime(self, x: int):
        if x < 2:
            return False
        if x <= self.n:
            return self.max_div[x] == x
        for p in self.primes:
            if p * p > x:
                break
            if x % p == 0:
                return False
        return True

    def prime_factorization(self, x: int):
        if x > self.n:
            for p in self.primes:
                if p * p > x:
                    break
                if x <= self.n:
                    break
                if x % p == 0:
                    cnt = 0
                    while x % p == 0:
                        cnt += 1
                        x //= p
                    yield (p, cnt)
        while 1 < x and x <= self.n:
            (p, cnt) = (self.max_div[x], 0)
            while x % p == 0:
                cnt += 1
                x //= p
            yield (p, cnt)
        if x >= self.n and x > 1:
            yield (x, 1)

    def get_factors(self, x: int):
        factors = [1]
        for (p, b) in self.prime_factorization(x):
            n = len(factors)
            for j in range(1, b + 1):
                for d in factors[:n]:
                    factors.append(d * p ** j)
        return factors
pt = PrimeTable(5 * 10 ** 5)
(n, q) = MII()
nums = LII()
note = [0] * n
mobius = getMu(5 * 10 ** 5)
cnt = [0] * (5 * 10 ** 5 + 1)
ans = 0
for _ in range(q):
    x = II() - 1
    v = nums[x]
    vals = [1]
    for (p, _) in pt.prime_factorization(v):
        for i in range(len(vals)):
            vals.append(vals[i] * p)
    for val in vals:
        if note[x]:
            cnt[val] -= 1
            ans -= cnt[val] * mobius[val]
        else:
            ans += cnt[val] * mobius[val]
            cnt[val] += 1
    note[x] ^= 1
    print(ans)