Created
April 9, 2019 18:50
-
-
Save blrobin2/6fe20d31fae40396e483d43125103762 to your computer and use it in GitHub Desktop.
Pythagorean Triples with MATH
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Function: pythagorean Triples | |
* | |
* How to derive the side_b formula: | |
* - a² + b² = c² | |
* - b² = c² - a² | |
* - 2bc + b² + b² = c² - a² + 2bc + b² | |
* - 2bc + b² + b² = c² + 2bc + b² - a² // Line above reorganized to see simplification | |
* - 2bc + b² + b² = (b + c)² - a² | |
* - 2b² + 2bc = (b + c)² - a² | |
* - 2b(b + c) = (b + c)² - a² | |
* - b = (b + c)² - a² / 2(b + c) | |
*/ | |
const pythagoreanTriples = (sum: number): Set<number[]> => | |
new Set(Array.from({ length: sum / 3 }) | |
.map((_, i: number) => { | |
const side_a = i + 1; | |
const b_plus_c = sum - side_a; | |
const side_b = (b_plus_c ** 2 - side_a ** 2) / (2 * b_plus_c) | 0; | |
const side_c = b_plus_c - side_b; | |
return [ side_a, side_b, side_c ]; | |
}) | |
.filter(([side_a, side_b, side_c]) => | |
side_a < side_b && side_a ** 2 + side_b ** 2 === side_c ** 2)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment