c/c++语言开发共享GCD&&素筛&&快速幂 –A – Pseudoprime numbers

Fermat's theorem states that for any prime number p and for any integer a > 1, ap = a (mod p). That is, if we raise a to the pth power and divide by p …

fermat’s theorem states that for any prime number p and for any integer a > 1, ap = a (mod p). that is, if we raise a to the pth power and divide by p, the remainder is a. some (but not very many) non-prime values of p, known as base-a pseudoprimes, have this property for some a. (and some, known as carmichael numbers, are base-a pseudoprimes for all a.)

given 2 < p ≤ 1000000000 and 1 < a < p, determine whether or not p is a base-a pseudoprime.

input

input contains several test cases followed by a line containing “0 0”. each test case consists of a line containing p and a.

output

for each test case, output “yes” if p is a base-a pseudoprime; otherwise output “no”.

sample input

3 2  10 3  341 2  341 3  1105 2  1105 3  0 0  

sample output

no  no  yes  no  yes  yes
本题用到快速幂,素数判定、二者结合;
题意:输入两个数p,a.先判断p是否为素数,如果是,输出no。否则,再判断a的p次方取余p是否为a,是则yes,反之
则no。
#include<iostream>  #include<math.h>  #include<stdio.h>  using namespace std;  typedef long long ll;  int isprime(ll n)  {      if(n<=3)  return n>1;      int k;       k=sqrt(n);      if(n%6!= 1 && n%6!=5)          return 0;      for(int i=5;i<=k;i+=6)      {          if(n%i==0 || n%(i+2)==0)              return 0;      }      return 1;  }  ll qpow(ll a, ll n,ll mod)//计算a^n % mod  {      ll re = 1;      while(n)      {          if(n & 1)//判断n的最后一位是否为1              re = (re * a) % mod;          n >>= 1;//舍去n的最后一位          a = (a * a) % mod;//将a平方      }      return re;  }  int main()  {      ll p,a;      while(cin>>p>>a&&a&&p)      {          if(isprime(p))          cout<<"no"<<endl;          else          {              if(a==qpow(a,p,p))              cout<<"yes"<<endl;              else              cout<<"no"<<endl;              }                }      return 0;  } 

typedef

typedef long long ll;

快速幂模板

ll qpow(ll a, ll n,ll mod)//计算a^n % mod  {      ll re = 1;      while(n)      {          if(n & 1)//判断n的最后一位是否为1              re = (re * a) % mod;          n >>= 1;//舍去n的最后一位          a = (a * a) % mod;//将a平方      }      return re;
}

质数判定模板

int isprime(ll n)  {      if(n<=3)  return n>1;      int k;       k=sqrt(n);      if(n%6!= 1 && n%6!=5)          return 0;      for(int i=5;i<=k;i+=6)      {          if(n%i==0 || n%(i+2)==0)              return 0;      }      return 1;  }

 

 

注意输入用cin,用scanf会wa

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/c-cdevelopment/602586.html

(0)
上一篇 2021年5月11日
下一篇 2021年5月11日

精彩推荐