# Java Interface

# Java Interface

chrynan + 0 comments A lot of these questions are written poorly. Proper Java naming conventions are being ignored (I've seen things such as "MyCalculator my_calc" and "int A"; both of which are wrong). Interfaces are being written incorrectly (Interface methods written like: "public abstract int divisorSum()"; where both "public" and "abstract" are redundant for an interface). And sometimes the questions are ambiguous. It's very important that these things be considered before publishing a question as not doing so will promote bad practice among new developers.

RodneyShag + 0 comments ### Efficient O(n^(1/2)) solution

From my HackerRank solutions.

Runtime: O(n^(1/2))

Space Complexity: O(1)class MyCalculator implements AdvancedArithmetic { public int divisor_sum(int n) { int sum = 0; int sqrt = (int) Math.sqrt(n); for (int i = 1; i <= sqrt; i++) { if (n % i == 0) { // if "i" is a divisor sum += i + n/i; // add both divisors } } /* If sqrt is a divisor, we should only count it once */ if (sqrt * sqrt == n) { sum -= sqrt; } return sum; } }

Let me know if you have any questions.

AdHominem + 0 comments Again the most elegant solution is a one liner:

java.util.stream.IntStream.rangeClosed(1,number) .filter(e -> number % e == 0) .sum();

kalyan_bandi + 0 comments The code can be improved from O(n) to O(n/2) time complexity.

int divisorSum(int num) { int result = num; /*Loop only till num/2 elements. You do not have any divisor of num after num/2*/ for (int i=1; i<=num/2; i++) { if (num%i == 0) result += i; } return result; }

wooddoo + 0 comments When talking about math, it only requires to loop from 1 to sqrt(n):

public int divisor_sum(int n){ int sum=0; int sqrt = (int)Math.sqrt(n); for (int i=1; i<=sqrt; i++) if (n%i==0) sum = sum + i + n/i; if (n == sqrt*sqrt) sum = sum-sqrt; return sum; }

Sort 245 Discussions, By:

Please Login in order to post a comment