您的位置:首页 > 其它

Codeforces Round #174 (Div. 2) Cows and Primitive Roots(数论)

2013-03-22 13:46 786 查看
Cows and Primitive Roots

time limit per test
2 seconds

memory limit per test
256 megabytes

input
standard input

output
standard output

The cows have just learned what a primitive root is! Given a prime p, a primitive root

is an integer x (1 ≤ x < p) such that none of integers x - 1, x2 - 1, ..., xp - 2 - 1 are divisible by p, but xp - 1 - 1 is.

Unfortunately, computing primitive roots can be time consuming, so the cows need your help. Given a prime p, help the cows find the number of primitive roots

.

Input
The input contains a single line containing an integer p (2 ≤ p < 2000). It is guaranteed that p is a prime.

Output
Output on a single line the number of primitive roots

.

Sample test(s)

Input
3


Output
1


Input
5


Output
2


Note
The only primitive root

is 2.

The primitive roots

are 2 and 3.

可使用蛮力法,但需要注意两点:

1、不要每次都用pow计算x的n次方,由于x^n=x*X^(n-1),设一个变量m储存x^(n-1),那么x^n=m*x.

2、如果直接算出m,就算用64位也会溢出,利用性质(a-b)%p=(a%p-b%p)%p,则只需保留m%p的值。

AC Code:

#include <iostream>
#include <fstream>
#include <string>
#include <set>
#include <map>
#include <vector>
#include <stack>
#include <queue>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <utility>
using namespace std;
#define ll long long
#define cti const int
#define ctll const long long
#define dg(i) cout << '*' << i << endl;

int main()
{
ll p, x;
ll m;
int ans;
bool ok;
while(scanf("%I64d", &p) != EOF)
{
ans = 0;
for(x = 1; x < p; x++)
{
m = 1;
ok = true;
for(int i = 1; i < p - 1; i++)
{
m *= x;
m %= p;
if((m - 1) % p == 0)
{
ok = false;
break;
}
}
if(ok && ((m * x) - 1) % p == 0) ans++;
}
printf("%d\n", ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: