package ints;
class IntExponential{
static int intExp(int a,int n){
if (n < 0) // Exponent must be non-negative
throw new ArithmeticException();
else if ((a == 0) && (n == 0)) // 0 to 0 is undefined
throw new ArithmeticException();
else {
int out = 1;
for (;n > 0;n--)
out = out*a;
return out;
}
}
static int intExpRec(int a,int n){
if (n < 0) // Exponent must be non-negative
throw new ArithmeticException();
else if ((a == 0) && (n == 0)) // 0 to 0 is undefined
throw new ArithmeticException();
else if (n == 0) return 1;
else if (n == 1) return a;
else return a*intExpRec(a,n-1);
}
static int intExpBuggy(int a,int n){
if (n < 0) // Exponent must be non-negative
throw new ArithmeticException();
else if ((a == 0) || (n == 0)) // 0 to 0 is undefined
throw new ArithmeticException();
else {
int out = 1;
for (;n > 0;n--)
out = out*a;
return out;
}
}
/*
public static void main(String[] args){
System.out.println(intExpRec(1,0));
}
*/
}
|