15 Jul 2024 - Syed Muhammad Shahrukh Hussain
Write a program which find perfect number between [1-1000]. A perfect number is a number which equals to the sum of its divisors.
number :6 divisor:1
number :6 divisor:2
number :6 divisor:3
6 is perfect
number :28 divisor:1
number :28 divisor:2
number :28 divisor:4
number :28 divisor:7
number :28 divisor:14
28 is perfect
number :496 divisor:1
number :496 divisor:2
number :496 divisor:4
number :496 divisor:8
number :496 divisor:16
number :496 divisor:31
number :496 divisor:62
number :496 divisor:124
number :496 divisor:248
496 is perfect
#include <iostream>
using namespace std;
int isPerfect(int number);
int main() {
for (int i = 1; i <= 1000; i++) {
if (isPerfect(i)) {
cout << i << " is perfect" << endl;
}
}
return 0;
}
int isPerfect(int number) {
int sum = 0;
for (int i = 1; i < number; i++) {
if ( 0 == number % i ) {
sum += i;
}
}
if (sum == number) {
// print divisors of perfect no's.
for (int i = 1; i < number; i++) {
if ( 0 == number % i ) {
cout << "number :" << number << " divisor:" << i << endl;
}
}
return 1;
} else {
return 0;
}
}