On Monday, 19 August 2024 at 09:42:44 UTC, Daniel Donnelly, Jr. wrote:
```d
   Type opBinary(string op="^")(int k)
   in {
      assert (k > 0);
   }
   do {
      if (k == 1)
         return this;

      auto P = this;

      while (k > 0)
      {
         k --;
         P = this * P;
      }

      return P;
   }
```

`^` should be a bitwise XOR, instead you can overload `^^` which is for exponentiation.

Also, your algorithm is a little bit flawed. To rework it, it would help if you consider cases like:
- `1^^n == 1`
- `n^^0 == sign(n)` (if `n` is 0, returns 1 or undefined)
- `0^^n == 0` (divide by zero if `n` is negative)

It’s cases like these which can help inform us how the algorithm should work. If you can’t think of how you’d make all those cases line up correctly, try looking at an existing integer exponentiation algorithm online. An algorithm written in another language will still be applicable in D.

Reply via email to