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
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

解題思路:這個題理解起來就是兩個函數去判斷,對應輸出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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章