Created
March 21, 2019 20:07
-
-
Save Mehni/548b57a0d7a3f3b00530d9ab3d728f97 to your computer and use it in GitHub Desktop.
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
using System; | |
using System.Collections.Generic; | |
public static class PythagoreanTriplet | |
{ | |
public static IEnumerable<(int a, int b, int c)> TripletsWithSum(int sum) | |
{ | |
for (int i = 0; i < sum; i++) | |
{ | |
var thing = Triplet(i, sum); | |
if (thing.HasValue) | |
yield return thing.Value; | |
} | |
} | |
public static (int a, int b, int c)? Triplet(int currentIterat, int sum) | |
{ | |
int a = currentIterat; | |
for (int b = a + 1; (a + b) <= sum; b++) | |
{ | |
for (int c = b + 1; (a + b + c) <= sum; c++) | |
{ | |
if (Matches(a, b, c, sum)) | |
return (a, b, c); | |
} | |
} | |
return null; | |
} | |
private static bool Matches(int a, int b, int c, int sum) | |
=> a + b + c == sum | |
&& Math.Pow(a, 2) + Math.Pow(b, 2) == Math.Pow(c, 2); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment