C++ Exercises: Find Perfect numbers and number of Perfect numbers between 1 to 1000
C++ Numbers: Exercise-5 with Solution
Write a program in C++ to find Perfect numbers and the number of Perfect numbers between 1 and 1000.
Visual Presentation:
Sample Solution:
C++ Code :
# include <iostream> // Include necessary libraries
# include <string>
using namespace std;
int main()
{
int i = 1, u = 1, sum = 0, ctr = 0; // Initialize variables i, u, sum, and ctr
cout << "\n\n Find the Perfect numbers and number of Perfect numbers between 1 to 1000:\n"; // Display message for user
cout << "------------------------------------------------------------------------------\n";
cout << "The Perfect numbers are : \n"; // Display message for user
while (i <= 1000) // Loop through numbers from 1 to 1000
{
while (u <= 1000) // Nested loop to find divisors of i
{
if (u < i) // Check if u is less than i
{
if (i % u == 0) // Check if u is a divisor of i
sum = sum + u; // Add u to the sum if it's a divisor of i
}
u++; // Increment u by 1 in each iteration
}
if (sum == i) // Check if the sum of divisors is equal to i
{
ctr++; // Increment the counter if the number is perfect
cout << i << " is a Perfect number." << "\n"; // Display if i is a Perfect number
}
i++; // Move to the next number
u = 1; // Reset u to 1 for the next iteration
sum = 0; // Reset sum for the next iteration
}
cout << "Number of Perfect numbers between 1 to 1000 is: " << ctr << "\n"; // Display the count of Perfect numbers
}
Sample Output:
Find the Perfect numbers and number of Perfect numbers between 1 to 1000: ------------------------------------------------------------------------------ The Perfect numbers are : 6 is a perfect number. 28 is a perfect number. 496 is a perfect number. Number of perfect numbers between 1 to 1000 is: 3
Flowchart:
C++ Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a program in C++ to check whether a given number is Perfect or not.
Next: Write a program in C++ to check whether a given number is Deficient or not.
What is the difficulty level of this exercise?
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/cpp-exercises/numbers/cpp-numbers-exercise-5.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics