Hello,

I'm trying to print out on the screen the the sum of a perfect number, and i can't quite figure it out how to code it. For example I now 6 is a perfect number so i need [ 6= 1+2+3 ] to print out on the screen. Any help would be much appreciated

Dani AI

Generated

A short, practical plan to print the decomposition you asked for and to tell whether a number is perfect (building on ’s definition and ’s pointer).

Find the proper divisors (exclude the number itself) efficiently by iterating i from 2 to sqrt(n). When i divides n, add i and n/i (but only add the pair once when i*i == n). Always include 1 for n > 1. After collecting divisors, sort them, compute their sum, and compare to n. If equal, print the formatted string n = d1 + d2 + ...; otherwise report that n is not perfect.

Example C++ helper functions:

#include <iostream>
#include <vector>
#include <algorithm>

std::vector<long long> proper_divisors(long long n) {
    std::vector<long long> d;
    if (n <= 1) return d;
    d.push_back(1);
    for (long long i = 2; i * i <= n; ++i) {
        if (n % i == 0) {
            d.push_back(i);
            long long j = n / i;
            if (j != i) d.push_back(j);
        }
    }
    std::sort(d.begin(), d.end());
    return d;
}

// Use this to print "n = 1 + 2 + 3" when n is perfect
void print_decomposition(long long n) {
    auto d = proper_divisors(n);
    long long sum = 0;
    for (auto v : d) sum += v;
    if (sum == n && !d.empty()) {
        std::cout << n << " = ";
        for (size_t k = 0; k < d.size(); ++k) {
            if (k) std::cout << " + ";
            std::cout << d[k];
        }
        std::cout << '\n';
    } else {
        std::cout << n << " is not a perfect number\n";
    }
}

Notes and pitfalls: this runs in O(sqrt(n)) for one n (plus sorting). If checking many values, generate even perfect numbers via the Euclid–Euler route: for prime p where 2^p-1 is a Mersenne prime, n = 2^(p-1)*(2^p-1) is perfect. Odd perfect numbers have never been found. Watch integer overflow for large n (use 64-bit or a big-integer library if needed). Common bugs: accidentally including n itself, double-counting the sqrt when n is a square, or forgetting to include 1 for n>1.

Recommended Answers

All 2 Replies

Start by defining what a perfect number is. Is a perfect number one that equals the sum of it's factors other than itself? If so, then determine all the factors of the number, arrange them in ascending order, and add all but the largest one together. If that sum is the same as the largest factor (that is the same as the number itself) then the number is perfect.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.