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.

Not really. sqrt is obtained by integer casting; what you suggested might end up not accounting for some of the divisors.

Say n = 6.
Then sqrt = (int) Math.sqrt(6) = 2
So your loop would run only once with this statement:
sum += 1+6

After that, i < sqrt so we exit the loop.
Since 2*2 != 6, you don't add 2 to the sum.

So your suggested modification would result in sum = 7 for n = 6, which is the wrong sum.

You have probably caught this but for anyone who have not, always pay close attention to the difference between (< vs <= ) when you do integer casting!

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;
}

## Day 19: Interfaces

You are viewing a single comment's thread. Return to all comments →

it would be slightly more efficient, though, to do

`for(... i < sqrt ...)`

and`if (sqrt*sqrt==n) sum += sqrt;`

in the end.Not really. sqrt is obtained by integer casting; what you suggested might end up not accounting for some of the divisors.

Say n = 6. Then sqrt = (int) Math.sqrt(6) = 2 So your loop would run only once with this statement: sum += 1+6

After that, i < sqrt so we exit the loop. Since 2*2 != 6, you don't add 2 to the sum.

So your suggested modification would result in sum = 7 for n = 6, which is the wrong sum.

You have probably caught this but for anyone who have not, always pay close attention to the difference between (< vs <= ) when you do integer casting!

You could draw that out front, then decrese the limit avoiding the double check.