The Pythagorean Theorem: A Journey from Ancient Wisdom to Modern Code

In the vast expanse of mathematics, there shines a brilliant star that has traversed thousands of years, from cuneiform inscriptions on clay tablets to its rebirth in computer code. This is the Pythagorean theorem.

The Pythagorean theorem, commonly referred to in the West as the Pythagorean theorem, although named after the ancient Greek philosopher Pythagoras, was discovered and applied long before his time. Ancient Babylonian clay tablets (circa 1800 BC) recorded multiple sets of Pythagorean triples; the ancient Egyptians may have used a “3-4-5” rope to measure right angles; and the earliest Chinese mathematical work, the “Zhou Bi Suan Jing,” also contains a clear record of “3-4-5,” hence the name “Pythagorean theorem.”

The Pythagorean theorem is one of the most fundamental theorems in plane geometry. Its classic statement is:

In a right triangle, the square of the length of the hypotenuse is equal to the sum of the squares of the lengths of the other two sides.

Expressed in formula form:<span><span>c² = a² + b²</span></span>

The value of the Pythagorean theorem lies in its establishment of a bridge between the algebraic relationships of triangle side lengths and the geometric properties of shapes. For centuries, there have been hundreds of methods to prove it, from the rigorous reasoning in Euclid’s Elements to Zhao Shuang’s intuitive and elegant “string diagram,” all shining with the light of human wisdom.

In modern society, the applications of the Pythagorean theorem are ubiquitous. From calculating the straight-line distance between two points in engineering measurements to computing the distance between pixel points in computer graphics, and even to vector composition in physics, its simplicity and power make it an indispensable tool in the fields of science and engineering.

It is precisely this universality that transcends time and space that makes it an excellent case study for programming beginners.

1. Finding the Hypotenuse Given Two Sides

The following program acts as a “precise calculator” with the task of finding the length of the hypotenuse given the lengths of the two legs of a right triangle.

// Include the C++ standard library header#include <bits/stdc++.h>// Use the standard namespace to avoid writing std:: every timeusing namespace std;// Main functionint main(){    int a, b;   // Define two integer variables a and b to store input values    cin >> a >> b;  // Read two integers from standard input into variables a and b        double x, c;    // Define double precision floating-point variables x and c    x = a*a + b*b;    // Calculate a squared plus b squared, assign to x    c = sqrt(x);    // Calculate the square root of x (i.e., the length of the hypotenuse)        // Set output format: fixed decimal places, keep two decimal places, then output hypotenuse length c    cout << fixed << setprecision(2) << c << endl;        // Program ends normally, return 0    return 0;}

This is an “O(1) constant time complexity” algorithm. Regardless of how large the values of a and b are, the steps executed by the program are fixed (one addition, one multiplication, one square root). This reflects the computer’s greatest strength: quickly and accurately performing mathematical operations.

  • Data Type Selection: The inputs a<span><span>a</span></span> and <span><span>b</span></span> are integers<span><span>int</span></span>, but the result<span><span>c</span></span> is a floating-point number<span><span>double</span></span>. This is because the square root result is likely to be a decimal, and <span><span>double</span></span> can provide higher precision.

  • Mathematical Library Application:<span><span>sqrt()</span></span> function is a feature in the C++ standard math library that encapsulates complex square root calculations.

  • Output Formatting:<span><span>fixed</span></span> and <span><span>setprecision(2)</span></span> ensure that the output result is clear and readable, conforming to everyday habits. For example, if the inputs are 3 and 4, the output will be “5.00” instead of a potentially error-prone floating-point number.

This program clearly demonstrates the basic programming paradigm of “input-processing-output” and how to directly translate mathematical formulas into computer instructions.

2. Finding Pythagorean Triples

If the previous program is about “calculation,” then the next program is about “searching.” It acts as a “patient explorer” whose goal is to find all integer triples<span><span>(x, y, z)</span></span> that satisfy the Pythagorean theorem within a given upper limit N, i.e., to find the “Pythagorean triples.”

#include <bits/stdc++.h>  // Include the C++ standard library headerusing namespace std;  // Use the standard namespace// Main functionint main(){    int x, y, z, N;  // Define four integer variables: x, y, z represent three numbers, N represents the upper limit    cin >> N;  // Read an integer N from standard input    bool flag = false;  // Define a boolean variable flag to mark whether a valid combination has been found    // Three nested loops to iterate through all possible combinations of x, y, z    for(x = 1; x <= N; x++) {        for(y = x + 1; y <= N; y++) {            for(z = y + 1; z <= N; z++) {                // Check if the condition is satisfied: z squared equals x squared plus y squared                if(z * z == x * x + y * y) {                    // If a valid combination is found, set flag to true                    flag = true;                    // Output the found three numbers                    cout << x << " " << y << " " << z << endl;                }            }        }    }    // If flag is still false after the loop, it means no combinations were found    if(!flag) {        cout << "no answer" << endl;    }    // Program ends normally    return 0;}

This is an “O(N³) cubic time complexity” algorithm. As N increases, the number of combinations the program needs to check grows cubically, resulting in a massive computational load. For example, if N=100, it needs to check about 1 million combinations; if N=1000, it needs to check nearly 1 billion combinations. This intuitively demonstrates the concept of “algorithm complexity.”

  • Loops and Iteration: The three nested<span><span>for</span></span> loops are a typical feature of “brute force search,” systematically enumerating all possible<span><span>(x, y, z)</span></span> combinations.

  • Search Optimization:<span><span>y=x+1</span></span> and <span><span>z=y+1</span></span> are key optimizations. They avoid redundant checks (like (3,4,5) and (4,3,5)) and unordered combinations, ensuring that<span><span>x < y < z</span></span>, greatly reducing ineffective searches.

  • Use of State Flags:<span><span>flag</span></span> variable is a common technique in programming. It records the state during the program’s execution (whether at least one solution has been found), allowing for appropriate output at the end (“no answer”).

This program serves as a stepping stone for learning algorithmic thinking. It vividly illustrates core concepts such as “iteration,” “searching,” “state management,” and “basic optimization,” forming the foundation for understanding more complex algorithms (like backtracking and dynamic programming).

Conclusion: One theorem, two ways of thinking, infinite possibilities

By analyzing these two pieces of code, we see two distinctly different computational approaches to solving the same problem:

  • Program One (Calculator) represents analytical thinking. It is based on a definite formula, obtaining a unique answer through direct calculation, efficient and precise. This is the ideal way to solve problems with clear mathematical relationships.

  • Program Two (Explorer) represents search thinking. When a problem does not have a direct analytical solution or requires enumeration of all possible cases, systematic searching through the computer’s powerful computational ability becomes the only or most direct method.

From the ancient Pythagorean theorem to modern programming implementations, we see not only the transmission of mathematical knowledge but also the evolution and expansion of human problem-solving thinking. In today’s era of artificial intelligence and big data mining, these two ways of thinking—rapid and precise analytical computation and vast and complex combinatorial search—remain the twin wings driving technological advancement. And this is the true charm of learning programming and mathematics: understanding the past, mastering the present, and thus creating the future.

Leave a Comment