Finds all (integer) the triples from zero to max. won't return duplicates (ie. (3,4,5) and (4,3,5)) prints them
demonstrates:
nested loops,
multiple classes,
proper equals(Object) override (no hashcode though),
writing to file
Pythagorean Triples
/**creates pythagorian triples. SciWizEH*/
public class Tripler
{
static java.io.PrintWriter f; // = new java.io.FileWriter("triples.txt");
static int max = 1000;
static boolean add = true;
static int count;
static java.util.ArrayList < Triple > ts =
new java.util.ArrayList < Triple > ();
/**main.*/
public static void main(String[] args) {
ts.clear();
count = 0;
for (int a = 1; a <= max; a++) {
for (int b = 1; b <= max; b++) {
for (int c = 1; c <= max; c++) {
add = true;
if (((a * a) + (b * b)) == (c * c)) {
Triple t = new Triple(a, b, c);
for (Triple x : ts) {
if (t.equals(x)) {
add = false;
}
}
if (add) {
ts.add(t);
}
}
}
}
}
try {
String str = "";
f = new java.io.PrintWriter(new java.io.FileWriter("triples.txt"));
for (Triple y : ts) {
f.println(y.toString());
Triple.print(y);
count++;
}
f.println(count + "");
System.out.println(count + "");
f.close();
}
catch (Exception e) {
//dd
}
}
}
/**clas to handle triples*/
class Triple {
/**a part.*/
public int a ;
/**b part.*/
public int b ;
/**c part.*/
public int c ;
/**
* Costructor for objects of class triple.
*/
public Triple ( int na , int nb , int nc ) {
a = na ;
b = nb ;
c = nc ;
}
/**
* checks if it equals another, or is a multiple of it.
*/
@Override
public boolean equals ( Object n ) {
if ( n == null ) {
return false ;
}
if ( n.getClass ( ) == getClass ( ) ) {
Triple nt = ( Triple ) n ;
if ( ( a == nt.a || a == nt.b ) && ( b == nt.b || b == nt.a )
&& ( c == nt.c ) ) {
return true ;
} else if ( ( ( ( ( a % nt.a ) == 0 ) || ( ( nt.a % a ) == 0 ) ) || ( ( ( a % nt.b ) == 0 ) || ( ( nt.b % a ) == 0 ) ) )
&& ( ( ( ( b % nt.b ) == 0 ) || ( ( nt.b % b ) == 0 ) ) || ( ( ( b % nt.a ) == 0 ) || ( ( nt.a % b ) == 0 ) ) )
&& ( ( c % nt.c ) == 0 || ( nt.c % c ) == 0 ) ) {
return true ;
} else {
return false ;
}
} else {
return false ;
}
}
/**
* prints one to system.
*/
static void print ( Triple nt ) {
System.out.println ( nt.a + ", " + nt.b + ", " + nt.c ) ;
}
/**
* makes a string of this triple.
*/
public String toString ( ) {
return a + ", " + b + ", " + c ;
}
}
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.