传送门
Now you get Baby Ehab’s first words: “Given an integer n, find the longest subsequence of [1,2,…,n−1] whose product is 1 modulo n.” Please solve the problem.
A sequence b is a subsequence of an array a if b can be obtained from a by deleting some (possibly all) elements. The product of an empty subsequence is equal to 1.
Input
The only line contains the integer n (2≤n≤105).
Output
The first line should contain a single integer, the length of the longest subsequence.
The second line should contain the elements of the subsequence, in increasing order.
If there are multiple solutions, you can print any.
思路:
需要特判n=1和n=2的情况,打表找规律,当n为大于2的质数时,输出1到n-2的所有数,当n为合数时,先标记n的因数的倍数,然后输出1到n的非n的因数的倍数的数,同时需要特判n-1是否满足。
#include<bits/stdc++.h>
using namespace std;
const int inf = 0x3f3f3f3f;
#define ll long long
const int mod = 1e9+7;
int vis[100010];
int num = 1;
int p[100010];
int ans[100010];
int yin[100010];
int vis2[100010];
void pri(int n)
{
for(int i = 2; i <= n; i++)
{
if(!vis2[i])
{
for(int j = i*2; j <= n; j+=i)
{
vis2[j] = 1;
}
}
}
}
int main()
{
int n;
cin>>n;
pri(n);
int cnt = 1;
if(n <= 2)
{
printf("%d\n%d\n",1,1);
return 0;
}
if(!vis2[n])
{
printf("%d\n",n-2);
for(int i = 1; i <= n-2; i++)
{
printf("%d ",i);
}
}
else
{
int l = 1;
for(int i = 1; i <= n; i++)
{
if(n % i == 0)
{
yin[l++] = i;
}
}
for(int i = 2; i < l;i++)
{
for(int j = yin[i]; j <= n; j+=yin[i])
{
vis[j] = 1;
}
}
for(int i = 1; i <= n; i++)
{
if(!vis[i])
{
ans[cnt++] = i;
}
}
if(ans[cnt-1] == n-1)
{
ll sum = 1;
for(int i = 1; i < cnt; i++)
{
sum *= ans[i];
sum %= n;
}
if(sum != 1)
{
cnt--;
}
}
printf("%d\n",cnt-1);
for(int i = 1; i < cnt; i++)
printf("%d ",ans[i]);
}
}