Thursday, April 10, 2014

Project Euler Solution using C#: Problem 9: Special Pythagorean Triplet

Problem:

A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a^2 + b^2 = c^2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
My Solution:

  1. static void Main(string[] args)
  2. {
  3. int total = 1000;
  4. for (int i = 1; i <= total; i++)
  5. {
  6. for (int j = 1; j <= total; j++)
  7. {
  8. int k = total - i - j;
  9. int res = (i * i) + (j * j) + (k * k);
  10. int r = i + j + k;
  11.  
  12. int left = (i * i) + (j * j);
  13. int right = (k * k);
  14.  
  15. if (left == right && i < j && j < k)
  16. {
  17. Console.WriteLine(i + " " + j + " " + k);
  18. Console.WriteLine(Math.Pow(i, 2) + " " + Math.Pow(j, 2) + " " + Math.Pow(k, 2));
  19. Console.WriteLine(i * j * k);
  20. Console.WriteLine("---------------------");
  21. }
  22. }
  23. }
  24. Console.ReadLine();
  25. }

Note: You can simplifies the coding :)

No comments:

Post a Comment