Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

soccersquirt82

macrumors 6502
Original poster
Mar 11, 2008
296
0
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?

Code:
	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) {
		  	[I]return divisor[/I]; }
		  answer = answer + divisor;
		  divisor = divisor + 1;
		}
		return answer;
	}
 

admanimal

macrumors 68040
Apr 22, 2005
3,531
2
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

macrumors 6502
Original poster
Mar 11, 2008
296
0
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

macrumors 68040
Jan 10, 2005
3,182
3
Dallas, TX
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
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.