Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding perfect numbers (optimization)

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);
  }
 }
} 
like image 318
paradox Avatar asked Apr 16 '10 08:04

paradox


People also ask

What is the formula for finding perfect numbers?

“Perfect numbers” are equal to the sum of their “proper” divisors (positive integers that divide a number evenly, not counting itself). For example, 6 = 3 + 2 + 1, and 28 = 14 + 7 + 4 + 2 + 1.

How do you find the perfect number between two numbers?

In child loop we modulate parent loop value with child loop value. If value is equal to zero then add that value in sum variable. After child loop completes, check if sum value and parent loop value both are equal or not. If both values are equal then this number is a perfect number.

How do you find a perfect number in C++?

Perfect Number in C++A number is said to be a Perfect Number when that is equal to the sum of all its positive divisors except itself. The number n will be in range 1^8. So, if the input is like 28, then the output will be True, as its sum of divisors − 1 + 2 + 4 + 7+ 14 = 28.


1 Answers

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

like image 154
Charles Gargent Avatar answered Oct 03 '22 05:10

Charles Gargent