Solving the Lazy Hobo Riddle I would like help in optimizing this calculation, which is from the Lazy Hobo Riddle:


  There once were 4 hoboes travelling across the country.  During their
  journey, they ran short on funds, so they stopped at a farm to look
  for some work.  The farmer said there were 200 hours of work that
  could be done over the next several weeks.  The farmer went on to say
  that how they divided up the work was up to them.  The hoboes agreed
  to start the next day.
  
  The following morning, one of the hoboes - who was markedly smarter
  and lazier than the other 3 - said there was no reason for them all to
  do the same amount of work.  This hobo went on to suggest the
  following scheme:
  
  
  The hoboes would all draw straws.
  A straw would be marked with a number.
  The number would indicate both the number of days the drawer must work and the number of hours to be worked on each of those days.  For
  example, if the straw was marked with a 3, the hobo who drew it would
  work 3 hours a day for 3 days.
  
  
  It goes without saying that the lazy hobo convinced the others to
  agree to this scheme and that through sleight of hand, the lazy hobo
  drew the best straw.
  
  The riddle is to determine the possible ways to divide up the work
  according to the preceding scheme.


It basically just involves finding all possible solutions of \$a,b,c,d\$ such that \$a^{2} + b^{2} + c^{2} + d^{2} = 200 \$

for(int a = 1;a&lt;=100; a++)
    for(int b = 1; b&lt;=100; b++)
        for(int c = 1; c&lt;=100; c++)
            for(int d = 1; d&lt;=100; d++){
                ++counter;
                if(a*a + b*b + c*c + d*d == 200)
                    cout &lt;&lt; "a: " &lt;&lt; a &lt;&lt; " b: " &lt;&lt; b &lt;&lt; " c: " &lt;&lt; c &lt;&lt; " d: " &lt;&lt; d &lt;&lt; endl;
            }
Notice how the square of a number 15 or greater exceeds 200? What you can do, is set the interval from 1 to 14.
There is no advantage in evaluating the same combination over and over again. Realize that the most efficient way is to structure your for loops such that 

$$ a  \leq b  \leq c  \leq d $$

In your attempt, you are iterating 38,416 times!

By limiting the interval, you iterate just 2380 times! 

One more thing you can do: check and break when \$a^{2} + b^{2} + c^{2} + d^{2} &gt; 200 \$

for(int a = 1; a&lt;=14; a++)
    for(int b = a; b&lt;=14; b++)
        for(int c = b; c&lt;=14; c++)
            for(int d = c; d&lt;=14; d++){
                if(a*a + b*b + c*c + d*d == 200)
                    cout &lt;&lt; "a: " &lt;&lt; a &lt;&lt; " b: " &lt;&lt; b &lt;&lt; " c: " &lt;&lt; c &lt;&lt; " d: " &lt;&lt; d &lt;&lt; endl;
                else if(a*a + b*b + c*c + d*d &gt; 200)
                    break;
            }


Now you iterate only 1,214 times! This is way more efficient.