Our List Factors code in C++.
List Factors Class Header File:
#pragma once
#include <iostream>
#include <math.h>
#include <algorithm>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
class ListFactors {
public:
ListFactors(unsigned);
virtual ~ListFactors();
string doBusiness();
private:
vector<unsigned> found_factors;
unsigned int find_my_factors;
unsigned int sqrt_range; // Use this range for our loop
string result;
stringstream aux;
};
List Factors Class File:
#include "stdafx.h"
#include "ListFactors.h"
ListFactors::ListFactors(unsigned candidate) {
found_factors = { 1, candidate };
find_my_factors = candidate;
sqrt_range = (int)ceil(sqrt(find_my_factors));
result = "The factors of ";
}
/**
* Does the main job of finding the requested factors.
*/
string ListFactors::doBusiness() {
/* Loop through 1 to 'find_my_factors' and test for divisibility. */
for (int i = 2; i < sqrt_range; i++) {
if ((find_my_factors % i) == 0) {
found_factors.push_back(i);
/* Get the complementing factor by dividing 'find_my_factor' by variable i. */
found_factors.push_back(find_my_factors / i);
}
}
found_factors.shrink_to_fit();
// Sort the array in ascending order; Not entirely necessary.
sort(found_factors.begin(), found_factors.end());
aux << find_my_factors;
result += aux.str() + " are: \n";
for (unsigned factor : found_factors) {
aux.str("");
aux << factor;
result += aux.str() + "; ";
}
return result;
}
ListFactors::~ListFactors()
{
}
Main Class:
// Arithmetic.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "ListFactors.h"
#include <iostream>
using namespace std;
int main() {
try {
cout << "\n Welcome to our demonstration sequels\n";
cout << "Hope you enjoy (and follow) the lessons.\n\n";
unsigned int start = 1, stop = 100;
/*
* Factors of a number.
*/
ListFactors f_list(48);
cout << "\n\n" << f_list.doBusiness() << "\n";
} catch (exception& e) {
cout << "\n" << e.what() << "\n";
}
return 0;
}
Try it out!
Elegance (0.0)