Skip to content

Instantly share code, notes, and snippets.

@Mehni
Created March 21, 2019 20:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Mehni/548b57a0d7a3f3b00530d9ab3d728f97 to your computer and use it in GitHub Desktop.
Save Mehni/548b57a0d7a3f3b00530d9ab3d728f97 to your computer and use it in GitHub Desktop.
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