Reducing Fractions (Codeforces 222C)
Tags: Implement, number theory

To confuse the opponents, the Galactic Empire represents fractions in an unusual format. The fractions are represented as two sets of integers. The product of numbers from the first set gives the fraction numerator, the product of numbers from the second set gives the fraction denominator. However, it turned out that the programs that work with fractions in this representations aren't complete, they lack supporting the operation of reducing fractions. Implement this operation and the Empire won't forget you.

Input: The first input line contains two space-separated integers n, m (1 ≤ n, m ≤ 105) that show how many numbers the first set (the numerator) and the second set (the denominator) contain, correspondingly.The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 107) — the numbers that are multiplied to produce the numerator.The third line contains m space-separated integers: b1, b2, ..., bm (1 ≤ bi ≤ 107) — the numbers that are multiplied to produce the denominator.

Output: Print the answer to the problem in the form, similar to the form of the input data. The number of values in the sets you print nout, mout must satisfy the inequality 1 ≤ nout, mout ≤ 105, and the actual values in the sets aout, i and bout, i must satisfy the inequality 1 ≤ aout, i, bout, i ≤ 107. Separate the values in the lines by spaces. The printed fraction must be reduced, that is, there mustn't be such integer x (x > 1), that the numerator and the denominator of the printed fraction are divisible by x. If there are several matching answers, print any of them.

Note: In the first test sample the numerator equals 1000, the denominator equals 500. If we reduce fraction 1000/500 by the greatest common divisor of the numerator and the denominator (by 500), we obtain fraction 2/1.In the second test sample the numerator equals 2000, the denominator equals 300. If we reduce fraction 2000/300 by the greatest common divisor of the numerator and the denominator (by 100), we obtain fraction 20/3.

Sample Inputs:
3 2
100 5 2
50 10

4 3
2 5 10 20
100 1 3

Sample Outputs:
2 3
2 1
1 1 1

1 1
20
3

Solution (Python):
import math as mt
from sys import stdin, stdout
MAXN = 10000001
spf = [0] * MAXN

def sieve():
    spf[1] = 1
    for i in range(2, MAXN):
        spf[i] = i
    for i in range(4, MAXN, 2):
        spf[i] = 2
    for i in range(3, mt.ceil(mt.sqrt(MAXN))):
        if spf[i] == i:
            for j in range(i * i, MAXN, i):
                if spf[j] == j:
                    spf[j] = i

def getFactorization(x):
    ret = list()
    while x != 1:
        ret.append(spf[x])
        x = x // spf[x]
    return ret
sieve()

def help():
    (a, b) = map(int, stdin.readline().split(' '))
    num = list(map(int, stdin.readline().split(' ')))
    den = list(map(int, stdin.readline().split(' ')))
    spfn = [0] * MAXN
    for i in range(b):
        temp = getFactorization(den[i])
        for j in temp:
            spfn[j] -= 1
    spfn_den = [0] * MAXN
    for i in range(a):
        temp = getFactorization(num[i])
        for j in temp:
            if spfn[j] < 0:
                spfn[j] += 1
                spfn_den[j] -= 1
                num[i] = num[i] // j
    for i in range(b):
        temp = getFactorization(den[i])
        for j in temp:
            if spfn_den[j] < 0:
                spfn_den[j] += 1
                den[i] = den[i] // j
    stdout.write(str(a) + ' ' + str(b) + '\n')
    for i in range(a):
        stdout.write(str(num[i]) + ' ')
    stdout.write('\n')
    for i in range(b):
        stdout.write(str(den[i]) + ' ')
    stdout.write('\n')
help()

Solution (Python):
from sys import stdin, stdout

def countlen(Dict):
    c = 0
    for e in Dict:
        if Dict[e] != 0:
            c += 1
    return c
MAX = pow(10, 7)
HP = [0] * (MAX + 1)
HP[1] = 1
for i in range(2, MAX + 1):
    if HP[i] == 0:
        for j in range(i, MAX + 1, i):
            HP[j] = i
