---
id: 570
lang: en
translation_of: index.md
source_sha256: ea81e1d1fc2221c5a7de453c0a640693a3ecadcc8feac9601920dff2b8f38dde
title: "P3846: [TJOI2007] Cute Prime — Solution"
description: "A BSGS template problem: given a^x ≡ b (mod p), find the value of x."
tags: ["OI","Math","Number Theory","BSGS"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes:
  - "Problem name 可爱的质数 rendered as “Cute Prime” (literally “lovely prime number”)."
  - "模板题 rendered as “template problem” without a chip, treated as standard OI jargon, as in other approved editions."
  - "后半部分 / 前半部分 rendered literally as “the second half” / “the first half” of the equation."
---

## BSGS Algorithm Template Problem

We have $a^{x} \equiv b (mod \; p)$ and want the value of $x$. Let's work through this equation a bit. First, this $x \in [0, p]$, and we can let $x=im-j$, where $m=\lceil \sqrt{p} \rceil$. Clearly, $j \in [0, m], i \in [1, m]$. The equation turns into this:

$$
a^{im}\equiv a^j b (mod \; p)
$$

Then we only need to compute the second half, push it into a map, and then enumerate the first half to get the answer.

## Code

```cpp
// P3846.cpp
#include <bits/stdc++.h>
#define ll long long
using namespace std;
ll p, a, b;
ll quick_power(ll base, ll tim)
{
    ll tmp = 1;
    while (tim)
    {
        if (tim & 1)
            tmp = tmp * base % p;
        base = base * base % p;
        tim >>= 1;
    }
    return tmp;
}
map<ll, ll> hashTable;
int main()
{
    scanf("%lld%lld%lld", &p, &a, &b);
    a %= p;
    if (a == 0)
    {
        if (b == 0)
            printf("0");
        else
            printf("no solution");
        return 0;
    }
    hashTable.clear();
    ll m = ceil(sqrt(p));
    for (int j = 0, x = 1; j <= m; j++, x = x * a % p)
        hashTable[x * b % p] = j;
    ll unit = quick_power(a, m);
    for (int i = 1, x = unit; i <= m; i++, x = x * unit % p)
        if (hashTable.count(x))
        {
            printf("%lld", i * m - hashTable[x]);
            return 0;
        }
    printf("no solution");
    return 0;
}
```
