Once again, the challenge for this month’s exercise is to unravel a math puzzle. This time, the puzzle reads like this:
Find all positive values a+b+c+d = 36. Then determine which is the largest value generated for ab+bc+cd?
My first approach was to figure all the permutations of four values that add up to 36. In other words, not to repeat any already-tested combinations. Such code would be delightful, but also a pain. No, my solution was just to brute-force it with a series of for loops and then a “max” test for results that total to 36:
2026_03-Exercise.c
#include <stdio.h>
int main()
{
int a,b,c,d,max;
max = 0;
for( a=0; a<36; a++ )
for( b=0; b<36; b++ )
for( c=0; c<36; c++ )
for( d=0; d<36; d++ )
if( a+b+c+d == 36 )
if( (a*b)+(b*c)+(c*d) > max )
max = (a*b)+(b*c)+(c*d);
printf("%d\n",max);
return 0;
}
Nested for loops cycle variables a, b, c, and d from 0 through 35. This approach is very brute-forcey, but it works.
An if statement tests to see whether the accumulated values total to 36:
if( a+b+c+d == 36 )
When true, a second if statement calculates the value of ab+bc+cd and compares it with the current value of variable max:
if( (a*b)+(b*c)+(c*d) > max )
When the value calculated is greater than max, the value of max is reset:
max = (a*b)+(b*c)+(c*d);
After running through all the possibilities, the value of max represents the largest value calculated, which is 324.
I just recognized that this code consists of three, not two statements as I wrote in the original post. The first statement initializes variable max. But the nested for loops and their if tests are all a single statement:
for( a=0; a<36; a++ )
for( b=0; b<36; b++ )
for( c=0; c<36; c++ )
for( d=0; d<36; d++ )
if( a+b+c+d == 36 )
if( (a*b)+(b*c)+(c*d) > max )
max = (a*b)+(b*c)+(c*d);
There’s only a single semicolon in the stack, which makes it all a single statement.
The final statement is the printf() to output the result.
I hope that your solution met with success. As I wrote above, it would be more efficient to work through the values and avoid repeating already tested results. But the brute force method works and the code runs just as fast. Still, I may attempt to address non-repeating solutions in a future lesson.