Write a C++ program that displays all the factors of a given integer entered by the user.
Input and Output Examples
- Input: 12
Output: Factors of 12 are: 1, 2, 3, 4, 6, 12. - Input: 20
Output: Factors of 20 are: 1, 2, 4, 5, 10, 20.
Algorithm:
- Start the Program: Include necessary headers and declare the use of the standard namespace.
- Prompt for Input: Ask the user to enter an integer.
- Read the Input: Store the integer in a variable.
- Find Factors: Use a method to find all the factors of the number.
- Display the Output: Print all the factors of the number.
- End the Program: Finish execution cleanly.
C++ Programs with Different Methods to Display Factors
Method 1: Using a Loop
This method uses a loop to iterate from 1 to the given number and checks if each number divides the given number evenly.
#include <iostream>
using namespace std;
int main() {
int num; // Declare a variable to store the input number.
cout << "Enter an integer: ";
cin >> num;
cout << "Factors of " << num << " are: "; // Display the message for factors.
// Find factors using a loop
for (int i = 1; i <= num; ++i) {
if (num % i == 0) {
cout << i << ", "; // Output if i is a factor of num.
}
}
cout << endl; // Move to the next line.
return 0; // End the program successfully.
}
Method 2: Optimized Loop
This method optimizes the loop by iterating only up to the square root of the given number, which reduces the number of iterations.
#include <iostream>
#include <cmath> // Include the library for mathematical functions.
using namespace std;
int main() {
int num;
cout << "Enter an integer: ";
cin >> num;
cout << "Factors of " << num << " are: ";
int sqrtNum = sqrt(num); // Calculate the square root of the number.
// Find factors using an optimized loop
for (int i = 1; i <= sqrtNum; ++i) {
if (num % i == 0) {
cout << i << ", "; // Output if i is a factor of num.
if (num / i != i) {
cout << num / i << ", "; // Output the corresponding factor.
}
}
}
cout << endl;
return 0;
}
Practice Problem
Write a C++ program to find and display the sum of all the factors of a given number.