1. Welcome to the new MacRumors forums. See our announcement and read our FAQ

Add divisors question

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

  1. macrumors 6502

    #1
    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;
    	}
    
     
  2. macrumors 68040

    #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.
     
  3. macrumors 6502

    #3
    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. macrumors 68040

    lee1210

    #4
    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
     
  5. macrumors demi-god

    mobilehaathi

    #5
    Yeah, don't return divisor there, and once you remove that take a second look at your if statement brackets...
     

Share This Page