views:

304

answers:

4

I coded up a program in C# to find perfect numbers within a certain range as part of a programming challenge . However, I realized it is very slow when calculating perfect numbers upwards of 10000. Are there any methods of optimization that exist for finding perfect numbers? My code is as follows:

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleTest
{
 class Program
 {
  public static List<int> FindDivisors(int inputNo)
  {
   List<int> Divisors = new List<int>();
   for (int i = 1; i<inputNo; i++)
   {
    if (inputNo%i==0)
     Divisors.Add(i);
   }
   return Divisors;
  }

  public static void Main(string[] args)
  { 
   const int limit = 100000;

   List<int> PerfectNumbers = new List<int>();
   List<int> Divisors=new List<int>();
   for (int i=1; i<limit; i++)
   {
    Divisors = FindDivisors(i);
    if (i==Divisors.Sum())
     PerfectNumbers.Add(i);
   }

   Console.Write("Output =");

   for (int i=0; i<PerfectNumbers.Count; i++)
   {
    Console.Write(" {0} ",PerfectNumbers[i]);
   }

   Console.Write("\n\n\nPress any key to continue . . . ");
   Console.ReadKey(true);
  }
 }
} 
+2  A: 

Do perfect numbers change? No. Look here. Surely, they should be calculated once and then stored. In your case, the only results will be

6
28
496
8128

The next one is 33550336. Outside your range.

Daniel Dyson
A: 

One way to solve things like this involves building a huge array in memory of every number, and then crossing numbers out.

SLC
A: 

Use the formula

testPerfect = 2n-1(2n - 1)

to generate possiblities then check wether the number is in fact perfect.

try this for some bedtime reading

Charles Gargent
+1, but note that this wouldn't find any odd perfect numbers (should such numbers exist). Not a problem in this case, though.
balpha
@balpha how did you get the superscript?
Charles Gargent
Look at [the source](http://stackoverflow.com/revisions/40788b8d-f2a9-453d-86e9-08c85410eb39/view-source): `<sup>` is one of the whitelisted HTML tags, but you have to use `<pre>` instead of a 4-space-indent code block, since the latter shows HTML tags literally
balpha
I used that generation formula coupled with a check for number % 9 == 1; :) Thanks!
paradox
+1  A: 

Just the obvious one from me: you don't need to check every divisor. No point looking for divisors past inputNo/2. That cuts down half of the calculations, but this is not an order of magnitude faster.

Joel Goodwin