Pseudoprime numbers(POJ-3641 快速幂)

简介: Pseudoprime numbers(POJ-3641 快速幂)

快速幂:快速幂就是所求的幂次方过大,导致代码所用的时间超限。

如:求2^3,3的二进制是11,(n&1)判断次方数的二进制是否为1,n>>1,向右进位1:

代码:

k=1,t=n;
while(n)
  {
    if(n&1)//判断n的最后一位二进制不为0
    {
      k=k*m;
    }
    n=n>>1;
    m=m*m;
  }

题目描述:

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

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

解题思路:这个题理解起来就是两个函数去判断,对应输出yes/no,首先判断这个数是否为素数,然后再判断(a^p)%p==a就可以了,不过这个幂次方就是需要快速幂。

程序代码:

#include<stdio.h>
#include<math.h>
int  fn(long long n)
{
  long long i,j,k;
  k=sqrt(n);
  for(i=2;i<=k;i++)
  {
    if(n%i==0)
      return 0;
  }
  return 1;
}
int f(long long n,long long m)
{
  long long k,a,t;
  k=1,t=n;
  while(n)
  {
    if(n&1)
    {
      k=(k*m)%t;
    }
    n=n>>1;
    m=(m*m)%t;
  }
  return k;
}
int main()
{
  long long i,j,k,m,n;
  while(scanf("%lld%lld",&n,&m)!=EOF)
  {
    if(n==0&&m==0)
      break;
    if(fn(n)==1)
      printf("no\n");
    else
    {
      k=f(n,m);
      if(k==m)
        printf("yes\n");
      else
        printf("no\n");
    }
  }
  return 0;
}
















相关文章
|
8月前
|
Java C++
poj 1503 高精度加法
把输入的数加起来,输入0表示结束。 先看我Java代码,用BigINteger类很多东西都不需要考虑,比如前导0什么的,很方便。不过java效率低点,平均用时600ms,C/C++可以0ms过。
20 1
|
8月前
poj 1185 炮兵阵地 (状态压缩dp)
如果你是刚刚开始做状态压缩dp,我建议你先看看 poj 3254 Corn Fields 这是一道比这一题更简单,更容易入门的题目。 还有在代码中我用了一个很巧妙的方法求一个数二进制数中1的个数 具体请看我博客中 x& (x - 1)==0 这篇文章 链接 。
23 1
|
8月前
poj 1990 MooFest 树状数组
题意就是有N头牛,每头牛都有一个坐标和声调值(x, v),两头牛之间通讯要花费的能量是他们的距离乘以最大的一个音调值,现在要任意两头牛之间都相互通讯一次,求总共需要花费多少能量?
25 0
POJ-3641,Pseudoprime numbers(快速幂)
POJ-3641,Pseudoprime numbers(快速幂)
|
人机交互
POJ-2524,Ubiquitous Religions(并查集模板题)
POJ-2524,Ubiquitous Religions(并查集模板题)
|
人工智能 网络架构
|
容器
hdu3388 Coprime【容斥原理】
Problem Description Please write a program to calculate the k-th positive integer that is coprime with m and n simultaneously.
1114 0