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.