BZOJ 1406 密码箱(数论)

很简洁的题目。求出x^2%n=1的所有x<=n的值。 n<=2e9.

直接枚举x一定是超时的。 看看能不能化成有性质的式子。

有 (x+1)(x-1)%n==0,设n=a*b,那么一定有x+1=k1a,x-1=k2b. 不妨设a<=b.那么就能O(sqrt(n))枚举a。

然后再枚举x,验证x是否满足这两个式子。注意不能令x=k1a-1.由于a比较小,枚举x=k2b+1,k2b-1即可。

另外set很好用啊。

 

# include <cstdio>
# include <cstring>
# include <cstdlib>
# include <iostream>
# include <vector>
# include <queue>
# include <stack>
# include <map>
# include <set>
# include <cmath>
# include <algorithm>
using namespace std;
# define lowbit(x) ((x)&(-x))
# define pi 3.1415926535
# define eps 1e-9
# define MOD 100000007
# define INF 1000000000
# define mem(a,b) memset(a,b,sizeof(a))
# define FOR(i,a,n) for(int i=a; i<=n; ++i)
# define FO(i,a,n) for(int i=a; i<n; ++i)
# define bug puts("H");
# define lch p<<1,l,mid
# define rch p<<1|1,mid+1,r
# define mp make_pair
# define pb push_back
typedef pair<int,int> PII;
typedef vector<int> VI;
# pragma comment(linker, "/STACK:1024000000,1024000000")
typedef long long LL;
int Scan() {
    int res=0, flag=0;
    char ch;
    if((ch=getchar())=='-') flag=1;
    else if(ch>='0'&&ch<='9') res=ch-'0';
    while((ch=getchar())>='0'&&ch<='9')  res=res*10+(ch-'0');
    return flag?-res:res;
}
void Out(int a) {
    if(a<0) {putchar('-'); a=-a;}
    if(a>=10) Out(a/10);
    putchar(a%10+'0');
}
const int N=100005;
//Code begin...

set<LL>::iterator it;
set<LL>S;

int main ()
{
    LL a, b, x, n;
    scanf("%lld",&n);
    for (int i=1; i*i<=n; ++i) {
        if (n%i) continue;
        a=i; b=n/i;
        for (int k=0; (x=b*k+1)<n; ++k) if ((x+1)%a==0) S.insert(x);
        for (int k=1; (x=b*k-1)<n; ++k) if ((x-1)%a==0) S.insert(x);
    }
    for (it=S.begin(); it!=S.end(); ++it) printf("%lld\n",*it);
    return 0;
}
View Code

 

posted @ 2017-03-17 17:34  free-loop  阅读(260)  评论(0编辑  收藏  举报