0% found this document useful (0 votes)
7 views3 pages

Pythagorean Triples and Pi Series in Java

Uploaded by

wwangyibo17
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views3 pages

Pythagorean Triples and Pi Series in Java

Uploaded by

wwangyibo17
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

CHAPTER 5

1. The set of three integer values for the lengths of the sides of a right triangle is called a
Pythagorean triple. Write an application that displays a table of the Pythagorean triples for
side1, side2 and the hypotenuse, all no larger than 50. Use a triple-nested for loop that tries
all possibilities.

Program:
package CH_5;
public class PythagorasTriples{
public static void main(String[] args){
int a = 0, b = 0, h = 0;
[Link](“Lengths of the three sides that form a right triangle.\n");
[Link]("%-10s %-10s %-10s \n","Side A","Side B","Hypotenuse");

for(int i=0; i<50; i++){ // Side A loop


a += 1;
checkHypotenuse(a, b, h);

for(int j=0; j<50; j++){ // Side B loop


b += 1;
checkHypotenuse(a, b, h);

for(int k=0; k<50; k++){ // Hypotenuse loop


h += 1;
checkHypotenuse(a, b, h);
}
h = 0; // reset h after Hypotenuse loop ends

}
b = 0; // reset b after Side B loop ends
}
}// main method
public static void checkHypotenuse(int a, int b, int h){ // check Pythagorean theorem
if( (a * a) + (b * b) == (h * h) ) {
[Link]("%-10d %-10d %-10d \n",a,b,h);
}
}
}// class end
Output:
Lengths of the three sides that form a right triangle.
Side A Side B Hypotenuse
3 4 5
4 3 5
.
.
.
48 14 50

2. Write a java program that compute and display values of the first 20 terms of the following
infinite series.
4 4 4 4 4
π=4− + − + − +…
3 5 7 9 11
Program:
package CH_5;
public class ValueOfPi{
private static final long TERMS = 20;

public static void main(String[] args){


double infiniteSeries = 0.0f;
boolean sign = true;
long count = 0;

[Link]("The first 20 terms of the infinite series\n");


[Link]("%-10s %-10s\n","TERMS","VALUE");
//Since we wanted to discard even values of i,
//for loop will only execute half of the total iteration.
//So we need to multiply TERMS with 2 to loop until the actual iteration count
long totalIterationCount = TERMS * 2;
for(int i=1; i<= totalIterationCount; i+=2){
// only compute odd numbers
if(i % 2 == 0)
continue; // skip the iteration if it is even

// check if addition or subtraction


if(sign)
infiniteSeries += (4.0 / (double)i);
else
infiniteSeries -= (4.0 / (double)i);

count += 1;
[Link]("%-10d %-10f\n",count,infiniteSeries);

// reverse the sign after every iteration


sign = !sign;

}
}
}
Output:
The first 20 terms of the infinite series
TERMS VALUE
1 4.000000
2 2.666667
3 3.466667
.
.
20 3.091624

Common questions

Powered by AI

The Java program calculates an approximation of π by evaluating the series π = 4 − 4/3 + 4/5 − 4/7 + ..., which is an infinite series known as the Gregory-Leibniz series. The program uses a loop to calculate the first 20 terms of this series, alternating between adding and subtracting values by reversing a boolean sign. The effectiveness of this series in approximating π is limited by its slow convergence; while it converges to π, it requires a very large number of terms to achieve high precision, making it relatively inefficient for practical computation of π .

When using nested loops to calculate mathematical series, it is important to ensure that each loop iterates over the correct range and that the loops efficiently manage the program's logic to avoid unnecessary calculations. It is also crucial to consider performance implications, such as ensuring loops do not have redundant iterations which could lead to increased computational time. Additionally, managing variable reset (e.g., resetting 'b' and 'h' in the outer loops as shown in the program) and handling numerical precision when performing computations are key considerations, particularly in floating-point arithmetic .

The program strikes a balance between readability and computational complexity by using a straightforward triple-nested loop structure, making it easy to understand the logic and flow of computation. However, this comes at the cost of efficiency, as the brute-force approach has inherent performance drawbacks due to its high computational demand. For enhancing efficiency while maintaining readability, the program could incorporate commentaries explaining logical shortcuts or efficient data structures while keeping the base structure straightforward to avoid hindering code comprehension .

The series approximation method for π used in the program, the Gregory-Leibniz series, converges extremely slowly, which makes it unsuitable for high-precision scientific computations where a high number of decimal places might be needed. Despite its theoretical validity, to achieve even moderate precision, an impractical number of terms must be computed. For scientific applications requiring high precision, other formulas like the Machin-like formulas or the Chudnovsky algorithm, which converge much more rapidly, are preferred .

Order of operations is crucial in the calculation of an infinite series because the precision and correctness of the result depend on the sequence of addition and subtraction. In the program, this is managed using a boolean variable 'sign' to alternate the operations accurately. After each term is computed, the 'sign' is toggled to switch between addition and subtraction, ensuring the correct order prescribed by the series formula is maintained .

The brute-force method to find Pythagorean triples involves iterating through all possible combinations of sides within a specified range, which can be computationally expensive, especially as the range increases. This approach is inefficient because it checks many combinations that are not valid triangles. To optimize performance, we can limit iterations by checking side constraints early, using mathematical insights to limit the search space, or employing more efficient algorithms like primitive triple generation formulas (e.g., using m, n coprime integers).

The given programs embody fundamental programming principles of iteration through for loops, and control flow via conditional checks. In the Pythagorean triples program, iteration is used to try all possible side combinations, while control flow establishes the validity through a conditional statement checking the Pythagorean theorem. In the π approximation program, iteration computes terms in the series, and control flow alternates addition and subtraction using a boolean toggle. These principles are critical as they provide the essential mechanisms for systematically traversing solutions and directing program execution to achieve desired outcomes efficiently and correctly .

The Java program generates Pythagorean triples by using a triple-nested for loop to iterate through possible values for sides 'a', 'b', and the hypotenuse 'h', each from 1 to 49 (within the limit of 50). It checks each combination using the condition a^2 + b^2 = h^2 to determine if it forms a right triangle. When the condition is satisfied, it prints the values as a Pythagorean triple .

To improve the efficiency of identifying Pythagorean triples for longer sides, several strategies can be employed: 1) Use analytic methods like Euclid's formula which generate primitive triples directly and then apply scaling, drastically reducing computational effort; 2) Implement memoization or dynamic programming techniques to avoid redundant calculations; 3) Utilize parallel processing to divide the search space and leverage multiple compute threads; 4) Use mathematical properties like symmetry to reduce the number of computations (e.g., if (a, b, h) is a triple, then so is (b, a, h)).

The program maintains numerical precision by performing calculations using the double data type, which offers greater precision than float. It carefully controls the sign of each term in the series using a boolean flag to ensure correct addition and subtraction. However, improvements could include using higher-precision data types such as BigDecimal in Java for even more accurate results, especially when a high number of terms are involved, to minimize the accumulated error typical of floating-point arithmetic .

You might also like