HackerRank Java- Interface




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.

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.

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.



  1. import java.util.*;
  2. interface AdvancedArithmetic{
  3. int divisor_sum(int n);
  4. }
  5. class MyCalculator implements AdvancedArithmetic {
  6. public int divisor_sum(int n) {
  7. int sum = 0;
  8. int sqrt = (int) Math.sqrt(n);
  9. for (int i = 1; i <= sqrt; i++) {
  10. if (n % i == 0) {
  11. sum += i + n / i;
  12. }
  13. }
  14. if (sqrt * sqrt == n) {
  15. sum -= sqrt;
  16. }
  17. return sum;
  18. }
  19. }
  20. class Solution{
  21. public static void main(String []args){
  22. MyCalculator my_calculator = new MyCalculator();
  23. System.out.print("I implemented: ");
  24. ImplementedInterfaceNames(my_calculator);
  25. Scanner sc = new Scanner(System.in);
  26. int n = sc.nextInt();
  27. System.out.print(my_calculator.divisor_sum(n) + "\n");
  28. sc.close();
  29. }
  30. /*
  31. * ImplementedInterfaceNames method takes an object and prints the name of the interfaces it implemented
  32. */
  33. static void ImplementedInterfaceNames(Object o){
  34. Class[] theInterfaces = o.getClass().getInterfaces();
  35. for (int i = 0; i < theInterfaces.length; i++){
  36. String interfaceName = theInterfaces[i].getName();
  37. System.out.println(interfaceName);
  38. }
  39. }
  40. }




codesadda.com

Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube