Search code examples
c++perfect-numbers

How to find all perfect numbers in specific interval in c++?


I want to find all perfect numbers from interval x to y. Any help how can I do that ?


Solution

  • Here is a simple solution, it's not very fast, just an example to understand how perfect numbers work.

    #include <iostream>
    
    using namespace std;
    
    int main()
    {
        int x, y;
        int sum_del;
        cin >> x >> y;
        for(int i = x; i <= y; i++){
    
            sum_del = 0;
    
            for (int j = 1; j <= i/2; j++){
                if (i % j == 0)
                    sum_del += j;
            }
    
            if (sum_del == i)
                cout << i << endl;
    
        }
        return 0;
    }