My teacher wants me to find all the perfect numbers between 2 and 1000 and must use:
for
loops%
operator to determine if a number is a divisorstatic final
variables for 2 and 1000- A
static
method to return a boolean value by finding and adding the divisors of the integer parameter and comparing the sum to the parameter
The code works and I just wanted a second opinion on it.
public class Problem_B {
//Search between 2 and 1000
public static final int minNum = 2;
public static final int maxNum = 1000;
public static void main(String[] args) {
for (int num=minNum; num <= maxNum; num++)
if (perfectNum(num)) {
int i_sumDiv = 0;
for (int j=1; j <= (num/2); j++) {
if(num%j == 0)
i_sumDiv = i_sumDiv + j;
}
if (i_sumDiv == num)
System.out.println(num + " is a perfect number.");
}
}
public static Boolean perfectNum(int num) {
// a variable that holds the sum of the factors
int sum = 0;
for (int factor = 1; factor < num; factor++) {
if (num % factor == 0) {
sum += factor;
}
}
if (sum == num) {
return true;
} else {
return false;
}
}
}
main()
which is a duplicate of all the code inperfectNum()
? \$\endgroup\$perfectNum
is broken (answer in progress) ;-) \$\endgroup\$true
, doesn't feel right at all. How did you test/validate it? \$\endgroup\$