So I'm trying to implement a more efficient method of calculating 2^n
.
I know that you can split it up so that it is O(logn)
and it is easy to do using recursion. You keep dividing by 2 and multiply it by the lower power when its odd (or something like that). The problem is I wrote out my multiplication method by hand since its for big numbers. So it needs to return more than one parameter.
One solution I can think of is to make a pair which contains all the needed information. Other than that though I was trying to figure out how to write it using iteration. The only way I can see of doing is using some kind of data structure and then loop through dividing n by 2 and storing the value when n is odd. Then write a for loop and check at each iteration if the value is contained in the data structure. This seems to me like a relatively costly operation.
Is it possible that it would end up less efficient than the recursive version?
I'm doing this because:
- I can't get gnp working.
- I think I am learning from writing the big numbers class and working with it.