Your problem is here:
for(int i =2;i<=n-1;i++)
{
if(n%i != 0)
{
break;
}
else
{
sum = sum + i;
}
}
With break
you are stopping the whole iteration of you for
loop, meaning after the first number which is not a divisor, i.e. where n%i != 0
equals true you are breaking out of the loop and continue execution with if(sum == n)
. I guess you where mistaken that as you don’t want to add i
s which are not a divisor, you where too “eager” not to count them. I guess you mixed it up with continue
which would had gone back to the for
condition check and would have continued execution with i+1
if the condition is still true.
Still as you had packed the addition in an else
branch, meaning the summation would either way only happen if and only the if
before n%i != 0
would be false, meaning if its a divisor. Thats the reason you don’t need either continue
, which would not do any big difference, nor break
, which “breaks” you program in this case.
3
solved My code works for only one input. Please advice