数学

\(\qquad\!\!\)大概是最近需要的 OI 中有关纯数学的部分算法,估计会鸽很多。

  • 1、快速幂:

\(\qquad\!\!\)例题:

\(\qquad\!\!\)快速幂||取余运算

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include<bits/stdc++.h>
#define in inline
#define re register
#define int long long
using namespace std;
int a,b,p;
in int qread()
{
int x=0,y=1;
int ch=getchar();
while(ch<'0'||ch>'9')
{
if(ch=='-')
{
y=-1;
}
ch=getchar();
}
while(ch>='0'&&ch<='9')
{
x=(x<<1)+(x<<3)+(ch^48);
ch=getchar();
}
return x*y;
}
in void qwrite(re int x)
{
if(x<0)
{
putchar('-');
qwrite(-x);
}
else
{
if(x>9)
{
qwrite(x/10);
}
putchar(x%10+'0');
}
return ;
}
in int qpow(re int x,re int y)
{
int res=1;
while(y)
{
if(y&1)
{
res=(res*x)%p;
}
x=(x*x)%p;
y>>=1;
}
return res%p;
}
signed main()
{
a=qread();
b=qread();
p=qread();
qwrite(a);
printf("^");
qwrite(b);
printf(" mod ");
qwrite(p);
printf("=");
qwrite(qpow(a,b));
putchar('\n');
return 0;
}
  • 2、慢速乘:

\(\qquad\!\!\)输出 \(a\times b\ \ \bmod \ \ p\) 的值:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include<bits/stdc++.h>
#define in inline
#define re register
#define int long long
using namespace std;
int a,b,p;
in int qread()
{
int x=0,y=1;
int ch=getchar();
while(ch<'0'||ch>'9')
{
if(ch=='-')
{
y=-1;
}
ch=getchar();
}
while(ch>='0'&&ch<='9')
{
x=(x<<1)+(x<<3)+(ch^48);
ch=getchar();
}
return x*y;
}
in void qwrite(re int x)
{
if(x<0)
{
putchar('-');
qwrite(-x);
}
else
{
if(x>9)
{
qwrite(x/10);
}
putchar(x%10+'0');
}
return ;
}
in int qpow(re int x,re int y)
{
int res=0;
while(y)
{
if(y&1)
{
res=(res+x)%p;
}
x=(x+x)%p;
y>>=1;
}
return res%p;
}
signed main()
{
a=qread();
b=qread();
p=qread();
qwrite(a);
printf("*");
qwrite(b);
printf(" mod ");
qwrite(p);
printf("=");
qwrite(qpow(a,b));
putchar('\n');
return 0;
}