• Hdoj 1905.Pseudoprime numbers 题解


    Problem Description

    Fermat's theorem states that for any prime number p and for any integer a > 1, a^p == 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 ≤ 1,000,000,000 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
    

    Author

    Gordon V. Cormack

    Source

    2008-1杭电公开赛(非原创)


    思路

    就是判断(a^p\%p==a),计算(a^p)可以用快速幂的方法,快速幂本质也是二分不断加速

    代码

    #include<bits/stdc++.h>
    using namespace std;
    typedef __int64 ll;
    
    bool isprime(ll x)
    {
    	for(int i=2;i<sqrt(x);i++)
    		if(x%i==0)
    			return false;
    	return true;
    }//判断是否为质数
    
    ll quickpower(ll a,ll b,ll c)
    {
    	ll ans =1;
    	while(b)
    	{
    		if(b&1)
    			ans = (ans*a) % c;
    		a = (a*a) % c;
    		b >>= 1;
    	}
    	return ans;
    }//返回a^b%c的结果
    int main()
    {
    	int a,p;
    	while(cin>>p>>a)
    	{
    		if(p==0 && a==0) break;
    		if(isprime(p))
    			cout << "no" << endl;
    		else
    		{
    			int ans_power = quickpower(a,p,p);
    			if(ans_power==a)
    				cout << "yes" << endl;
    			else 
    				cout << "no" << endl;
    		}
    	}
    	return 0;
    }
    
  • 相关阅读:
    快速排序算法
    excel取值
    5.管理控制文件和日志文件
    贝叶斯决策与参数估计小结
    Kernel Methods (5) Kernel PCA
    Kernel Methods (4) Kernel SVM
    Kernel Methods (3) Kernel Linear Regression
    Kernel Methods (2) Kernel function
    Kernel Methods (1) 从简单的例子开始
    PCA算法是怎么跟协方差矩阵/特征值/特征向量勾搭起来的?
  • 原文地址:https://www.cnblogs.com/MartinLwx/p/9985961.html
Copyright © 2020-2023  润新知