On Tue, 08 Dec 2009 05:32:26 -0500, Don <[email protected]> wrote:

Based on everyone's comments, this is what I have come up with:

--------------------
x ^^ y is right associative, and has a precedence intermediate between multiplication and unary operators.

* The type of x ^^ y is the same as the type of x * y.
* If y == 0,  x ^^ y is 1.
* If both x and y are integers, and y > 0,  x^^y is equivalent to
    { auto u = x; foreach(i; 1..y) { u *= x; } return u; }
* If both x and y are integers, and y < 0, an integer divide error occurs, regardless of the value of x. This error is detected at compile time, if possible.
* If either x or y are floating-point, the result is pow(x, y).

If x and y are both integral and x is 2, then the operation becomes 1 << y

Also, what happens when you do 3^^1000000? I hope this does not result in the exact loop you wrote above.

At the very least, when y > 32, the following code is more efficient:

{
/* get largest set bit, probably could do this more efficiently, note that the type of m and y should be unsigned */
  typeof(y) m = 1 << (typeof(y).sizeof * 8 - 1);
  while(m > y)
      m >>= 1;

  long u = 1;
  for(; m > 0; m >>=1)
  {
    u *= u;
    if(m & y)
      u *= x;
  }
  return u;
}

-Steve

Reply via email to