Java examples for Algorithm:Number
Write your own power function
//from www. ja va2 s . c o m class Calculator { public int power(int n, int p) throws Exception { if (n < 0 || p < 0) throw new Exception("n and p should be non-negative"); else { int ans = 1; for (int i = 1; i <= p; i++) { ans = ans * n; } return ans; } } } public class Main { public static void main(String[] argh) { Calculator myCalculator = new Calculator(); try { int ans = myCalculator.power(2, 3); System.out.println(ans); } catch (Exception e) { System.out.println(e.getMessage()); } } }