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