二分法:
package com.test;
public class Power {
public static void main(String[] args) {
System.out.print("Hello, \r\n");
System.out.print(power2(3, 2) + "\r\n");
System.out.print(power(3, 2) + "\r\n");
System.out.print(power2(3, 3) + "\r\n");
System.out.print(power(3, 3) + "\r\n");
System.out.print(power2(3, 32) + "\r\n");
System.out.print(power(3, 32) + "\r\n");
}
static long power(long a, int n) {
long r = 1;
int t = 0;
while (n >= 1) {
if ((n & 1) == 1) {
r *= a;
t++;
}
a *= a;
t++;
n = n >> 1;
}
System.out.print(t + "times \r\n");
return r;
}
static long power2(long a, int n) {
long r = 1;
while (n-- >= 1) {
r =r * a;
}
return r;
}
}
public class Power {
public static void main(String[] args) {
System.out.print("Hello, \r\n");
System.out.print(power2(3, 2) + "\r\n");
System.out.print(power(3, 2) + "\r\n");
System.out.print(power2(3, 3) + "\r\n");
System.out.print(power(3, 3) + "\r\n");
System.out.print(power2(3, 32) + "\r\n");
System.out.print(power(3, 32) + "\r\n");
}
static long power(long a, int n) {
long r = 1;
int t = 0;
while (n >= 1) {
if ((n & 1) == 1) {
r *= a;
t++;
}
a *= a;
t++;
n = n >> 1;
}
System.out.print(t + "times \r\n");
return r;
}
static long power2(long a, int n) {
long r = 1;
while (n-- >= 1) {
r =r * a;
}
return r;
}
}
id 博主 = [[KILONET.CNBLOGS.COM alloc] initWithValue:@"天堂向右,我依然向左"
网名:@"老舟"
兴趣:@"影音,阅读"
动态:@"系统架构设计,Android通信模块开发"
网址:@"http://kilonet.cnblogs.com"
签名:@"--------------------------------------------------
Stay Hungry , Stay Foolish
求 知 若 渴,处 事 若 愚
--------------------------------------------------"
]; // Never Release