Find factors

manutd 0 Tallied Votes 178 Views Share

This is a function that will find the factors of a given number for you.
EDIT: Better algorithm using vectors (thanks all at cprog :) )

template <typename T>                                               //Any type.
void findfactors(T n)
{
    // 1 is a factor of any positive integer
    vector<T> factors(1, 1);
    // warning: assumes T can be correctly casted to double and vice-versa
    T max = static_cast<T>(sqrt(n));

    // begin finding factors
    if (n % 2 == 0)
    {
        // n is even
        factors.push_back(2);
        for (T factor = 3; factor <= max; ++factor)
        {
            if (n % factor == 0)
            {
                factors.push_back(factor);
            }
        }
    }
    else
    {
        // n is odd, so it has no even factors
        for (T factor = 3; factor <= max; factor += 2)
        {
            if (n % factor == 0)
            {
                factors.push_back(factor);
            }
        }
    }

    // print factors to out
    for (typename vector<T>::iterator i = factors.begin();
        i != factors.end(); ++i)
    {
        cout << *i << " * " << (n / *i) << "\n";
    }
}
~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster
T arraynums[n] ;
arraynums[n] = n ; // dont you think its out of bounds error.

Please make sure your code works before you post it in the code snippets section. In future code snippets which dont compile will be deleted.

manutd 2 Junior Poster

It will compile and work, at least for me. [n] and [n-1] in that section produce the same output for me. I'm using wxDev-C++.
EDIT: In fact, this causes it to output n (1) twice, which is incorrect.

lxXTaCoXxl 26 Posting Whiz in Training

How should you call it? I'm used to just standard calling:

if ( commandCatche == avg )
			{
				averageCalculator();
			}

			if ( commandCatche == ftmt )
			{
				feet2meters();
			}

			if ( commandCatche == palin )
			{
				palindrome();
			}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.