## 一个算法问题，result *=a : result *= result 的改进。

Brianlicorice 发布于 2013/02/20 18:38

`1 result = 1; `
`2 for(int i = 1; i <=n; i++) `
`3 result *= a;`

`result = a; `
`for(int i = 1; i <=k; i++) `
`result = result * result;`

0

0

B

0

B

0
```//x是底数，y是指数
long power(int x, int y) {
long half;

if (y == 0) return 1;
half = power(x, y / 2);
return half * half * (y%2 == 0 ? 1 : x);
}```

0
```/* n必须是2的整数次幂， k =  log2 （n）*/
#include <stdio.h>
#include <math.h>

int main(int argc, char* argv[])
{
int i = 0, n = 8, ret = 1, a = 3, k;

for (i = 1; i <= n; i++)
ret *= a;
printf("ret = %d\n", ret);

ret = a;
k = (int)((float)log(n)/(float)log(2));

for (i = 1; i <= k; i++)
ret *= ret;
printf("ret = %d\n", ret);

return 0;
}```
0
B

#### 引用来自“lwdxinghuo”的答案

```/* n必须是2的整数次幂， k =  log2 （n）*/
#include <stdio.h>
#include <math.h>

int main(int argc, char* argv[])
{
int i = 0, n = 8, ret = 1, a = 3, k;

for (i = 1; i <= n; i++)
ret *= a;
printf("ret = %d\n", ret);

ret = a;
k = (int)((float)log(n)/(float)log(2));

for (i = 1; i <= k; i++)
ret *= ret;
printf("ret = %d\n", ret);

return 0;
}```

0

```int a, n, i, result = 1;
for( i = 1; i < 32; i++ ) {
if( n & 1 ) {
result *= a;
}
a *= a;
n >>= 1;
}```