C++ Solution for ProjectEuler Problem #5 What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?

Is there a more elegant solution in C++?

#include &lt;iostream&gt;
using namespace std;

int main(){
    long long num = 1;
    int divMin = 1;
    int divMax = 20;
    int tempDivMax = divMax;

    while(true){
        if(num % tempDivMax == 0)
        {
            tempDivMax--;
            if(tempDivMax == divMin){
                cout &lt;&lt; num &lt;&lt; endl;
                break;
            }
        }else{
            tempDivMax = divMax;
            num++;
        }
    }
    return 0;
}
Code review

To start with, some points about your code:


using namespace std; is something I consider a code smell. It doesn't save much time and I find it clearer to see exactly where cout etc. are coming from. Additionally, it clutters your namespace although I myself haven't run into name collisions with the STL being an issue before.
It looks like your condition to exit the while loop is tempDivMax == divMin. Use this rather than while (true) to make it clearer what behaviour is intended.
You are also performing two iterations inside a single loop: num is being incremented from 1 until it succeeds and tempDivMax is being decremented until it equals divMin. Split these into separate loops! The code will be clearer to read and will be just as fast. The outer loop I would turn completely into a for loop for (; tempDivMax != divMin; ++num) { ... } and but the inner one I would make a while loop while (tempDivMax &gt; divMin &amp;&amp; num % tempDivMax == 0) { ... } since the long condition expression makes for some rough reading when condensed into a for loop.
Finally, define your constants before your working variables and declare them as const. I would even do this outside of the main function.


This leaves you with:

#include &lt;iostream&gt;

const int DIV_MIN = 1;
const int DIV_MAX = 20;

int main() {
    long long num = 1;
    int tempDivMax = DIV_MAX;
    for (; tempDivMax &gt; DIV_MIN; ++num) {
        tempDivMax = DIV_MAX;
        while (tempDivMax &gt; DIV_MIN &amp;&amp; num % tempDivMax == 0) {
            --tempDivMax;
        }
    }

    std::cout &lt;&lt; num &lt;&lt; std::endl;
    return 0;
}


A "more elegant" solution...

== Obligatory code below is untested ==

I'd imagine they're looking for something like this?

For something to be divisible by a number, it must have at least that number's prime factors. Furthermore, in any given number below 20, there can be a maximum of $$\lfloor{log_p(20)}\rfloor$$ copies of the prime factor $$p$$

The following snippet calculates the product of these.

#include &lt;iostream&gt;

const int DIV_MAX = 20;
const int[] PRIMES = {2, 3, 5, 7, 11, 13, 17};

int main() {
  int result = 1;
  for (int p : PRIMES) {
    int tmp = 1;
    while (tmp &lt; DIV_MAX) tmp *= p;
    result *= tmp;
  }

  std::cout &lt;&lt; result &lt;&lt; std::endl;
  return 0;
}