We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
You could draw that out front, then decrese the limit avoiding the double check.
public int divisorSum(int n) {
int sum = 0;
int limit = (int) Math.sqrt(n);
if (limit * limit == n) {
// if limit is divisor count it, decrease limit
sum += limit;
limit--;
}
// If n is odd, no even divisors
int stepSize = n % 2 + 1;
for (int i = 1; i <= limit; i += stepSize) {
if (n % i == 0) { // if "i" is a divisor
sum += i + n/i; // add both divisors
}
}
return sum;
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Day 19: Interfaces
You are viewing a single comment's thread. Return to all comments →
You could draw that out front, then decrese the limit avoiding the double check.