I’m new to Java, and in order to practice I found a task on the Internet:
"Find all the perfect numbers between the two numbers you enter."
By the way – a perfect number is a natural number equal to the sum of all its own divisors. So I got to work and ran into such a problem that when I enter two numbers.
For example: 1 100, I get the correct answer in the console: 6,28. But if the first number is, for example, 100 and the second is 500 I get this output to the console: 6,28,496,, while I should get only 496. That is, for some reason, the minimum value does not shorten the search for a perfect number.
Here’s where I ended up:
import java.util.Scanner;
public class IsPerfect {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int min = in.nextInt();
int max = in.nextInt();
System.out.println(min +" to "+max+" perfect numbers:");
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.print(sum+ ",");
}
}
}
}
If anyone has any advice on how to fix this error, I would sincerely appreciate it.
>Solution :
You are assigning the minimum value to 1, no matter what the user enters. Change your outer for loop to start from the minimum value the user enters:
import java.util.Scanner;
public class IsPerfect {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int min = in.nextInt();
int max = in.nextInt();
System.out.println(min +" to "+max+" perfect numbers:");
for (; min <= max; min++) {
int sum = 0;
for (int e = 1; e < min; e++) {
if ((min % e) == 0) {
sum += e;
}
}
if (sum == min) {
System.out.print(sum+ ",");
}
}
}
}