A small exercise per day -- numerical auto-multiplication non-recursive Solution

Source: Internet
Author: User

Go to the hall, go down to the kitchen, write code, and flip the walls. Welcome to the unstoppable daily practice!


Question: Non-recursive solutions for numerical self-Multiplication


Content:

Continuously evaluate the m ^ n Problem (m and n are positive integers ). The preceding prompt shows a recursive program. Compile a non-recursive program with the same computing efficiency.

 

My solution: I did not think much about it. I opened vs2013 and knocked it up. The problem was really simple, and it was superb in minutes .. Sorry, no! If it is not recursive, a simple method is,

We can use a loop to process the if branch of recursive classes. However, if we think about m ^ n, we will find that n is represented in binary format, for example: 2 ^ 7 can be rewritten

2 ^ 0111 is 2 ^ (2 ^ 0) x 2 ^ (2 ^ 1) x 2 ^ (2 ^ 2 ), therefore, the number used can all be expressed in this way: i1 * m ^ (2 ^ 0) + i2 * m ^ (2 ^ 1) + ....

M ^ (2 ^ (I + 1) = m ^ (2 ^ I * 2) = (m ^ (2 ^ I )) ^ 2 = m ^ (2 ^ I) * m ^ (2 ^ I) so we can use these principles for loop.

 

# Include <iostream> using namespace std; int _ tmain (int argc, _ TCHAR * argv []) {unsigned long int recursion (unsigned long int base, unsigned long int index ); unsigned long int base, index; cout <"Enter the base number:" <endl; cin> base; cout <"Enter the index:" <endl; cin> index; cout <base <"<index <" sub-party: "<recursion (base, index) <endl; getchar (); getchar (); return 0;} unsigned long int recursion (unsigned long int base, unsigned long int index) {unsigned long int temp = 1; while (index> 0) {if (index & 0x01 = 1) temp * = base; base * = base; index >>=1;} return temp ;}

Experiment results:



You are welcome to join us for a short exercise every day!

Practice once a day, see kung fu for a long time, come on!


-End-

References: Selecting hundreds of documents for C language naming questions


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.