Search code examples
c++loopsgeneratorfactors

How to make a factor generator of a whole number?


I'm trying to make a factor generator for any number, and I'm starting off with creating something that gathers all numbers of the "num" variable, and adding each number of the "num" variable to another vector numbersOfN, so I can later on divide that by something to get the possible factors.

At the moment I'm stuck on why numbersOfN.size() doesn't work properly as it keeps repeating, could you show me an alternative or a way to quickly fix this?

#include <iostream>
#include <string>
#include <vector>


void getFactors(int num)
{
    int n = num;
    int nofn;
    std::vector<int> factorsOfN(n);
    std::vector<int> numbersOfN(n);
    n = numbersOfN.size();

    for (nofn = 1; nofn <= n; nofn++)
    {
        numbersOfN.push_back(nofn);
        for (int j = 1; j < numbersOfN.size(); j++)
        {
            std::cout << numbersOfN.at(j) << " ";
        }
    }

}

int main()
{
    int num = 32;
    getFactors(num);
}

Solution

  • A much simpler version of what you are after:

    #include <iostream>
    #include <vector>
    
    std::vector<int> getFactors(int num) {
        std::vector<int> factors;
    
        for (int i = 1; i*i <= num; i++) {
            if ((num % i) == 0) {
                factors.push_back(i);
                int j = num / i;
                if (i != j) {
                    factors.push_back(j);
                }
            }           
        }
    
        return factors;
    }
    
    int main() {
        int num = 32;
        std::vector<int> factors = getFactors(num);
        for (int f : factors) {
            std::cout << f << " ";
        }
        std::cout << "\n";
        return 0;
    }