Finding Perfect Numbers in Java

Problem:

A positive integer is called a perfect number if it is equal to the sum of all of its positive divisors, excluding itself. For example, 6 is the first perfect number because 6 = 3 + 2 + 1. The next is 28 = 14 + 7 + 4 + 2 + 1. There are four perfect numbers less than 10000. Write a program to find all these four numbers.


Output:

6
28
496
8128


Solution:

public class PerfectNumbers
{
  public static int sumDivisors(int n )
  {
    int sum = 0;
    for (int i =n-1;i>=1;i--)
    {
      if(n%i == 0)
      {
        sum+=i;
      }
    }
    return sum;
  }
  public static void main(String[] args)
  {
    for (int i =1;i<10000;i++)
    {
      if(sumDivisors(i) == i)
        System.out.println(i);
    }
  }
}


No comments :

Post a Comment

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact