Project Euler | Problem 9 | Special Pythagorean Triplet
Problem Description :
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 :
This file contains hidden or 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
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 :
References :
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.
Project Euler | Problem 9 | Special Pythagorean Triplet
Reviewed by Rohit Agarwal
on
3/10/2017
Rating:

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.