Google Answers Logo
View Question
 
Q: Data structure and algorithm ( Answered,   2 Comments )
Question  
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.
Answer  
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
Comments  
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;

Important Disclaimer: Answers and comments provided on Google Answers are general information, and are not intended to substitute for informed professional medical, psychiatric, psychological, tax, legal, investment, accounting, or other professional advice. Google does not endorse, and expressly disclaims liability for any product, manufacturer, distributor, service or service provider mentioned or any opinion expressed in answers or comments. Please read carefully the Google Answers Terms of Service.

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 Answers  


Google Home - Answers FAQ - Terms of Service - Privacy Policy