codeforces 488 E. Prefix Product Sequence

E. Prefix Product Sequence
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

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.

Sample test(s)
input
7
output
YES
1
4
3
6
5
2
7
input
6
output
NO
Note

For the second sample, there are no valid sequences.



思路:
兩個結論:
(1)1,2,3,4有解,>4的合數都無解,反之有解
(2)解都可以由結果1,2,3,...,n - 1,0反推
對於結論1,可以發現對於>4的合數都可以用小於它的兩個數乘起來得到,所以0會出現在中間,所以>4的合數都無解。
對於結論2,可以發現,n爲質數的時候,f(x)=x*inv(x-1)是一個單射,所以結論2成立
/*======================================================
# Author: whai
# Last modified: 2015-12-05 19:46
# Filename: e.cpp
======================================================*/
#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
#include <cstring>
#include <string>
#include <cmath>
#include <set>
#include <map>
#include <queue>
#include <stack>

using namespace std;

#define LL __int64
#define PB push_back
#define P pair<int, int>
#define X first
#define Y second

const int N = 1e5 + 5;

bool is_pri[N];
void get_pri(int n) {
	memset(is_pri, 1, sizeof(bool) * (n + 1));
	is_pri[0] = is_pri[1] = 0;
	for (int i = 2; i <= n; ++i)
		if (is_pri[i]) {
			if (n / i < i) break;
			for (int j = i * i; j <= n; j += i) is_pri[j] = false;
		}
}

LL inv(LL a, LL m) {
	LL p = 1, q = 0, b = m, c, d;
	while (b > 0) {
		c = a / b;
		d = a; a = b; b = d % b;
		d = p; p = q; q = d - c * q;
	}
	return p < 0 ? p + m : p;
}

int ans[N];

int ny[N];

int main() {
	get_pri(N - 1);
	int n;
	while(cin>>n) {
		if(n == 1) {
			puts("YES");
			puts("1");
			continue;
		}
		if(n == 2) {
			puts("YES");
			puts("1");
			puts("2");
			continue;
		}
		if(n == 4) {
			puts("YES");
			puts("1\n3\n2\n4\n");
			continue;
		}
		if(!is_pri[n]) {
			puts("NO");
		} else {
			puts("YES");
			ans[0] = 1;
			ans[n - 1] = n;
			for(int i = 1; i < n - 1; ++i) {
				ny[i] = inv(i, n);
			}
			for(int i = 1; i < n - 1; ++i) {
				ans[i] = (LL)(i + 1) * ny[i] % n;
			}

			for(int i = 0; i < n; ++i) {
				cout<<ans[i]<<endl;
			}
		}
	}
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章