how come a brute force method won't work at least in my case? |
I said it
would work in your case, but that's only because it's a small case like 20 as opposed to a large case like 40. But those kinds of questions are not looking for mindless brute force solutions. What's the use of that? What could you possibly learn? It's not like the answer itself is important.
I modified my code a little to put i as the largest number an unsigned long long could hold |
No you didn't. The largest number an unsigned long long can hold is 2^64 - 1, which is 18446744073709551615. (Using ^ to mean exponentiation instead of it's usual meaning in C++.)
how did you come up with that approximation [of it taking years] |
As you say, it's just an approximation. 2^64 is about 18^18 (18 quintillion). Suppose you had an algorithm/computer that could search a billion (1^9) values per second. 18^18 / 1^9 = 18^9, or 18 billion seconds, which is over 500 years. Even if you could search a trillion a second it would take over 6 months.
how come doing a test for if a number is prime greatly reduces the execution time? |
Because if you THINK about the problem you will see that the answer is obviously made up of the largest number of factors of the primes that occur in all the values up to the limit (20 in your case). I initially just came up with the answer without a program. The largest number of 2's occurs in 16, which is 2^4, so obviously the answer must have 4 2's in it as factors. The largest number of 3's is in 9, which is 2^3. None of the other prime factors can occur more than once since the next prime is 5 and 5^2 is 25, which is already over 20. So the answer is:
2^4 * 3^2 * 5 * 7 * 11 * 13 * 17 * 19 = 232792560.
For 40, we have:
2^5 * 3^3 * 5^2 * 7 * 11 * 13 * 17 * 19 * 23 * 29 * 31 * 37
= 5342931457063200
is there a name for this particular algorithm? |
No. I just made it up. However, it's far from optimal. Kind of crap, really.