Click to See Complete Forum and Search --> : Pythagorean Triplets


vee-eye
01-23-2002, 01:22 AM
My latest Java program! It displays sets of Pythagorean Triplets with numbers up to the integer stored in the variable limit. It also displays them in four neat columns.


public class PTriplets
{
public static void main(String[] args)
{
// No triplets past limit; the program should end sometime :-)
int limit = 100;

// The number of times a column has been printed
// When the number of columns defined in the variable columns
// has been used, a new line is started
int used = 0;

// The number of columns to be used
int columns = 4;

// Holds the triplet values; they are incremented in a loop
// The three elements begin with the default value 0
int[] trip = new int[3];

// Three loops cycle through all possible triplets up to limit
// The elements of trip are always initialized to 1
// because a side of a triangle can not be 0
for(trip[0] = 1; trip[0] <= limit; trip[0]++)
for(trip[1] = 1; trip[1] <= limit; trip[1]++)
for(trip[2] = 1; trip[2] <= limit; trip[2]++)
{
// Triplets are tested for when the third number is reached
// If they are triplets, then they are printed
if(trip[0]*trip[0] + trip[1]*trip[1] == trip[2]*trip[2])
{
// An extra space is added to single digits (less than 10)
// Without two or more spaces, using tabs is quite messy
// A tab character is inserted in the end to make columns
System.out.print((trip[0]<10 ? " " : "") + trip[0] +
(trip[1]<10 ? " " : " ") + trip[1] +
(trip[2]<10 ? " " : " ") + trip[2] + "\t");

// Increment the number of used columns
// If all columns in the variable columns have been used
// then print a new line; start a new set of columns
if(++used == columns)
{
System.out.print("\n");
used = 0;
}
}
}

// The shell starts on a new line when the program ends
System.out.print("\n");
}
}


Save this in a file called PTriplets.java. Then run the commands:

javac PTriplets.java
java PTriplets

You can type:

java PTriplets > trip.txt

to store the triplets in a file called trip.txt.

scanez
01-23-2002, 02:50 AM
Sweeeeet :D

~praise Pythagorean triples

tecknophreak
01-23-2002, 11:21 AM
if you do your for loops like:

for (trip[0] = 1; trip[0] <= limit; ++trip[0])
for (trip[1] = trip[0] + 1; trip[1] <= limit; ++trip[1])
for (trip[2] = trip[1] + 1; trip[2] <= trip[2]; ++trip[2])

your comp time is about 1/2 what it was before. you'll save about 480,000 loops out of about 970,000 :D

(of course these computations are small, but ya know...)