2^x mod n = 1(暴力或欧拉函数)

2^x mod n = 1

 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

题意:

找到最小的x使得 2x mod n=1 2 x   m o d   n = 1

根据欧拉定理我们知道如果2和n不互质x一定不存在,但是还要注意当n = 1的时候因为他很特殊所有数模1都是0,所以也无解

因此根据求欧拉函数可得到一个值使得x满足上式,但不一定是最小的,所以还有从小于phi的数内枚举一遍。。当然了也可以直接一开始就暴力枚举

code:

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
typedef long long ll;
ll Euler(ll n){
    ll ans = n;
    for(ll i = 2; i * i <= n; i++){
        if(n % i == 0){
            ans = ans / i *(i - 1);
            while(n % i == 0) n /= i;
        }
    }
    if(n != 1){
        ans = ans / n * (n - 1);
    }
    return ans;
}
ll gcd(ll a,ll b){
    return b ? gcd(b,a%b) : a;
}
ll q_pow(ll a,ll b,ll mod){
    ll ans = 1;
    while(b){
        if(b & 1)
            ans = ans * a % mod;
        b >>= 1;
        a = a * a % mod;
    }
    return ans;
}
int main(){
    ll n;
    while(~scanf("%lld",&n)){
        if(gcd(2LL,n) != 1 || n == 1){
            printf("2^? mod %lld = 1\n",n);
        }
        else{
            ll phi = Euler(n);
            ll ans = phi;
            for(ll i = 2; i <= phi; i++){
                if(q_pow(2LL,i,n) == 1){
                    ans = i;
                    break;
                }
            }
            printf("2^%lld mod %lld = 1\n",ans,n);
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值