bradacha - 10 months ago 114

Java Question

I have an assignment to create a perfect number calculator, but I don't really understand how to go about it. I've found some examples on here, but obviously don't want to just copy, but I'm having trouble figuring out what each part is for.

I know that the first For loop means that when min is less than or equal to 10000 to add 1, but why is the next variable declared inside the loop, along with whatever 'e' is for. Is 'e' supposed to be the check for perfect numbers?

`public static void main(String[] args){`

int min = 1;

int max = 10000;

for (min = 1; min <= max; min++) {

int sum = 0;

for (int e = 1; e < min; e++) {

if ((min % e) == 0) {

sum += e;

}

}

if (sum == min){

System.out.println(sum);

}

}

}

Answer Source

In number theory, a perfect number is a positive integer that is equal to the sum of its proper positive divisors, that is, the sum of its positive divisors excluding the number itself

Let's break this code down:

```
public static void main(String[] args){
// The lowest number we will check to see if it's perfect
int min = 1;
// The highest number we will check to see if it's perfect
int max = 10000;
// A loop to go over all numbers in the range to check which of them are perfect
for (min = 1; min <= max; min++) {
// The sum of proper positive divisors for our number
int sum = 0;
// A loop to calculate the sum of positive divisors for our number, here 'e' will
// go from 1 to 'min-1' (because a perfect number excludes the number itself)
for (int e = 1; e < min; e++) {
// This if is true if the number if a proper divisor of our number ('min')
if ((min % e) == 0) {
// The number is a proper divisor so we add it to the sum of proper divisors
// for our number
sum += e;
}
}
// We finished checking all of our proper divisors for the number 'min'
if (sum == min){
// If this is is true, that means that the sum of all proper divisors
// for 'min' equals to 'min' -> 'min' is a perfect number, so we
// print it
System.out.println(sum);
}
}
```