I am writing a program to tell me all the perfect numbers between 1 and 500 and I made this program, but it doesn't work although the algorithm makes sense.
import java.util.Scanner;
class allPerfect {
public static void main(String args[]) {
int sum = 0;
System.out.println("All perfect numbers between 1 and 500 are:");
for (int j = 0; j != 501; j++) {
for (int i = 1; i < j; i++) {
if (j % i == 0) {
sum = sum + i;
if (sum == j) {
System.out.println(j);
sum = 0;
} else {
sum = 0;
}
}
}
}
}
}
What's wrong here?
You are resetting sum before you finish finding all of a numbers divisors.
for(int i = 1; i < j; i++ ){
if(j % i == 0){
sum = sum + i;
if(sum == j){
System.out.println(j);
sum = 0;
}else{
sum = 0;
}
}
}
You should do the if(sum == j) only after you exit the inner for loop.
Please find the comment in-line.
class allPerfect {
public static void main(String args[]){
int sum;
System.out.println("All perfect numbers between 1 and 500 are:");
for(int j = 1; j!=501; j++){
sum = 0; //**You should reset the sum at the start of the inner loop.**
for(int i = 1; i < j; i++ ){
if(j % i == 0) {
sum = sum + i;
}
}
if(sum == j) { //------ statement-1
System.out.println(j);
}
}
}
}
statement-1
you check the sum of all the divisor is equal to the number, after summing up for all the numbers less than j
.
You can ignore all the odd number (j)
in outer loop, because odd perfect number does not exist. To be precise: it is not known that odd perfect number exists.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.