Let us see, what is perfect number and the code to print perfect numbers in a given range from 1 to n.

What is a Perfect Number?

Perfect Number is a number whose sum of factors is the same number, excluding itself.

Example: 6

factors of 6 are 1, 2, 3 and 6  

sum of the factors = 1 + 2 + 3 = 6 (excluding the given number 6).

Java Code to Print Perfect Numbers Between 1 to n

import java.util.Scanner;
public class Perfect
{
        static boolean perfect(int num)
        {
            int sum = 0;
            for(int i=1; i<num; i++)
            {
                if(num%i==0)
                {
                    sum = sum+i;
                }
            }
            if(sum==num)
                return true;
            else
                return false;
        }
        public static void main(String[] args)
        {
            Scanner obj = new Scanner (System.in);
            System.out.println("enter the value for n");
            int n = obj.nextInt();
            for(int i=1; i<=n; i++)
            {
                if(perfect(i))
                    System.out.println(i);
            }
        }


}

Output:

enter the value for n
50
6
28