Write a program that prints perfect numbers PCOD

This is the first in a new series of posts that I will regularly write to give you a little challenge to do. Today’s programming challenge of the day (PCOD) is to create a program that prints perfect numbers.

A perfect number is an integer that is equal to the sum of it’s divisors (excluding itself). An example perfect number is 6. 6 can be cleanly divided by 1, 2 and 3. 1 + 2 + 3 = 6. Therefore 6 is a perfect number.

The program should expose a single function that takes a single argument (the argument is a integer equal to the maximum number of times the program will loop over increasing integers to find the perfect numbers):

You can write your program in any language of your choosing. Post your answer in the comments. The most elegant solution will receive my appreciation (no prizes sorry).


10 thoughts on “Write a program that prints perfect numbers PCOD

  1. My solution. Could be much shorter by not breaking down the actions and just issuing 3 for loops as James did. I did this in JavaScript, but feel free to have a go in your own language of choice.

  2. I only have two for loops ;) although they obviously grow exponentially. My current solution is VERY slow compared to what it should be.

    My thought for a better solution is to generate a range() of numbers between 1 and the given number. That’s as far as I’ve got. Pretty busy today!

  3. Agreed, on the range – but then I didn’t know where to go after range. It made sense in my head, but you still have to loop through each number twice to get the devisors :-S .. I will have another crack at this.

  4. @Jonathan since range gives you am array back, you could array_walk each element. The only problem is, you need a loop around/inside (I can’t work that out yet), to check if it’s divisible by the factor etc. Urgh!

  5. So I was thinking about this earlier. You could use the SPL ArrayIterator class to create an object that you can iterate through, using the class functions to get the actual number etc. Not sure if this is any faster (using SPL) but I’d imagine it to be a tidy solution.

Leave a Reply