寒假算法训练1-D(快速幂,欧拉函数的简单使用)

Give a number n, find the minimum x(x>0) that satisfies 2^x mod n = 1.
Input
One positive integer on each line, the value of n.
Output
If the minimum x exists, print a line with 2^x mod n = 1.

Print 2^? mod n = 1 otherwise.

You should replace x and n with specific numbers.
Sample Input
2
5
Sample Output
2^? mod 2 = 1
2^4 mod 5 = 1
记住快速幂模板,很重要!!!

#include <iostream>
using namespace std;
typedef long long ll;
ll a;
//计算欧拉函数(欧拉函数模板)
ll euler(ll n)
{
    
    
    ll res=n;
    for(int i=2;i*i<=n;i++)
    {
    
    
        if(n%i==0)
        {
    
    
            res*=res*(i-1)/i;
            while(n%i==0) n/=i;
        }
        if(n<i) break;
    }
    if(n!=1) res=res*(n-1)/n;
    return res;
}

//计算快速幂
ll q_pow(ll a,ll b,ll c)
{
    
    
    ll res=1;
    while(b)
    {
    
    
        if(b&1) res=res*a%c;
        a=a*a%c;
        b>>=1;
    }
    return res%c;
}

int main()
{
    
    
    while(scanf("%lld",&a)!=EOF)
    {
    
    
        if((a%2)==0 || a==1)
        {
    
    
            cout<<"2^? mod "<<a<<" = 1"<<endl;
        }
        else
		{
    
    
		    ll k=euler(a);
            /*for(int i=1;i<=k;i++)
            {
                if(q_pow((ll)2,i,a)==1)
                {
                    printf("2^%lld mod %lld = 1\n",i,a);
                    break;
                }
            }*/
            int i=0;
			while(++i)
			{
    
    
				if(q_pow((ll)2,i,a)==1) {
    
    printf("2^%lld mod %lld = 1\n",i,a);break;}
			}
		}
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_45754016/article/details/114254189