usingMaths.com
From Theory to Practice - Math You Can Use.







<< PreviousNext >>

How to find all Factors of a Number in C++



What are Factors? | Maths Explanation for C++ Kids

Factors are the complete set of integers that will divide a particular number without remainder.
Take 36 as an example, it's complete set are:

1, 2, 3, 4, 6, 9, 12, 18, and 36.

Other than prime numbers, every other number has at least one factor - not considering 1 as a factor.
Where there is just one factor, then this factor is the square root of the number in question;
In this guide, we'll explore the math behind factors-of-numbers and walk through how to code a C++ algorithm for listing factors in a simple and fun way.



Code Logic for Factorising Numbers in C++ - Fun Maths Exercise

Actually, we've been doing factors over the last two demonstrations (lessons).

We can implement a C++ algorithm for factorising a number by simply checking for our factors using the square-root of number range.
We'll start from 1 (which is always a factor).
For each found factor, we'll get the corresponding complementary factor by dividing the number (whose factors we are trying to find), by the found factor.
This Math activity and C++ script help primary school students understand factorization by listing all factors of a number.


Create a new C++ class file;
Call it ListFactors.

Type out the adjoining C++ code for listing the factors of any number.



Note: You can comment out the C++ code for the main class from the previous lesson if you have been following.


So! C++ Fun Practice Exercise - List Factors

As a fun practice exercise, feel free to try out your own different numbers, and see how the C++ code lists the factors of those numbers.







C++ Code for List Factors - 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;
};


C++ Code for 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()
{
}

C++ Code for List Factors - 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;
}




<< PreviousNext >>