Files
freeCodeCamp/guide/chinese/algorithms/exponentiation/index.md
2018-10-16 21:32:40 +05:30

61 lines
1.0 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: Exponentiation
localeTitle: 幂
---
## 幂
给定两个整数a和n写一个函数来计算^ n。
#### 码
算法范式:分而治之。
```C
int power(int x, unsigned int y) {
if (y == 0)
return 1;
else if (y%2 == 0)
return power(x, y/2)*power(x, y/2);
else
return x*power(x, y/2)*power(x, y/2);
}
```
时间复杂度On|空间复杂度O1
#### 优化的解决方案Ologn
```C
int power(int x, unsigned int y) {
int temp;
if( y == 0)
return 1;
temp = power(x, y/2);
if (y%2 == 0)
return temp*temp;
else
return x*temp*temp;
}
```
## 模块化指数
给定三个数字xy和p计算x ^ yp
```C
int power(int x, unsigned int y, int p) {
int res = 1;
x = x % p;
while (y > 0) {
if (y & 1)
res = (res*x) % p;
// y must be even now
y = y>>1;
x = (x*x) % p;
}
return res;
}
```
时间复杂度OLog y