Prefix Product Sequence (Codeforces 487C)
Tags: Math, number theory

Consider a sequence [a1, a2, ... , an]. Define its prefix product sequence .Now given n, find a permutation of [1, 2, ..., n], such that its prefix product sequence is a permutation of [0, 1, ..., n - 1].

Input: The only input line contains an integer n (1 ≤ n ≤ 105).

Output: In the first output line, print "YES" if such sequence exists, or print "NO" if no such sequence exists.If any solution exists, you should output n more lines. i-th line contains only an integer ai. The elements of the sequence should be different positive integers no larger than n.If there are multiple solutions, you are allowed to print any of them.

Note: For the second sample, there are no valid sequences.

Sample Inputs:
7

6

Sample Outputs:
YES
1
4
3
6
5
2
7

NO

Solution (Python):
n = int(input())
if n == 4:
    print('YES\n1 3 2 4')
elif [i for i in range(2, n) if n % i == 0]:
    print('NO')
else:
    print('YES\n1 %s' % ' '.join((str(pow(x + 1, n - 2, n) * (x + 2) % n or n) for x in range(n - 1))))

Solution (Python):
import sys
input = sys.stdin.readline

def check(a, n):
    x = 1
    s = set()
    for i in a:
        x = x * i % n
        if x in s:
            return False
        s.add(x)
    return True

def solve():
    n = int(input())
    if n == 4:
        print('YES\n1\n3\n2\n4\n')
        return
    if n == 1:
        print('YES\n1\n')
        return
    if n == 2:
        print('YES\n1\n2\n')
        return
    for i in range(2, n):
        if n % i == 0:
            print('NO')
            return
    m = n - 1
    d = []
    for i in range(2, m):
        if i * i > m:
            break
        if m % i == 0:
            d.append(i)
            m //= i
            while m % i == 0:
                m //= i
    if m != 1:
        d.append(m)
    m = n - 1
    for w in range(2, n):
        ok = True
        for i in d:
            if pow(w, n // i, n) == 1:
                ok = False
                break
        if ok:
            p = [None] * (n - 1)
            p[0] = 1
            p[1] = w
            x = w
            for i in range(2, n - 1):
                x = x * w % n
                p[i] = x
            print('YES')
            for i in range(0, m):
                print(p[i * (-1) ** i % m])
            print(n)
            return
    raise Exception('wut')
solve()

Solution (Python):
n = int(input())
if n == 1:
    print('YES')
    print(1)
elif n == 4:
    print('YES')
    print(1)
    print(3)
    print(2)
    print(4)
else:
    s = [1]
    for i in range(2, n):
        s.append(pow(i - 1, n - 2, n) * i % n)
    s.append(n)
    if len(set(s)) < n:
        print('NO')
    else:
        print('YES')
        print('\n'.join(map(str, s)))