Perfect Numbers Up To n.........

 

Write A Program To Display All Perfect Numbers Up To n ?


package PerfectNumbers;

import java.util.Scanner;

public class UptoNPerfectNumbers

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

            public static boolean isPerfectNumber(int num)

            {   int sum = 0;

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

                {

                    if (num % i == 0)

                    {

                        sum += i;

                    }

                }

                return sum == num;

            }

           public static void main(String[] args)

            {

                int n = 1000; // Change this value to display perfect numbers up to a different limit

                System.out.println("Perfect numbers up to " + n + ":");

                for (int i = 1; i <= n; i++)

                {

                    if (isPerfectNumber(i))

                    {

                        System.out.println(i);

                    }

                }

            }

        }


Output:

enter the integer value = 1000
6
28
496

Explanation :
1.The program still defines the class UptoNPerfectNumbers
2.The isPerfectNumber function takes an integer num as input and directly sums up its proper divisors as we find them. We use a variable sum to keep track of the sum.
3.In the main method, we set the value of n to determine the range of numbers up to which we want to find perfect numbers.
4.We iterate from 1 to n and check if each number is a perfect number using the isPerfectNumber function. If it is, we print it.

Comments

Popular posts from this blog

Constructor

How To Move Zeros To End Of An Array?

Method Overriding