Created
October 23, 2019 11:30
-
-
Save ChrisLeNeve/3c86b90c993f44dfbf9b77e7014f8447 to your computer and use it in GitHub Desktop.
Project Euler - problem 9
This file contains 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
class Scratch { | |
public static void main(String[] args) { | |
Scratch s = new Scratch(); | |
Triplet t = s.solution(); | |
System.out.println("The triplet is: " + t.a + "," + t.b + "," + t.c); | |
int product = t.a * t.b * t.c; | |
} | |
private Triplet solution() { | |
int m = 2, n = 1; | |
int sumInFirstLoop = 0, sumInSecondLoop = 0; | |
while (sumInFirstLoop <= 1000) { | |
while (sumInSecondLoop <= 1000) { | |
Triplet t = getTriplet(m, n); | |
sumInSecondLoop = sum(t); | |
if (sumInSecondLoop == 1000) { | |
return t; | |
} | |
m++; | |
} | |
sumInSecondLoop = 0; | |
n++; | |
m = n + 1; | |
} | |
return null; | |
} | |
private int sum(Triplet t) { | |
return t.a + t.b + t.c; | |
} | |
/** | |
* Get triplet with Euclid's formula | |
* @param m | |
* @param n | |
* @return | |
*/ | |
private Triplet getTriplet(int m, int n) { | |
int a = (m*m) - (n*n); | |
int b = 2 * m * n; | |
int c = (m*m) + (n*n); | |
return new Triplet(a, b, c); | |
} | |
class Triplet { | |
int a; | |
int b; int c; | |
public Triplet(int aa, int bb, int cc) { | |
this.a = aa; | |
this.b = bb; | |
this.c = cc; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment