In this HackerRank Day 17 More Exceptions 30 days of code problem set, we need to develop a program that can take two input integers and then we need to print the power of that inputs on the output screen and if the numbers are negative integers then we need to print the message that inputs are needed to positive numbers.


Day 17 More Exceptions 30 days of code solution Hackerrank


Problem solution in Python 2 programming.

#Write your code here
class Calculator:
    def power(self, n, p):
        if (n < 0 or p < 0):
            raise Exception("n and p should be non-negative")
        else:
            return n**p
        


Problem solution in Python 3 programming.

#Write your code here
class Calculator:

    def power(self,n, p):
        if n < 0 or p < 0:
            raise Exception("n and p should be non-negative")
        else:
            return pow(n,p)


Problem solution in java programming.

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");
        }
        return (int)Math.pow(n,p);
    }
}


Problem solution in c++ programming.

//Write your code here
class Calculator {
    public:
        int power(int n, int p){
            if(n < 0 || p < 0){
                throw invalid_argument("n and p should be non-negative"); 
            }
            
            return pow(n, p);
        }
};


Problem solution in Javascript programming.

//Write your code here
function Calculator() {
    this.power = function(n, p) {
        if (n < 0 || p < 0)
            throw "n and p should be non-negative";
            
        var ans = 1;
        for (i = 0; i < p; i++) {
            ans *= n;
        }
        
        return ans;
    }
}