Test whether a number is perfect or not - C++ Data Structure

C++ examples for Data Structure:Algorithm

Introduction

An integer is said to be a perfect number if the sum of its divisors, including 1 (but not the number itself), is equal to the number.

For example, 6 is a perfect number, because 6 = 1 + 2 + 3.

Demo Code

#include <iostream>

bool isPerfect(long);

int main(int argc, const char *argv[]) {
    std::cout << "Perfect number between 1 and 100: " << std::endl;
    for (long i = 1; i <= 100; i++) {
        // print perfect numbers
        if (isPerfect(i)) {
            std::cout << i << ":" << "\t";
            // print divisors
            for (long d = 1; d < i; d++) {
                if (i % d == 0) 
                   std::cout << d << " ";
            }/*from  w  w  w  .ja  v  a2  s .  c  om*/
            std::cout << std::endl;
        }
    }

    std::cout << std::endl;
    return 0;
}
// checks whether n is a perfect number
bool isPerfect(long n) {
    long sum = 0;

    // sum all divisors up to n/2
    for (long i = 1; i <= n / 2; i++) {
        if (n % i == 0) sum += i;
    }

    return sum == n;
}

Result


Related Tutorials