```
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";
}
}
```

Recommended Topics