Header Logo
Forum Index >> General >> The Culture Forum
- [C++] Perfect Numbers.

[C++] Perfect Numbers.

24th March 2010, 23:06

DY357LX

[C++] Perfect Numbers.

One of the things mentioned at Saturdays Dave Gorman show was his brief stint at Uni where his studied maths and attempted to find "Perfect Numbers".

Basically a Perfect Number is a number that, once divided, is the sum of it's parts.

For example, 6.
6 is can be divided by 1, 2 and 3. 1+2+3=6 making it Perfect.

He then continued with his story... and I was left thinking "I wonder if I can adapt my C++ Prime Number program to calculate Perfect Numbers".

After some arsing about I managed it.

Code:
#include <iostream>
using namespace std;

int main()
{
unsigned int n = 400000000, sum = 0;

cout << "Seaching for Perfect Numbers" << endl;

for(int num = 1; num <= n; num++)
{
sum = 0;
for(int i = 1; i < num; i++)
{
if(!(num%i))
{
sum+=i;
}
}

if(sum == num)
{
cout << num << " is a perfect number!" << endl;
}
}

return 0;
}


The program runs and after 1-5 seconds it tells us that 6, 28, 496 and 8128 are Perfect Numbers... then things go a little quiet.
I thought my initial code was wrong but it turns out that the next number in the sequence is 33550336 so it's just taking a while to calculate.

After a little Google'ing I find that there are only 37 known Perfect Numbers. The last person to find one was rewarded $100,000. (I assume, that like Prime Numbers, these numbers are later used in encryption algorithms and the like.)

Now I need to adapt the code to spit out the sum when a Perfect Number is found.
I think I'll need some hefty arrays for that. :-/

FUN!
"And so is the Golden City blackened With each step you take in my Hall. Marvel at perfection, for it is fleeting. You have brought Sin to Heaven And doom upon all the world."

25th March 2010, 10:26

Chez

[C++] Perfect Numbers.

I'd be willing to offer you some CPU cycles in exchange for a small chunk of the reward Wink
The aim of all life is death.
Email notifications on this thread