brilliant_moves

PythagoreanTriples2.java

May 9th, 2015
508
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.27 KB | None | 0 0
  1. public class PythagoreanTriples2 {
  2.  
  3. /*
  4.     "In a right angled triangle, the square on the hypotenuse is equal to
  5.     the sum of the squares on the other two sides." - Pythagoras' Theorem.
  6. */
  7.  
  8.     /**
  9.     *   Program:    PythagoreanTriples2.java
  10.     *   Purpose:    Calculate series of right-angled triangles
  11.     *   Creator     Chris Clarke
  12.     *   Created:    09.05.2015
  13.     *   Note:       Calculates all triples from a=3 to a=499.
  14.     *   See also:   https://en.wikipedia.org/wiki/Pythagorean_triples
  15.     */
  16.  
  17.     private static long a=3L, b=4L, c=5L;
  18.  
  19.     public static void main(String[] args) {
  20.  
  21.         System.out.println("Triangles with the following length sides are right-angled:");
  22.  
  23.         while (a<=500L) {
  24.             calcSides(a);
  25.             a+=2;
  26.         } // end while
  27.  
  28.     } // end main()
  29.  
  30.     public static void calcSides(long a) {
  31.     // given a, calculate b and c and display them all
  32.  
  33.     /*
  34.         a is odd (Pythagoras, c. 540 BC):
  35.         side a : side b = (a^2 - 1)/2: side c = (a^2 +1)/2
  36.  
  37.     */
  38.  
  39.         // calculate new values
  40.         b = (a*a-1)/2;
  41.         c = (a*a+1)/2;
  42.  
  43.         if (c<0) {  // exceeded maximum long number, become negative
  44.             System.exit(0);
  45.         } // end if
  46.  
  47.         if (!(a*a + b*b == c*c)) {
  48.             return;
  49.         } // if
  50.  
  51.         // print sides of right-angled triangle
  52.         System.out.println(a+", "+b+", "+c);
  53.  
  54.     } // end calcSides()
  55.  
  56. } // end class PythagoreanTriples2
Advertisement
Add Comment
Please, Sign In to add comment