Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) IsPerfectNumber

 

IsPerfectNumber is a math code snippet to determine if a number is perfect.

 

#include <cassert>
//---------------------------------------------------------------------------
///GetSumProperDivisors returns the sum of all proper divisors of x
///From http://www.richelbilderbeek.nl/CppGetSumProperDivisors.htm
int GetSumProperDivisors(const int x)
{
  assert(x > 0);
  int sum = 0;
  const int j = (x / 2) + 1;
  for (int i=1; i!=j; ++i)
  {
    //Is i a proper divisor of x?
    if (x % i == 0)
    {
      sum+=i;
    }
  }
  return sum;
}
//---------------------------------------------------------------------------
///IsPerfectNumber determines if x is a perfect number
///From http://www.richelbilderbeek.nl/CppIsPerfectNumber.htm
bool IsPerfectNumber(const int x)
{
  return (GetSumProperDivisors(x) == x);
}
//---------------------------------------------------------------------------
int main()
{
  assert(!IsPerfectNumber( 1));
  assert(!IsPerfectNumber( 2));
  assert(!IsPerfectNumber( 3));
  assert(!IsPerfectNumber( 4));
  assert(!IsPerfectNumber( 5));
  assert( IsPerfectNumber( 6));
  assert(!IsPerfectNumber( 7));
  assert(!IsPerfectNumber( 8));
  assert(!IsPerfectNumber( 9));
  assert(!IsPerfectNumber(10));
  assert(!IsPerfectNumber(11));
  assert(!IsPerfectNumber(12));
  assert(!IsPerfectNumber(13));
  assert(!IsPerfectNumber(14));
  assert(!IsPerfectNumber(15));
  assert(!IsPerfectNumber(16));
  assert(!IsPerfectNumber(17));
  assert(!IsPerfectNumber(18));
  assert(!IsPerfectNumber(19));
  assert(!IsPerfectNumber(20));
  assert(!IsPerfectNumber(21));
  assert(!IsPerfectNumber(22));
  assert(!IsPerfectNumber(23));
  assert(!IsPerfectNumber(24));
  assert(!IsPerfectNumber(25));
  assert(!IsPerfectNumber(26));
  assert(!IsPerfectNumber(27));
  assert( IsPerfectNumber(28));
  assert(!IsPerfectNumber(29));
  assert(!IsPerfectNumber(30));
  assert(!IsPerfectNumber(31));
  assert(!IsPerfectNumber(32));
  assert(!IsPerfectNumber(33));
  assert(!IsPerfectNumber(34));
  assert(!IsPerfectNumber(35));
  assert(!IsPerfectNumber(36));
}

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict