给你两个数字p,a。如果p是素数,并且ap mod p = a,输出“yes”,否则输出“no”。
很简单的板子题。核心算法是幂取模(算法详见《算法竞赛入门经典》315页)。
幂取模板子:
int pow_mod(int a,int n,int m)
{
if(n==) return ;
int x = pow_mod(a, n / , m);
long long ans = (long long)x * x % m;
if(n%) ans = ans * a % m;
return (int)ans;
}
题目代码也比较简单,有一个坑点是如果用筛素数打表,数组开不了这么大。
报错:error: total size of array must not exceed 0x7fffffff bytes
报错代码:
#include <iostream>
#include <algorithm>
#include <iomanip>
#include <cstdio>
#include <cstring>
#include <stack>
#include <functional>
#include <queue>
#include <cmath>
using namespace std;
typedef long long ll;
ll pow_mod(ll a, ll n, ll m)
{
if (n == )
return ;
ll x = pow_mod(a, n / , m);
ll ans = x * x % m;
if (n % )
ans = ans * a % m;
return ans;
}
const long long maxn = + ;
int *vis = new int[maxn];
void prime()
{
memset(vis, , sizeof(vis));
int len = sqrt(maxn * 1.0);
for (int i = ; i <= len; i++)
if (!vis[i])
for (int j = i * ; j <= maxn; j += i)
vis[j] = ;
}
int main()
{
int p, a;
prime();
while (cin >> p >> a)
{
if (!vis[p])
cout << "no\n";
else
{
if (pow_mod(a, p, p) == a)
cout << "yes\n";
else
cout << "no\n";
}
}
delete[] vis;
return ;
}
AC代码:
#include <iostream>
#include <algorithm>
#include <iomanip>
#include <cstdio>
#include <cstring>
#include <stack>
#include <functional>
#include <queue>
#include <cmath>
using namespace std;
typedef long long ll;
ll pow_mod(ll a, ll n, ll m)
{
if (n == )
return ;
ll x = pow_mod(a, n / , m);
ll ans = x * x % m;
if (n % == )
ans = ans * a % m;
return ans;
}
bool prime(ll a)
{
if (a == )
return ;
if (a == )
return ;
for (int i = ; i * i <= a; i++)
if (a % i == )
return ;
return ;
}
int main()
{
ll a, p;
while (cin >> p >> a)
{
if (a == && p == )
break;
else
{
if (prime(p))
{
cout << "no\n";
continue;
}
if (pow_mod(a, p, p) == a)
cout << "yes\n";
else
cout << "no\n";
}
}
}