Another way of thinking about exponentiation

Source: Internet
Author: User

In the introduction of the algorithm, it is mentioned that in seeking a certain number of powers, we follow the thought of reducing the law.

Here is another approach, by the exponential y binary decomposition of the exponentiation, such as X^y, when y=5, the x^5=x^101,x*=x equivalent to solve the x^10...0....0:, the algorithm time complexity is O (log (y)), the code is as follows.

#include <iostream>int len (char *arr) {int count=0;for (int i=0;arr[i]!= ' + '; i++) {count++;} return count;} void Main (int argc,char* argv[]) {int x=0,y=0;int result=1;printf ("pls input") numbers:\n ("%d", scanf); &x ( "%d", &y), Char Ch[256];itoa (y,ch,2), for (int i=len (CH) -1;i>=0;i--) {if (ch[i]== ' 1 ') {printf ("%d\n", x); result*= x;}   X*=x;}   print ("result:%d", result); System ("Pause");}

  

Another way of thinking about exponentiation

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.