BZOJ1406 [AHOI2007] 密码箱

题目链接:http://www.lydsy.com/JudgeOnline/problem.php?id=1406

Description

在一次偶然的情况下,小可可得到了一个密码箱,听说里面藏着一份古代流传下来的藏宝图,只要能破解密码就能打开箱子,而箱子背面刻着的古代图标,就是对密码的提示。经过艰苦的破译,小可可发现,这些图标表示一个数以及这个数与密码的关系。假设这个数是n,密码为x,那么可以得到如下表述: 密码x大于等于0,且小于n,而x的平方除以n,得到的余数为1。 小可可知道满足上述条件的x可能不止一个,所以一定要把所有满足条件的x计算出来,密码肯定就在其中。计算的过程是很艰苦的,你能否编写一个程序来帮助小可可呢?(题中x,n均为正整数)

Input

输入文件只有一行,且只有一个数字n(1<=n<=2,000,000,000)。

Output

你的程序需要找到所有满足前面所描述条件的x,如果不存在这样的x,你的程序只需输出一行“None”(引号不输出),否则请按照从小到大的顺序输出这些x,每行一个数。

x ^ 2 % n = 1 等价于 x ^ 2 = kn + 1 等价于 x ^ 2 - 1 = kn 等价于 ( x + 1 ) ( x - 1 ) = kn

枚举 n 的大于 sqrt( n ) 的约数作为 x + 1 或 x - 1 检验,去重后输出

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <algorithm>
 4 #include <cstring>
 5 #define rep(i,l,r) for(int i=l; i<=r; i++)
 6 #define clr(x,y) memset(x,y,sizeof(x))
 7 using namespace std;
 8 const int maxn = 100010;
 9 int n,cnt = 0,tot = 0,d[maxn],ans[maxn];
10 int main(){
11     scanf("%d",&n);
12     for (int i = 1; i*i <= n; i++) if (!(n % i)) d[++cnt] = n / i;
13     rep(i,1,cnt){
14         int now = d[i];
15         for (int j = now; j <= n; j += now){
16             if (!((j - 2) % (n / now))) ans[++tot] = j - 1;
17             if (!((j + 2) % (n / now))) ans[++tot] = j + 1;
18         }
19     }
20     sort(ans+1,ans+tot+1);
21     tot = unique(ans+1,ans+tot+1) - ans - 1;
22     if (!tot) printf("None
"); else{
23         printf("1
");
24         rep(i,1,tot) if (ans[i] < n) printf("%d
",ans[i]);
25     }
26     return 0;
27 }
View Code
原文地址:https://www.cnblogs.com/jimzeng/p/bzoj1406.html