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!

## Day 19: Interfaces

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

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!