Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find the perfect number between two numbers

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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+ ",");
            }
        }
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading