In general, a simple implementation of the exponential function POW (n, m) is
public long myPow(int n, int m){ long value = 1; while(m>0){ value *= n; m--; } return value;}
The time complexity of this algorithm is O (m );
This algorithm is more effective when the computing scale is small, but the following algorithm can be used when the scale increases to a certain extent.
Take X21 as an Example
1) the binary value of X21 = x10101 21 is 10101.
2) starting from the left of the Binary Index, if the first value is 1, it is represented as Y = y * x = x (the initial value of Y is 1)
3) if the second is 0, y = y * Y = x2
4) The third is 1, and y = y * x = X5.
5) if the fourth is 0, y = y * Y = x10
6) if the fifth is 1, y = y * x = X21
Code Implementation
/** *Apr 14, 2013 *Copyright(c)JackWang *All rights reserve *@Author <a href="mailto:wangchengjack@163.com">JackWang</a>*/package com.myjava.generic;public class MyPow {/** * @param args */public static void main(String[] args) {int x = 2;int n = 12;long value = myPow(x,n);System.out.println(value);}private static long myPow(int x, int n) {int m; m = n;int t = 1;while(m > 0){m /= 2;t *= 2; // 1;}m = n;int y = 1;while(t>1){t /= 2;y *= y;while(m >= t){y *= x;m -= t; // 2;}}return y;}}
This algorithm is complex to understand, but the time complexity is O (logm)
What is hard to understand in this algorithm is marked as 1 and 2.
1 is the value of BITs + 1 when the record m is converted to a binary system. 2 is the result of processing the leftmost 1. The following figure can help you understand.