The Program in C++ Program to Find Perfect numbers between Two Given Numbers is given below:
#include <iostream>
using namespace std;
bool isPerfect(int num) {
int i, sum = 0;
for (i = 1; i <= num/2; i++) {
if (num % i == 0) {
sum += i;
}
}
return (sum == num);
}
int main() {
int start, end, i;
cout<<"Hello Codeauri Family, enter the two numbers here to find the perfect numbers between them;\n";
cout << "Enter start of range: ";
cin >> start;
cout << "Enter end of range: ";
cin >> end;
cout << "Okay, the Perfect numbers between " << start << " and " << end << " are: " << endl;
for (i = start; i <= end; i++) {
if (isPerfect(i)) {
cout << i << endl;
}
}
return 0;
}
Output:
Hello Codeauri Family, enter the two numbers here to find the perfect numbers between them;
Enter start of range: 1
Enter end of range: 1000
Okay, the Perfect numbers between 1 and 1000 are:
6
28
496
Pro-Tips💡
In this program, we first define a helper function isPerfect
which takes an integer num
as input and returns true
if num
is a perfect number and false
otherwise.
The isPerfect
function uses the same logic as in the previous program to find the sum of the divisors of num
and compare it with num
.
The main
function prompts the user to enter the start and end of the range, and then uses a for loop to iterate through the range,
checking if each number is a perfect number by calling the isPerfect
function. If a number is a perfect number, it is printed to the screen.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.