Say I have a number, I can find all the prime factors that make up that number. For instance, 6000 is 2^4 * 3 * 5^3.
If I have a number that doesn't factorize well (given a list of acceptable primes), how can I find the next closest number? For instance, given the number 5917, what is the closest number that factors with the list of primes 2, 3, 5, 7? Which is 6000 in this example.
I have something that will brute force find the answer, but there has to be a more elegant solution.
const UInt32 num = 5917;
const CVector<UInt32> primes = { 2, 3, 5, 7 };
const size_t size = primes.size();
UInt32 x = num;
while (x < num * 2)
{
const UInt32 y = x;
for(size_t i = 0; i < size && x > 1; ++i)
{
while(x % primes[i] == 0)
{
x /= primes[i];
}
}
if (x == 1)
{
cout << "Found " << y << endl;
break;
}
else
{
x = y + 1;
}
}
EDIT
I created a test that used the brute force method and the 3 methods provided as answers and got somewhat surprising results. All 4 versions produce correct answers (so thanks for your contributions), however, the brute force method seemed to be the fastest, by an order of magnitude. I tried on a few different systems, compilers, and architectures which all yielded mostly consistent results.
The test code can be found here: http://ideone.com/HAgDsF. Please feel free to make suggestions.