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):

1 |
printPerfectNumbers(10000); |

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).

First attempt. Will revise later, I know there is a better way *shudders at loop in loop*.

http://codesnipp.it/php/php-perfect-numbers-first-quicky

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.

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!

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.

@Marta Oops, looks like you’ve only pasted half the function in…

@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!

Not divisible sorry, modulus and stuff.

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.