|Solving the Perfect Number Problem|
When attempting to devise an algorithmic solution to a difficult problem, begin by reducing the problem to something that you know how to solve. For example, before you can find the first three perfect numbers, you need to determine how to find one perfect number. If that problem is still too complex, try to simplify it further. The problem specification indicates that 6 is the first perfect number, so figure out on paper how to verify that 6 is perfect. Start by reviewing the definition of a perfect number:
Therefore, the first thing we need to do is to find the factors of 6. A factor of 6 is a number that divides evenly into 6. Obviously it must also be less than 6, and the problem specifications further stipulate that it must be less than and not equal to 6. In order to process all of the numbers less than or equal to 6 starting at 1, we consider them sequentially. 1 divides evenly into 6, 2 divides evenly into 6, 3 divides evenly into 6, 4 does not, 5 does not. Therefore the factors of 6 are 1, 2, and 3. We can stop the loop at 6/2, since we have already exhausted all possible factors.
The definition of a perfect number states that it is equal to the sum of its factors. In this case 1+2+3 = 6, which is the number in question. Thus, we just traced the process of verifying that 6 is a perfect number.
Looking back at the process, refer to 6 as "perfectCandidate". In order to find the factors, we cycled (looped) from 1 to perfectCandidate\2. If the loop control variable, call it "possibleFactor," divided evenly into perfectCandidate, then it was a factor and we added it to an accumulator, called "sum." If it was not a factor we ignored it and moved on.
When we completed our loop (i.e., examined all of the possible factors, and summing those that were factors) we had to test to see if the sum equaled the perfectCandidate. If it did, we found a perfect number.
By thinking of our simple solution in generic terms we have developed an approach to finding perfect numbers
Now you need to extend that algorithm to find X perfect numbers. That is a relatively simple proposition. Modify the above algorithm to increment a counter each time a perfect number is found. Then embed the modified algorithm in a loop that stops when that new counter reaches X.
By breaking an otherwise difficult problem into smaller, solvable problems, and then extending those portions a little at a time, we find that we can, indeed, solve the overall problem quite easily. As you become more experienced you will find that much of this process is performed subconsciously, and the process becomes more automatic.