Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C++ > How can I write the most efficient code about this problem?

Reply
Thread Tools

How can I write the most efficient code about this problem?

 
 
carlmuller@hotmail.com
Guest
Posts: n/a
 
      12-06-2005
wrote:
> Recently, I'm interested in writing very efficient code.
>
> Problem:
> there is a sequence { a(0), a(1), ..., a(n-1) } and a very small
> positive integer k, write an algorithm without using multiply to
> calculate the following formula:
> n-1
> _____
> \
> \ ki
> / 2 * a(i)
> /_____
> i = 0
>
> My answer is following:
>
> inline int sum(int a[], size_t n, size_t k) {
> int sum = 0;
> while (n--) (sum <<= k) += a[n];
> return sum;
> }
>
> would you please point out if my answer is the best answer?
> And could you cite out your answer? Thank you!


You should make it correct first before optimising it.
1. You are modifying the variable "sum" twice between sequence points,
which is not good in C or C++. So the answer may well be wrong,
depending on your compiler settings.
2. I also think it is bad style to have the function name and the local
variable using the same identifier.
3. The parameter a should be const as it is not modified; this will
allow its use in more situations.

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Re: How include a large array? Edward A. Falk C Programming 1 04-04-2013 08:07 PM
efficient way to write multiple loops code friend.05@gmail.com Perl Misc 18 10-10-2008 08:51 AM
Most Efficient Way of Exporting CSV data from page Peter ASP .Net 1 11-09-2004 10:41 PM
What is most efficient? OnItemDataBound or using a function Anders ASP .Net 4 07-19-2004 11:29 AM
What is the most efficient way to access common fcts on asp.net pages when using user controls? Brent Minder ASP .Net 3 12-28-2003 02:28 PM



Advertisments
 



1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57