5

I'm implementing the alkhwarizmi algorithm.
It's right but my g++ compiler doesn't like the shift operators: >> and << or I'm doing something wrong.
When I compile it, I get this output:

> g++ -Wall  -std=c++0x -o "Al-khwarizmi algorithm.o" "Al-khwarizmi algorithm.cpp" (in directory: /home/akronix/workspace/Algorithms)
> Al-khwarizmi algorithm.cpp: In function ‘int alkhwarizmi(int, int)’: Al-khwarizmi algorithm.cpp:31:9: warning: statement has no effect
> [-Wunused-value] Al-khwarizmi algorithm.cpp:34:9: warning: statement
> has no effect [-Wunused-value] Compilation finished successfully.

Here is my code:

int alkhwarizmi(int x, int y)
{
    int sum = 0;
    while (x>0)
    {
        if (x%2)
            sum+=y;
        //y *= 2;
        y << 1;
        cout << y <<endl;
        //x /= 2;
        x >> 1;
        cout << x <<endl;
    }
    return sum;
}

if I use the commented statements (straightforward multiplication and division), everything works fine.

Akronix
  • 1,858
  • 2
  • 19
  • 32
  • 2
    Just a comment: if you're doing this shifting as a learning exercise, fine. But if you're trying to 'optimize' the multiplication or division - don't. If the intent of your code is to multiply or divide a number, use the multiplication or division operators. Let your code express what your code's intent is. The compiler can generally decide whether a shift will be efficient quite well. – Michael Burr Mar 26 '14 at 18:17
  • 1
    but, when a multiplication or division by two is more efficient than a shift? – Akronix Mar 27 '14 at 18:21
  • 1
    the compiler will compile a multiplication or division by 2 into a shift. See this: http://stackoverflow.com/q/10681375/12711 Also, the compiler will optimize more complex situations than multiplication or division by powers of 2 into shifts/adds: http://stackoverflow.com/a/1168616/12711 Bottom line: if you are multiplying or dividing, use those operators and let the compiler do the transformation to shifts and adds if appropriate. – Michael Burr Mar 27 '14 at 18:41

1 Answers1

15
 y << 1;

should be

 y <<= 1; //^^equals y = y << 1;

Same issue on the statement below:

x >>1; //^^same issue should be x >>= 1;
taocp
  • 23,276
  • 10
  • 49
  • 62