Perfect Numbers In Range

 

Write A Program To Display All Perfect Numbers Between Given Ranges ?

package PerfectNumbers;

public class PerfectNumbersInRange

{   // Function to check if a number is perfect or not

    static boolean isPerfectNumber(int number)

    {

        int sum = 0;

        for (int i = 1; i <= number / 2; i++)

        {

           if (number % i == 0)

            {

                sum += i;

            }

        }

        return sum == number;

    }

    // Function to display perfect numbers within a given range

    static void displayPerfectNumbersInRange(int start, int end)

    {

       System.out.println("Perfect numbers between " + start + " and " + end + ":");

        for (int i = start; i <= end; i++)

        {

            if (isPerfectNumber(i))

            {

                System.out.println(i + " ");

            }

        }

    }

    public static void main(String[] args) {

        int startRange = 1; // Replace with your desired starting number

        int endRange = 10000; // Replace with your desired ending number

 

        displayPerfectNumbersInRange(startRange, endRange);

    }

}


Output :

Perfect numbers between 1 and 10000:

6

28

496

8128


Explanation :

  1. We define a function isPerfectNumber that takes an integer as input and returns true if it's a perfect number and false otherwise.
  2. In the isPerfectNumber function, we calculate the sum of all the proper divisors of the given number by iterating from 1 to half of the number and adding the divisors to the sum variable.
  3. The function then returns true if the sum is equal to the input number, indicating it's a perfect number.
  4. Next, we define a function displayPerfectNumbersInRange that takes two integers start and end as inputs and displays all the perfect numbers between the given range.
  5. Inside the displayPerfectNumbersInRange function, we use a loop to iterate through the numbers from start to end.
  6. For each number in the range, we check if it's a perfect number by calling the isPerfectNumber function.
  7. If the number is a perfect number, we print it on the console.
  8. In the main method, you can specify your desired startRange and endRange values to find the perfect numbers within that range.

Comments

Popular posts from this blog

Constructor

How To Move Zeros To End Of An Array?

Method Overriding