This is a function that will find the factors of a given number for you.
EDIT: Better algorithm using vectors (thanks all at cprog :) )
Find factors
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
manutd 2 Junior Poster
lxXTaCoXxl 26 Posting Whiz in Training
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.