TIP: Click on subject to list as thread! ANSI
echo: science
to: ALL
from: DAVID WILLIAMS
date: 2004-08-14 14:47:24
subject: Pythagorean triples

The (rarely seen) neat-freak in me insisted that I make a nicely 
structured version of my triples program, so here it is. Neatness comes 
with a price. This version is slightly, but only slightly, slower than 
the unstructured version. But it should be easier to understand. I've 
added a few comments, too. 
  
                               dow 
  
-------------------------------------------------------- 
  
' Pythagorean Triples 
  
' David O. Williams. 2004 
  
' Calculates and prints integer triples, A, B, C, such that 
' A 1), and A^2 + B^2 = C^2. 
' List is printed in order of increasing A, then of B. 
' A triple counter is also shown. 
  
DECLARE FUNCTION NoComFacs& (X&, Y&) 
DECLARE SUB PrintOut () 
DECLARE SUB Even () 
DECLARE SUB Odd () 
  
DEFLNG A-Z 
  
Mn = 3' minimum value of smallest number in triple 
Mx = 10000' maximum value of smallest number in triple 
  
DIM SHARED A, B, C  ' three numbers in triple (increasing order) 
DIM SHARED N, Z# ' triple counter, and much-used constant 
  
N = 0 
Z# = SQR(2) - 1 
  
CLS 
  
FOR A = Mn TO Mx 
  SELECT CASE A MOD 4 
    CASE 0: Even 
    CASE 1, 3: Odd 
    ' case 2 produces no valid triples 
  END SELECT 
NEXT 
  
END 
  
SUB Even ' handles cases when A is even (and a multiple of 4) 
  S = A \ 2 
  FOR F = INT(SQR(Z# * S)) TO 1 STEP -1 
    G = S \ F 
    IF G * F = S THEN 
      IF (F XOR G) AND 1 THEN 
        IF NoComFacs(F, G) THEN 
          E = F + G 
          D = G - F 
          B = D * E 
          C = (E * E + D * D) \ 2 
          PrintOut 
        END IF 
      END IF 
    END IF 
  NEXT 
END SUB 
  
FUNCTION NoComFacs (X, Y) ' non-zero if X and Y have no common factors 
  U = Y 
  V = X 
  DO WHILE V > 1 
    W = U MOD V 
    U = V 
    V = W 
  LOOP 
  NoComFacs = V 
END FUNCTION 
  
SUB Odd ' handles cases when A is odd 
  FOR D = INT(SQR(Z# * A)) - 1 OR 1 TO 1 STEP -2 
    E = A \ D 
    IF E * D = A THEN 
      IF NoComFacs(D, E) THEN 
        B = ((E + D) * (E - D)) \ 2 
        C = (E * E + D * D) \ 2 
        PrintOut 
      END IF 
    END IF 
  NEXT 
END SUB 
  
SUB PrintOut 
  N = N + 1 
  PRINT N, , A, B, C 
END SUB 
  
------------------------------------------------------- 
--- Platinum Xpress/Win/WINServer v3.0pr5
* Origin: The Bayman BBS,Toronto, (416)698-6573 - 1:250/514 (1:250/514)
SEEN-BY: 633/267 270
@PATH: 250/514 123/500 106/2000 633/267

SOURCE: echomail via fidonet.ozzmosis.com

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.