PDA

View Full Version : Add divisors question




soccersquirt82
Aug 31, 2008, 03:32 PM
Part of my homework is to make a program in Java that will take all the divisors of n and add them up. (e.g. n = 10, answer = 1+2+5 = 8) The part in italics is what (I think) keeps it from looping. The answer to all numbers is one because it doesn't loop. What can the italicized line be or am I way off?


static int slow (int n){

int divisor = 1; // number to divide n by and increases by one each time until above n
int answer = 0; // number that is being returned

//loop condition
while (divisor < n) {
if((n % divisor) == 0) {
return divisor; }
answer = answer + divisor;
divisor = divisor + 1;
}
return answer;
}



admanimal
Aug 31, 2008, 03:42 PM
You are right, since every number is divisible by 1, that return divisor line is exiting your loop the first time through. The question you need to ask yourself is why are you returning the divisor there.

soccersquirt82
Aug 31, 2008, 06:46 PM
I'm trying to return divisor, adding it to the answer, and then starting the loop again and adding the next divisor to the new answer until the divisor is less than n. Then I want it to return the answer.

lee1210
Aug 31, 2008, 07:13 PM
I'm trying to return divisor, adding it to the answer, and then starting the loop again and adding the next divisor to the new answer until the divisor is less than n. Then I want it to return the answer.

return exits the function immediately. Loops stop, you leave if-then constructs, the end. The function is over and the value you say to return is returned to the caller. If you want to add divisor to something, do it. No return is needed until all the work is done. You have the right addition already, but it's outside of the if. Get rid of the return and make sure the addition to answer is where you want it.

-Lee

mobilehaathi
Aug 31, 2008, 07:28 PM
Yeah, don't return divisor there, and once you remove that take a second look at your if statement brackets...