[Ybt gold medal navigation 8--6-5] the smallest primitive root

Minimal root

Topic link: ybt gold medal navigation 8--6-5

General idea

Give a prime number PPP , find his smallest primitive root.

Ideas

If you don’t know the original root, you can read this:
——>Click me<——

As for finding the original root, in fact, we can find it in a violent way.
Why is it possible, because it has a wide distribution of primitive roots, and the smallest is relatively small.

We consider judging whether a number is a primitive root.
For checking ggIs g moduloppThe primitive root of p , we can enumerateφ (p) \varphi(p)prime factoraa of φ ( p )a , then checkg φ (p) a ≡ 1 (mod p) g^{\frac{\varphi(p)}{a}}\equiv1(\mod\ p)gaz ( p )1(mod p ) is established, if it is established, it means that it is not a primitive root.

This question is because of ppp is a prime number, soφ (p) \varphi(p)φ ( p ) is directly equal top − 1 p-1p1 out.

Code

#include<cmath>
#include<cstdio>
#define ll long long

using namespace std;

int n, prime[100001];
int zyz[10001];
bool np[100001];

void get_prime() {
    
    //求质数
	for (int i = 2; i <= 100000; i++) {
    
    
		if (!np[i]) {
    
    
			prime[++prime[0]] = i;
		}
		for (int j = 1; j <= prime[0] && i * prime[j] <= 100000; j++) {
    
    
			np[i * prime[j]] = 1;
			if (i % prime[j] == 0) break;
		}
	}
}

void fenjie(int now) {
    
    //分解出质因数
	int up = sqrt(now);
	for (int i = 1; prime[i] <= up; i++)
		if (now % prime[i] == 0) {
    
    
			zyz[++zyz[0]] = prime[i];
			while (now % prime[i] == 0) now /= prime[i];
		}
	if (now > 1) zyz[++zyz[0]] = now;
}

ll ksm(ll x, ll y) {
    
    //快速幂
	ll re = 1;
	while (y) {
    
    
		if (y & 1) re = (re * x) % n;
		x = (x * x) % n;
		y >>= 1;
	}
	return re;
}

int main() {
    
    
	get_prime();
	
	scanf("%d", &n);
	
	fenjie(n - 1);
	
	for (int i = 1; i <= n; i++) {
    
    
		bool yes = 1;
		
		for (int j = 1; j <= zyz[0]; j++) {
    
    
			if (ksm(1ll * i, 1ll * (n - 1) / zyz[j]) == 1ll) {
    
    
				yes = 0;
				break;
			}
		}
		
		if (yes) {
    
    
			printf("%d", i);
			return 0;
		}
	}
	
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_43346722/article/details/114466625