42 lines
1.1 KiB
Text
42 lines
1.1 KiB
Text
using System;
|
|
using System.Console;
|
|
using Nemerle.Assertions;
|
|
|
|
module Expon
|
|
{
|
|
Expon(val : int, pow : int) : int // demonstrates simple/naive method
|
|
requires pow > 0 otherwise throw ArgumentOutOfRangeException("Negative powers not allowed, will not return int.")
|
|
{
|
|
mutable result = 1;
|
|
repeat(pow) {
|
|
result *= val
|
|
}
|
|
result
|
|
}
|
|
|
|
Expon(val : double, pow : int) : double // demonstrates shift and square method
|
|
{
|
|
mutable neg = false;
|
|
mutable p = pow;
|
|
when (pow < 0) {neg = true; p = -pow};
|
|
mutable v = val;
|
|
mutable result = 1d;
|
|
|
|
while (p > 0) {
|
|
when (p & 1 == 1) result *= v;
|
|
v *= v;
|
|
p >>= 1;
|
|
}
|
|
if (neg) 1d/result else result
|
|
}
|
|
|
|
Main() : void
|
|
{
|
|
def eight = 2^3;
|
|
// def oops = 2^1.5; // compilation error as operator is defined for integer exponentiation
|
|
def four = Expon(2, 2);
|
|
def four_d = Expon(2.0, 2);
|
|
|
|
WriteLine($"$eight, $four, $four_d");
|
|
}
|
|
}
|