Anonymous
Anonymous asked in Computers & InternetProgramming & Design · 1 month ago

# How to write a program in java that identifies perfect numbers?

Relevance

Start by writing a loop that produces all of the divisors of an integer n.

Place that loop in a static method that adds up all of the divisors and returns the sum as an int result.

One thing to beware of:  Only include "proper divisors" in the sum.  Proper divisors of n are greater than 0 and less than n.  So the number 1 has no proper divisors and its divisor sum is 0.  So 6 is the first perfect number, with a divisor sum of 1 + 2 + 3 = 6.

Besides making the main program simpler (see below), writing that sum as a static method means you'll can easily use that method in other programs, in case some future assignment (or competitive coding challenge) asks you to find abundant or deficient numbers.

The main() program is easy.  Just loop for n=1 to whatever you can stand waiting for and test:

if (n == divisorSum(n)) {

[report that (i) is a perfect number.]

}

Start with an upper limit of 10,000 or so, and you'll find the first four (6, 28, 496, 8,128). The next one is 33,550,336, and you'll probably need to speed up your divisorSum() function to find that one without waiting for many hours.

If you want your code to run faster, think about improving the divisor sum to only test divisor less than or equal to the square root of n.  When n is a million or more, that makes the code at least 1000 times faster for all values

Beyond that is where you'll need a whole new approach, searching for Mersenne primes instead of perfect numbers.  The Wikipedia article on "Perfect Numbers" has more information.