Let me suggest that brute force is NEVER the good way to solve a project Euler problem. NEVER. When brute force is applied, most of brute froce codes you would write would still be running long after both you and your computer are piles of dust. (Ok, I'll admit that the Sudoku PE problem was doable by me merely solving each sudoku puzzle by hand, then computing a result. That was ok, since I like doing sudoku puzzles. But that was one of the very, very few PE problems I solved on paper, and I recall having solved around 300 of them almost entirely in MATLAB.) I will comcede that this problem is probably doable via brute force, as a pretty low numbered problem. But that still makes it a poor choice of method.
Instead, start with the Euclidean formula for Pythagorean triples. ALWAYS do some reading and thinking BEFORE you try to write code for a PE problem.
In there, you will learn how to represent all Pythagorean triples as the triple:
{a,b,c} = {k*(m^2-n^2), 2*k*m*n, k*(m^2+n*2)}
In that formula, we know that m>n is necessary. What do you know about the desired triples? Their sum must be 1000, What can you get from that formula?
a+b+c == 2*k*m*2 + 2*k*m*n == 2*k*m*(m+n) == 1000
Now look for all such values of k,m,n, where m>n, such that the produt holds. It looks like solution for a sum as small as 1000 can be done using pencil and paper. And since they tell you that only one solution exists, you can do it via some pretty fast trial and error, just by looking at the factor pairs of a number.
factor(1000)
ans =
2 2 2 5 5 5
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
We know that one of those factors of 2 is already taken.
factorpairs = @(N) [divisors(N)',N./divisors(N)'];
First, suppose k is 1, then we can find M and N
fp = factorpairs(500)
fp =
1 500
2 250
4 125
5 100
10 50
20 25
25 20
50 10
100 5
125 4
250 2
500 1
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
Each such pair of factors would imply a value for m and n. Remembering that m>n is a requirement for the Euclid formula to work, we might do this:
mnsolve = @(fp) [fp(:,1), fp(:,2) - fp(:,1)];
mnsolve(fp)
ans =
1 499
2 248
4 121
5 95
10 40
20 5
25 -5
50 -40
100 -95
125 -121
250 -248
500 -499
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
And when k==1, only one such pair seems to yield a viable pythagorean triple.from that set. (Remember the rules about m and n. They must be both positive, and must have m>n.) You might decide to test it to see if that pair indeed satisfies your needs.
triplefun = @(k,m,n) k.*[m.^2-n.^2, 2*m.*n, m.^2+n.^2)];
Now you could try it again for k=2, which would require the factor pairs of 250.
Honestly, I don't recall my solution method for this problem, but I would guess I did something fairly simple like this. I could look it up, since I think I saved the MATLAB codes for all of those PE problems.