Project Euler | Problem 9 | Special Pythagorean Triplet



Problem Description :


A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a^2 + b^2 = c^2
For example, 32 + 42 = 9 + 16 = 25 = 52. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc.

Concept :


We have following two equations.

1) a^2+b^2=c^2
2) a+b+c=1000

on solving these equations mathematically.

1<=a<=999
b=(1000^2-(2*a*1000))/(2*(1000-a))
c=1000-b-a

Java Program :


package com.javamultiplex.projecteuler;

/**
 * 
 * @author Rohit Agarwal
 * @category Project Euler Problems
 * @problem Problem 9
 *
 */
public class Problem9 {

 public static void main(String[] args) {

  int limit = 1000, a, b, c, result;
  for (int i = 1; i < limit; i++) {
   a = i;
   /*
    * if a+b+c=n and c^2=a^2+b^2 on solving above equations we can find
    * value of b in terms of a and n b=(n^2-2an)/2(n-a)
    * 
    */
   b = (int) ((Math.pow(limit, 2) - 2 * a * limit) / (2 * (limit - a)));
   c = limit - b - a;
   if (isPythagoreanTriplet(a, b, c)) {
    if (a + b + c == limit) {
     result = a * b * c;
     System.out.println("Pythagorean triplet for which a + b + c = 1000 is : " + result);
     break;
    }
   }
  }

 }

 
 //a,b and c are Pythagorean Triplets if c>b>a and c^2=a^2+b^2
 private static boolean isPythagoreanTriplet(int a, int b, int c) {

  boolean result = false;
  if (c > b && b > a) {
   if (c * c == a * a + b * b) {
    result = true;
   }
  }
  return result;
 }

}


Output :


Output of Project Euler Problem 9 in Java
Output - Project Euler Problem 9 Solution in Java

References :


https://projecteuler.net/problem=9

https://en.wikipedia.org/wiki/Pythagorean_triple

https://docs.oracle.com/javase/7/docs/api/java/lang/Math.html

Thank you friends, I hope you have clearly understood the solution of this problem. If you have any doubt, suggestion or query please feel free to comment below. You can also discuss this solution in our forum.

Tags : Project Euler Problem 9 solution in Java, Mathematics problems, Special Pythagorean Triplet, for loop, if else statement.

About Author:

I am simple guy with lot of ambitions. My main motive is to share whatever knowledge I have related to programming. With me you can easily learn how to solve any programming problem in Java.You can connect with me on social networking sites also.


Let's Get Connected: Linkedin | Facebook |

Project Euler | Problem 9 | Special Pythagorean Triplet Project Euler | Problem 9 | Special Pythagorean Triplet Reviewed by Rohit Agarwal on 3/10/2017 Rating: 5

No comments:

Please provide your valuable comments. If you have any suggestion please share with me I will work on it and if you have any question or doubt please ask, don't hesitate. I am your friend, i will clarify all your doubts.

Powered by Blogger.