How to check whether a number is a perfect number in C++

2 Answers

0 votes
// If the sum of all factors of a number is equal to the number, then the number is perfect
  
// 6
// factors = 1, 2, 3
// 1 + 2 + 3 = 6

#include <iostream>

int main() {
    int num = 6;
    int sumOfFactors = 0;
  
    for (int i = 1; i < num; i++)
        if (num % i == 0)
            sumOfFactors += i;
  
    if (sumOfFactors == num)
        std::cout << "Perfect Number";
    else
        std::cout << "Not a Perfect Number";
}



 
 
/*
run:
 
Perfect Number
 
*/

 



answered Oct 27, 2021 by avibootz
0 votes
// If the sum of all factors of a number is equal to the number, then the number is perfect
  
// Factors of a number are numbers that divide the number evenly
     
// 6
// factors = 1, 2, 3
// 1 + 2 + 3 = 6

#include <iostream>
#include <cmath>

bool isPerfect(int n) {
    if (n < 2) return false;

    int sum = 1;
    int limit = sqrt(n);

    for (int i = 2; i <= limit; i++) {
        if (n % i == 0) {
            sum += i;
            int pair = n / i;
            if (pair != i) sum += pair;
        }
    }

    return sum == n;
}

int main() {
    std::cout << "Perfect numbers up to 10,000:" << std::endl;
    for (int i = 1; i <= 10000; i++) {
        if (isPerfect(i)) {
            std::cout << i << std::endl;
        }
    }
}


/*
run:

Perfect numbers up to 10,000:
6
28
496
8128

*/

 



answered 6 days ago by avibootz
...