Another implementation of exponential functions

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.