0

Write a static method printNumbers that takes an integer max as an argument and prints out all perfect numbers that are less than or equal to max.

At first, I kept getting the wrong answer because the inner loop was set to j < max before I changed it to j < i. However, I don't understand why that range would matter, because wouldn't i % j != 0 anyway, even if the range of j were to be larger?

for (int i = 1; i <= max; i++) {   
    int sum = 0;

    for (int j = 1; j < i; j++) {
        if (i % j == 0) {
            sum += j;
        }
    }
    if (sum == i) {
        System.out.print(sum + " ");
    }
}

If I changed the inner loop j < max, then printNumbers(6) gives both 1 and 6, but printNumbers(500) gives only 1 and no other number.

AAA
  • 3,520
  • 1
  • 15
  • 31
serena
  • 11
  • 1
  • The difference is when `j == i`, because `i % j` *is* 0 when that happens – Andreas Jun 05 '19 at 23:31
  • Did you try debugging? – shmosel Jun 05 '19 at 23:31
  • If j is allowed to climb beyond i, e.g. to max, then it will be larger than i during the loop. And also hit i once per iteration, yielding modulo 0. However, note that you are doing i mod j, not the other way around. 10 mod 5 is 0 as well, as it is for every divisor. So you are summing up all the divisors of i per iteration. – Zabuzard Jun 05 '19 at 23:32
  • E.g., 1 % 1 == 0 would happen with `j < max` but not with `j < i`. – Elmar Peise Jun 05 '19 at 23:33

1 Answers1

1

If you set j < max in the inner loop, then when j = i, i % j == 0 returns true and skews your result. This is a good example of a mathematical error to watch out for in coding.

AAA
  • 3,520
  • 1
  • 15
  • 31
  • I see, so printNumbers(500) wouldn't return 6 as an option, nor 28 or 496 because the sum would have been incremented by the value when j = i, which is what you mean by skewing the result, right? – serena Jun 05 '19 at 23:43
  • Exactly, that's what I mean. So, `sum == i` will erroneously return false for that `i` (6, 28, 496). – AAA Jun 05 '19 at 23:48