UVALive 7457 Discrete Logarithm Problem (暴力枚举)

本文针对一个具体的离散对数问题,通过枚举的方法解决了a^x%p=b的方程求解问题,并提供了一段C++代码实现,适用于p小于2^13的情况。

Discrete Logarithm Problem

题目链接:

http://acm.hust.edu.cn/vjudge/contest/127401#problem/D

Description


http://7xjob4.com1.z0.glb.clouddn.com/42600d1bedc3c308a68ea0453befd84e

Input


The first line of the input file contains a prime p, 1 < p < 2^13 . This prime will be used in the following
test cases. Each test case contains two integers a and b in a line. The last test case is followed by a
line containing ‘0’.

Output


For each test case, print out the solution x to the equation a
x = b in the finite group Zp. If there are no solutions, print ‘0’.

Sample Input


31
24 3
3 15
0

Sample Output


7
21


题意:


求一个x使得 a^x%p = b .


题解:


由于p的规模巨小(2^13),而取模的结果一定在p次以内出现循环,所以直接从0~p枚举x即可.
很多人TLE了,不知道什么姿势. (可能是末尾的0没有读好)
虽然是水题,还是很高兴拿了FB.


代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
#include <stack>
#include <vector>
#include <list>
#define LL long long
#define eps 1e-8
#define maxn 1010
#define mod 100000007
#define inf 0x3f3f3f3f
#define mid(a,b) ((a+b)>>1)
#define IN freopen("in.txt","r",stdin);
using namespace std;

LL quickmod(LL a,LL b,LL m)
{
    LL ans = 1;
    while(b){
        if(b&1){
            ans = (ans*a)%m;
            b--;
        }
        b/=2;
        a = a*a%m;
    }
    return ans;
}

int main(int argc, char const *argv[])
{
    //IN;

    int p; cin >> p;
    LL a, b;
    while(scanf("%lld", &a) != EOF && a)
    {
        scanf("%lld", &b);
        a %= p; //b %= p;

        int ans = 0;
        for(int i=0; i<=p+1; i++) {
            if(quickmod(a, i, p) == b) {
                ans = i;
                break;
            }
        }

        printf("%d\n", ans);
    }

    return 0;
}

转载于:https://www.cnblogs.com/Sunshine-tcf/p/5781439.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值