Add divisors question

Discussion in 'Mac Programming' started by soccersquirt82, Aug 31, 2008.

  1. soccersquirt82 macrumors 6502

    Mar 11, 2008
    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) {
    		  	[I]return divisor[/I]; }
    		  answer = answer + divisor;
    		  divisor = divisor + 1;
    		return answer;
  2. admanimal macrumors 68040

    Apr 22, 2005
    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.
  3. soccersquirt82 thread starter macrumors 6502

    Mar 11, 2008
    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.
  4. lee1210 macrumors 68040


    Jan 10, 2005
    Dallas, TX
    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.

  5. mobilehaathi macrumors G3


    Aug 19, 2008
    The Anthropocene
    Yeah, don't return divisor there, and once you remove that take a second look at your if statement brackets...

Share This Page