Programming Puzzle 16 - Perfect Numbers ?

This is a bit harder.

Don't work on this while your manager is around.

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.

Instructions:

a) Write an xbasic program to find all four of the perfect numbers.

b) Display your answer in a message box on screen. Show the divisors

for each perfect number, so we can easily check your sums.

c) Post your solution by attaching the "exported" script to your reply here.

d) Have fun.

1 Attachment(s)

Re: Programming Puzzle 16 - Perfect Numbers ?

Professor Cone,

Here is my homework. Not quite as difficult as you suggested. I tried to comment heavily to show my thought process (a scary venture at the best of times). I hope you like my solution. By the way, I had a lot of fun with it, and tried searching up to 100,000, but there are still only four perfect sums. But that took six minutes, as opposed to the 8.5 seconds for up to 10,000. Does that mean 1,000,000 would take 4-5 hours?

Thanks for doing these. I've been trying to think up one myself.

Re: Programming Puzzle 16 - Perfect Numbers ?

Nice bit of code Stephen, my machine must be getting very old, it took 10.688 seconds.

Re: Programming Puzzle 16 - Perfect Numbers ?

Stephen,

very nice!

In developing my own solution I struggled with:

a) figuring out an efficient way to determine the integer divisors of the candidate numbers. I used the MOD() function which I think may be a tiny bit more efficient than your "i/j = int(i/j)" test. Each time through the loop your approach must do two divisions and then the int() function is called. Haven't profiled the code yet, so can't say for sure.

b) my code runs through a far greater number of loops. ( n / 2 )

because I didn't have the wisdom to use the integer root to set the upper limit of the loop counter, nor would I have realized that each divisor has a complementary value that's also a divisor. Your approach is very clever.

c) even better, I struggled with storing my divisors in an array, and then processing the array to get the sum. Very messy. Your use of the eval() function running against the divisors arranged in a simple arithmetic string expression is ingenious!

Prof. Pickypicky is ready to move you to the head of the class!

1 Attachment(s)

Re: Programming Puzzle 16 - Perfect Numbers ?

Prof. Pickypicky,

My script contains two loops each going to 10000. I do believe my answer is correct, however it takes a while to generate the answers. Check it out when you have the time.

Attachment 29072