0

I dont know why I am getting confused about this as this is relatively simple but I am going to ask anyway...

Consider the following algorithm: Given a value k, compute ak, and binary search for ak in an array of size N. Consider the fact that multiplication takes O(log2(a)k) time.

What would the total runtime for this algorithm be? Here are my thoughts:

In the worst case, binary search will make log2(N) comparisons, and for each comparison, it takes O(log2(a)k) to calculate ak. So the total would be O(log2(a)k(log2(N)))? Am I going about this the correct way?

  • How is $N$ related to $a,k$? The time of multiplication should be related to the size of the numbers being multiplied, not to the size of the array. If $N$ is given, I can choose $a,k$ to make finding $a^k$ take longer than any constant based on $N$ – Ross Millikan Dec 16 '18 at 03:35
  • sorry my mistake i fixed it – Matt Sigfried Dec 16 '18 at 03:36
  • That would be fine for multiplying $a \cdot a$, but multiplying $a^{10} \cdot a^{10}$ takes longer as there are more bits to multiply. What you should say is that multiplication of $a^k \cdot a^k$ takes $\log_2(a^k)^2$ time – Ross Millikan Dec 16 '18 at 03:37
  • is my bound correct now? – Matt Sigfried Dec 16 '18 at 03:38

1 Answers1

0

Presumably you compute $a^k$ once, then search for it in the array. You should not multiply the number of operations for each part, you should add them. Using binary search assumes that the array is sorted, but we will accept that. You are right that you will do $\log_2 N$ comparisons. To compute $a^k$ you can express $k$ in binary, square $a$ enough times, then multiply the values that correspond to the one bits in $k$. You should be able to express this in terms of the number of bits in $a$, which is $\log_2 a$ and a function of $k$.

Ross Millikan
  • 374,822
  • what if you are repeating this process fo multiple values of a, then do you multiply? – Matt Sigfried Dec 16 '18 at 03:47
  • Yes, but you have to find the amount of computation for one value of $a$ first, then multiply by the number of values of $a$. The question does not talk of multiple values of $a$ – Ross Millikan Dec 16 '18 at 04:09