mirror of
https://bitbucket.org/Mattrixwv/projecteulerjava.git
synced 2025-12-06 17:13:58 -05:00
73 lines
2.3 KiB
Java
73 lines
2.3 KiB
Java
//ProjectEuler/Java/Problem9.java
|
|
//Matthew Ellison
|
|
// Created: 03-02-19
|
|
//Modified: 03-28-19
|
|
//There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc.
|
|
//Unless otherwise listed all non-standard includes are my own creation and available from https://bibucket.org/Mattrixwv/JavaClasses
|
|
/*
|
|
Copyright (C) 2019 Matthew Ellison
|
|
|
|
This program is free software: you can redistribute it and/or modify
|
|
it under the terms of the GNU Lesser General Public License as published by
|
|
the Free Software Foundation, either version 3 of the License, or
|
|
(at your option) any later version.
|
|
|
|
This program is distributed in the hope that it will be useful,
|
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
GNU Lesser General Public License for more details.
|
|
|
|
You should have received a copy of the GNU Lesser General Public License
|
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
*/
|
|
|
|
|
|
import mattrixwv.Stopwatch;
|
|
|
|
|
|
public class Problem9{
|
|
public static void main(String[] argv){
|
|
//Setup the variables
|
|
Stopwatch timer = new Stopwatch(); //To time the execution time of this algorithm
|
|
Integer a = 1; //Holds the length of the first side
|
|
Integer b = 0; //Holds the length of the second side
|
|
Double c = 0D; //Holds the length of the hyp
|
|
Boolean found = false; //A flag to show whether the solution has been found
|
|
|
|
//Start the timer
|
|
timer.start();
|
|
|
|
//Loop through all possible a's
|
|
while((a < 1000) && !found){
|
|
b = a + 1; //b must be larger than a
|
|
c = Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2)); //Compute the hyp
|
|
|
|
//Loop through all possible b's for this a
|
|
while((a + b + c) < 1000){
|
|
++b;
|
|
c = Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
|
|
}
|
|
|
|
//If the sum == 1000 you found the number, otherwise go to the next possible a
|
|
if((a + b + c) == 1000){
|
|
found = true;
|
|
}
|
|
else{
|
|
++a;
|
|
}
|
|
}
|
|
|
|
//Stop the timer
|
|
timer.stop();
|
|
|
|
//Print the results
|
|
if(found){
|
|
System.out.printf("The Pythagorean triplet is %d + %d + %d\n", a, b, c.intValue());
|
|
System.out.printf("The numbers' product is %d\n", a * b * c.intValue());
|
|
System.out.println("It took " + timer.getStr() + " to run this algorithm");
|
|
}
|
|
else{
|
|
System.out.println("The number was not found!");
|
|
}
|
|
}
|
|
} |