<\/span><\/h2>\n\n\n\nA Java interface can only contain method signatures and fields. The interface can be used to achieve polymorphism. In this problem, you will practice your knowledge on interfaces.<\/p>\n\n\n\n
You are given an interface AdvancedArithmetic which contains a method signature int divisor_sum(int n). You need to write a class called MyCalculator which implements the interface.<\/p>\n\n\n\n
divisorSum function just takes an integer as input and return the sum of all its divisors. For example divisors of 6 are 1, 2, 3 and 6, so divisor_sum should return 12. The value of n will be at most 1000.<\/p>\n\n\n\n
Read the partially completed code in the editor and complete it. You just need to write the MyCalculator class only. Your class shouldn’t be public.<\/p>\n\n\n\n
<\/span>Sample Input<\/strong><\/span><\/h4>\n\n\n\n 6<\/code><\/pre>\n\n\n\n<\/span>Sample Output<\/strong><\/span><\/h4>\n\n\n\n I implemented: AdvancedArithmetic\n 12<\/code><\/pre>\n\n\n\n<\/span>Explanation<\/strong><\/span><\/h4>\n\n\n\nDivisors of 6 are 1,2,3 and 6. 1+2+3+6=12.<\/p>\n\n\n\n
<\/span>Solution – Java Interface<\/strong><\/span><\/h2>\n\n\n\nimport java.util.*;\ninterface AdvancedArithmetic{\n int divisor_sum(int n);\n}\n\n\/\/Write your code here\nclass MyCalculator implements AdvancedArithmetic {\n public int divisor_sum(int n) {\n int sum=0;\n for(int i=1;i<=n;i++) {\n if(n%i==0)\n sum+=i;\n }\n return sum;\n }\n}\n\nclass Solution{\n public static void main(String []args){\n MyCalculator my_calculator = new MyCalculator();\n System.out.print(\"I implemented: \");\n ImplementedInterfaceNames(my_calculator);\n Scanner sc = new Scanner(System.in);\n int n = sc.nextInt();\n System.out.print(my_calculator.divisor_sum(n) + \"\\n\");\n \tsc.close();\n }\n \/*\n * ImplementedInterfaceNames method takes an object and prints the name of the interfaces it implemented\n *\/\n static void ImplementedInterfaceNames(Object o){\n Class[] theInterfaces = o.getClass().getInterfaces();\n for (int i = 0; i < theInterfaces.length; i++){\n String interfaceName = theInterfaces[i].getName();\n System.out.println(interfaceName);\n }\n }\n}<\/pre>\n\n\n\n