(n, m) = map(int, input().split())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
a = {}
b = {}
for ele in A:
    while ele > 1:
        if HP[ele] in a:
            a[HP[ele]] += 1
        else:
            a[HP[ele]] = 1
        ele //= HP[ele]
for ele in B:
    while ele > 1:
        if HP[ele] in b:
            b[HP[ele]] += 1
        else:
            b[HP[ele]] = 1
        ele //= HP[ele]
for key in a:
    if key in b:
        if a[key] == b[key]:
            a[key] = 0
            b[key] = 0
        elif a[key] > b[key]:
            a[key] -= b[key]
            b[key] = 0
        else:
            b[key] -= a[key]
            a[key] = 0
stdout.write(str(n) + ' ' + str(m) + '\n')
for i in range(n):
    temp = 1
    while A[i] > 1:
        if a[HP[A[i]]] != 0:
            temp *= HP[A[i]]
            a[HP[A[i]]] -= 1
        A[i] //= HP[A[i]]
    stdout.write(str(temp) + ' ')
stdout.write('\n')
for j in range(m):
    temp = 1
    while B[j] > 1:
        if b[HP[B[j]]] != 0:
            temp *= HP[B[j]]
            b[HP[B[j]]] -= 1
        B[j] //= HP[B[j]]
    stdout.write(str(temp) + ' ')

Solution (Python):
from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
from collections import *
if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip

def ii():
    return int(input())

def si():
    return input()

def mi():
    return map(int, input().strip().split(' '))

def msi():
    return map(str, input().strip().split(' '))

def li():
    return list(mi())

def dmain():
    sys.setrecursionlimit(1000000)
    threading.stack_size(1024000)
    thread = threading.Thread(target=main)
    thread.start()
abc = 'abcdefghijklmnopqrstuvwxyz'
abd = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25}
mod = 1000000007
inf = float('inf')
vow = ['a', 'e', 'i', 'o', 'u']
(dx, dy) = ([-1, 1, 0, 0], [0, 0, 1, -1])

def getKey(item):
    return item[1]

def sort2(l):
    return sorted(l, key=getKey, reverse=True)

def d2(n, m, num):
    return [[num for x in range(m)] for y in range(n)]

def isPowerOfTwo(x):
    return x and (not x & x - 1)

def decimalToBinary(n):
    return bin(n).replace('0b', '')

def ntl(n):
    return [int(i) for i in str(n)]

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

def ceil(x, y):
    if x % y == 0:
        return x // y
    else:
        return x // y + 1

def powerMod(x, y, p):
    res = 1
    x %= p
    while y > 0:
        if y & 1:
            res = res * x % p
        y = y >> 1
        x = x * x % p
    return res

def gcd(x, y):
    while y:
        (x, y) = (y, x % y)
    return x

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

def read():
    sys.stdin = open('input.txt', 'r')
    sys.stdout = open('output.txt', 'w')

def main():
    maxN = 10000000 + 10
    prime = []
    dp = list(range(maxN + 1))
    pre = [0, 0]
    for i in range(2, maxN + 1):
        pre.append(0)
        if dp[i] == i:
            prime.append(i)
        j = 0
        while j < len(prime) and prime[j] * i <= maxN and (prime[j] <= dp[i]):
            dp[i * prime[j]] = prime[j]
            j += 1
    (n, m) = mi()
    a = li()
    b = li()
    num = defaultdict(list)
    for i in range(n):
        ele = a[i]
        while ele > 1:
            num[dp[ele]].append(i)
            ele //= dp[ele]
    for i in range(m):
        ele = b[i]
        while ele > 1:
            if num[dp[ele]]:
                a[num[dp[ele]][-1]] //= dp[ele]
                num[dp[ele]].pop()
                b[i] //= dp[ele]
            ele //= dp[ele]
    print(n, m)
    print(*a)
    print(*b)
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):
    """"""
    (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))

def input():
    return sys.stdin.readline().rstrip('\r\n')
if __name__ == '__main__':
    main()