Friday, September 7, 2012

Break: Calculating perfect numbers

Till now there have been 4 perfect numbers discovered, but it would be also nice to know how to calculate them. The logic is very simple. I will write the logic and code in C++/CLI.
First lets define perfect numbers. Perfect numbers are numbers that are equal to their divisors. For example number 6, its divisors are 1,2,3 (excluding the number itself). 1 + 2 + 3 = 6. There are about 47 perfect numbers discovered till now, the first 4 are very easy to get; the rest go from 8 digits to millions of digits. The logic is very simple, Here is the code:

long count = 1;
for( ; ;)
{
long current = 0;
for(long i = count - 1; i  > 0; i--)
{
if(count % i == 0) // make sure the current number is divisble with the numbers smaller than it
{
 current += i;
}
}
if(current == count)
{
Console::WriteLine(count);
}
count++;
}

No comments:

Post a Comment