Interfaces problem solution 30 days of code HackerRank

Input Format
A single line containing an integer, .
Constraints
Output Format
You are not responsible for printing anything to stdout. The locked template code in the editor below will call your code and print the necessary output.
Interfaces problem solution 30 days of code HackerRank

Problem solution in Java programming language.

class Calculator implements AdvancedArithmetic{
    public int divisorSum(int n){
        int sum = 0;
        for (int i = 1; i*i<=n; i++) {
            if (n % i == 0) {
                if (i != n / i) sum += i;
                
                sum += (n / i);

            }
        }
        return sum;
    }
}


Second solution

class Calculator implements AdvancedArithmetic{
    public int divisorSum(int n){
        // n has no divisors other than itself
        if(n == 1){
            return n;
        }
        
        // Find and sum divisors:
        int half = n/2;
        int sum = n;
        do{
            if(n % half == 0){
                sum += half;
            }
        }while( half-- > 1 );
        
        return sum;
    }
}

Problem solution in Python programming language.



class AdvancedArithmetic(object):
    def divisorSum(n):
        raise NotImplementedError



class Calculator(AdvancedArithmetic):
    def divisorSum(self, n):
        temp = []
        for i in range(1, n+1):
            if n%i == 0:
                temp.append(i)
        return sum(temp)


n = int(input())
my_calculator = Calculator()
s = my_calculator.divisorSum(n)
print("I implemented: " + type(my_calculator).__bases__[0].__name__)
print(s)

Post a Comment

0 Comments