# Desperately seeking Pythagoras

Also known as Project Euler problem 39:

If p is the perimeter of a right angle triangle with integral length sides, {a,b,c}, there are exactly three solutions for p = 120.

{20,48,52}, {24,45,51}, {30,40,50}

For which value of p ≤ 1000, is the number of solutions maximised?

My first thought here was to generate an iterable collection of right angled triangles and accumulate a count of triangles by perimeter size. Don’t try this – it is far too slow an approach.

So my second thought was to try and iterate over the perimeter sizes and calculate the number of right angle triangles for each. It’s a long time since I had to think about Pythagoras but, for a triangle with sides `a`, `b` and `c` and a perimeter of `p`, I can make the following two statements:

`a + b + c = p`
`a^2 + b^2 = c^2`

Based on the second statement, above, I can also assert:
`c = sqrt(a^2 + b^2)`

Also:
`c = p - a - b`

Which means:
`a^2 + b^2 = (p - a - b)^2`

This can be expanded and simplified to state:
`0 = pp - 2pb - 2ap + 2ab`

or:

`b = p(p - 2a) / 2(p - a)`

Using this formula, we can say that for any values of `p` and `a` where `p > a`, if `b` is an integer then we have a right angle triangle.

One further optimisation: Intuitively, `a` can’t be greater than `p/3`.

Implementing this can then be done with two very simple `for` loops. The outer one iterates over all values of `p` and the inner one iterates over the range `(2, int(p / 3))` and counts the number of integer values of `b`.
{"ft_lang_label":"__label__en","ft_lang_prob":0.860419,"math_prob":0.99810296,"size":1438,"snap":"2021-43-2021-49","text_gpt3_token_len":414,"char_repetition_ratio":0.10878661,"word_repetition_ratio":0.0,"special_character_ratio":0.30458972,"punctuation_ratio":0.11890244,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9995011,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2021-10-18T10:48:01Z\",\"WARC-Record-ID\":\"<urn:uuid:a226ab31-dc90-4247-83ac-b877767fd223>\",\"Content-Length\":\"89463\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:3a4cc929-611e-4320-bd76-eb73c4d71fa3>\",\"WARC-Concurrent-To\":\"<urn:uuid:4d04dd93-2997-431d-821c-950af1c316d1>\",\"WARC-IP-Address\":\"192.0.78.30\",\"WARC-Target-URI\":\"https://blog.lightlyseared.online/2012/11/22/desperately-seeking-pythagoras/\",\"WARC-Payload-Digest\":\"sha1:AJEGQLYALCMPCPISMFBBRIJNUYFLEEZ4\",\"WARC-Block-Digest\":\"sha1:D77FLY4CCDMYOAYSVYT2ZBHSHJZ3VM7A\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2021/CC-MAIN-2021-43/CC-MAIN-2021-43_segments_1634323585201.94_warc_CC-MAIN-20211018093606-20211018123606-00226.warc.gz\"}"}