UVALive - 7457 Discrete Logarithm Problem 费马小定理+暴力枚举+快速幂

31 篇文章 0 订阅
29 篇文章 0 订阅

由 费马小定理可知:

a ^ b % m  = a ^ ( b % (m-1) ) % m ;

(费马小定理:m是质数时  a ^ (m-1) % m = 1)

所以对于本题 枚举 a 的 1 - p  次幂对 p 取模,


#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
#include <vector>
#include <set>
#include <stack>
#include <map>
#include <climits>

using namespace std;

typedef long long ll;
const int maxn = 10 + 7, INF = 0x3f3f3f3f, mod = 1e9 + 7;

ll p, a, b, x;

bool solve(ll n) {
    //cout << n << "  ";
    ll ans = 1;
    ll t = a;
    while(n) {
        if(n & 1) ans *= t, ans %= p;
        t = t * t; t %= p;
        n /= 2;
    }
    //cout << ans << " == " << endl;
    if(ans == b) return true;
    else return false;
}

int main() {
    ios::sync_with_stdio(0);

    cin >> p;
    while(cin >> a && a) {
        cin >> b;
        int f = 0;
        for(ll i = 1; i < p; ++i) {
            if(solve(i)) { cout << i << endl; f = 1; break;}
        }
        if(!f) cout << 0 << endl;
    }


    return 0;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值