Java program to print perfect numbers from 1 to 1000



Perfect Number:  a perfect number is a positive integer that is equal to the sum of its proper positive divisors, that is, the sum of its positive divisors excluding the number itself.

package demo;

public class PerfectNumbers
{
 public static void main(String[] args) 
 {
  int i, sum;
  System.out.print("Perfect numbers are: ");
  for (int n = 1; n <= 1000; n++) 
  {
   i = 1;
   sum = 0;
   while (i < n) {
    if (n % i == 0) {
     sum = sum + i;
    }
    i++;
   }
   if (sum == n) {
    System.out.print(n + " ");
   }
  }
 }
}

Output: Java program to print perfect numbers from 1 to 1000

Perfect numbers are: 6 28 496 
BUILD SUCCESSFUL (total time: 2 seconds)



No comments:

Post a Comment