Most programming languages have a built-in implementation of exponentiation.



Task

Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition).

If the language supports operator (or procedure) overloading, then an overloaded form should be provided for both   intint   and   floatint   variants.



Related tasks

   Exponentiation order
   arbitrary-precision integers (included)
   Exponentiation with infix operators in (or operating on) the base


 
(* Library Interface *)
DEFINITION MODULE Exponentiation;
 
PROCEDURE IntExp(base, exp : INTEGER) : INTEGER;
 (* Raises base to the power of exp and returns the result
    both base and exp must be of type INTEGER *)
 
PROCEDURE RealExp(base : REAL; exp : INTEGER) : REAL;
 (* Raises base to the power of exp and returns the result
    base must be of type REAL, exp of type INTEGER *)
 
END Exponentiation.
 
(* Library Implementation *)
IMPLEMENTATION MODULE Exponentiation;
 
PROCEDURE IntExp(base, exp : INTEGER) : INTEGER;
  VAR
    i, res : INTEGER;
  BEGIN
    res := 1;
    FOR i := 1 TO exp DO
      res := res * base;
    END;
    RETURN res;
  END IntExp;
 
PROCEDURE RealExp(base: REAL; exp: INTEGER) : REAL;
  VAR
    i : INTEGER;
    res : REAL;
  BEGIN
    res := 1.0;
    IF exp < 0 THEN
      FOR i := exp TO -1 DO
        res := res / base;
      END;
    ELSE (* exp >= 0 *)
      FOR i := 1 TO exp DO
        res := res * base;
      END;
    END;
    RETURN res;
  END RealExp;
 
END Exponentiation.
 