(数论)51NOD 1135 原根

本文介绍了一种算法,用于找到小于等于10^9范围内的质数P的最小原根。通过分解质因数和使用快速幂方法,文章详细解释了如何判断一个数是否为原根,并给出了具体的C语言实现代码。
设m是正整数,a是整数,若a模m的阶等于φ(m),则称a为模m的一个原根。(其中φ(m)表示m的欧拉函数)
 
给出1个质数P,找出P最小的原根。
Input
输入1个质数P(3 <= P <= 10^9)
Output
输出P最小的原根。
Input示例
3
Output示例
2
解:使用快速幂的时候小心int爆了。
 1 #include <stdio.h>
 2 #include <math.h>
 3 #include <string.h>
 4 #define CLR(x) memset(x,0,sizeof x)
 5 
 6 int num[30];
 7 
 8 int deco(int temp)//分解质因数
 9 {
10     int max = sqrt((double)temp);
11     int j = 0;
12     for (int i = 2; i <= max && temp != 1;i++)
13     {
14         if(temp%i == 0)
15         {
16             num[j++] = i; 
17             while (temp%i == 0) temp /= i;            
18         }
19     }
20     if (temp != 1) num[j] = temp;
21 }
22 
23 int jud(int a,int b)
24 {
25     int p = b + 1;
26     long long a1 = a;
27     for (int i = 0; num[i]; i++)
28     {
29         int c = b / num[i];
30         long long pd = 1;
31         while (c)
32         {
33             if (c & 1) pd = pd * a1 % p;
34             a1 = a1 * a1 % p;
35             c >>= 1;
36         }
37         if (pd == 1) return 1;
38     }
39     return 0;
40 }
41 
42 int main()
43 {
44     int n;
45     while (scanf_s("%d", &n) != EOF)
46     {
47         int temp = n - 1, i;
48         CLR(num);
49         deco(temp);
50         for (i = 2; jud(i, temp); i++);
51         printf("%d\n", i);
52     }
53 }

 

转载于:https://www.cnblogs.com/Ekalos-blog/p/9734661.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值