%mathpiper,def="PositiveIntPower"

// first define the binary exponentiation algorithm, MathIntPower.
// Later, the PowerN function will be defined through IntPower and MathLn/ExpN. Note that ExpN uses IntPower.

// power x^n only for non-negative integer n
Defun("PositiveIntPower", {x,n})
[
  Local(result,unit);
  If(IsLessThan(n,0), False,
  [
	Bind(unit,1);	 // this is a constant, initial value of the power
	Bind(result, unit);
	If(IsEqual(n,0),unit,
	 If(IsEqual(n,1),x,
	  [
		While(IsGreaterThan(n,0))
		[
			If(
				IsEqual(BitAnd(n,1), 1),
//				If(
//					IsEqual(result,unit), // if result is already assigned
//					Bind(result, x), // avoid multiplication
					Bind(result, MultiplyN(result,x))
//				)
			);
			Bind(x, MultiplyN(x,x));
			Bind(n,ShiftRight(n,1));
		];
		result;
	  ]
	 )
	);
  ]);
];

%/mathpiper