Search code examples
javafor-loopmagic-numbers

"Magic Number" exercise in java


So my assignment is to find all the "magic numbers" within a range of numbers (input by the user). A magic number is a number whose factors (except itself) sums up to that number. So 6 would be a magic number because it's factors besides itself are 1,2 and 3 which sum up to 6. I have stared at this code for some time now and cannot figure out for the life of me why it won't print out the magic number. Any help would be appreciated.

public class MagicNumber {

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub
    System.out.print("What is the top of the range?");
    int range = IO.readInt();
    if (range <= 0 ) {
        IO.reportBadInput();
    }
    int sumOfFactors = 0;
    for (int i = 1 ; i <= range ; i++) {
        for (int m = 1 ; m < i; m++) {
            if (i % m == 0) {
                sumOfFactors = sumOfFactors + m;
            }
            if (sumOfFactors == i) {
                System.out.println(i);
                    }
            }
        }
    }
}

Solution

  • You are testing whether sumOfFactors == i while you are still summing factors. You need to move that outside the m loop. Then you need to set sumOfFactors to 0 before starting the m loop each time through the i loop, not just once at the start of the looping.