RosettaCodeData/Task/Exponentiation-operator/Modula-2/exponentiation-operator.mod2

47 lines
1014 B
Plaintext

(* 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.