You are viewing a single comment's thread. Return to all comments →
Here is a tip, a number's divisor will always be 1 and the number itself.
So you can initialize the sum as n+1 itself.
And the start the loop from i=2 till i<=n/2 because the greatest divisor of the number will not be greater than its half. Hence by this you shorten your for loop.
Also place a condition at start for n=1 then just return 1. Otherwise that test case wont be successful
i think this would fail for the case of 1, n+1 will be 2 where the correct answer is just 1
To account for a special case like 1, you one can leverage the ternary operator to assign value to sum like so:
int sum = (n==1) ? 1 : n+1;
This will mitigate logic errors in code later on.
thanks! this worked for me