0

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";
    }
}
3
Contributors
3
Replies
4
Views
11 Years
Discussion Span
Last Post by lxXTaCoXxl
0
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.

0

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.

0

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

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

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

			if ( commandCatche == palin )
			{
				palindrome();
			}
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.