![]() |
|
|
| Subject:
Data structure and algorithm
Category: Computers Asked by: math01-ga List Price: $5.00 |
Posted:
16 Jul 2003 08:11 PDT
Expires: 15 Aug 2003 08:11 PDT Question ID: 231631 |
Give an O(n) algorithm for computing a^n, given a and n. Give an O(logn) algorithm for computing a^n, given that n is a power of 2. |
|
| Subject:
Re: Data structure and algorithm
Answered By: answerguru-ga on 16 Jul 2003 09:01 PDT |
Hi math01-ga,
Here are the algorithms you requested:
Give an O(n) algorithm for computing a^n, given a and n.
int i = 0;
int total = 1;
while(i <= n)
{
total = total*a;
}
return total;
Give an O(logn) algorithm for computing a^n, given that n is a power of 2.
int i = 1;
int total = a;
if(n == 0)
{
return 1;
}
else
{
while(i <= n)
{
total = total*total;
i = i + i;
}
return total;
}
Please let me know if you have any questions :)
Cheers!
answerguru-ga |
|
| Subject:
Re: Data structure and algorithm
From: jasontiger-ga on 23 Jul 2003 20:25 PDT |
The o(n) algorithm has a bug, I think. The loop control variable does not change and therefore the loop will go forever. |
| Subject:
Re: Data structure and algorithm
From: answerguru-ga on 24 Jul 2003 08:18 PDT |
That's correct jasontiger...the fixed algorithm should look like this:
int i = 0;
int total = 1;
while(i <= n)
{
total = total*a;
i++;
}
return total; |
If you feel that you have found inappropriate content, please let us know by emailing us at answers-support@google.com with the question ID listed above. Thank you. |
| Search Google Answers for |
| Google Home - Answers FAQ - Terms of Service - Privacy Policy |