WeixiangYan/CodeTransOcean huggingface dataset:
Task: Thiele's interpolation formula




Go: package main

import (
    "fmt"
    "math"
)

func main() {
    
    const nn = 32
    const step = .05
    xVal := make([]float64, nn)
    tSin := make([]float64, nn)
    tCos := make([]float64, nn)
    tTan := make([]float64, nn)
    for i := range xVal {
        xVal[i] = float64(i) * step
        tSin[i], tCos[i] = math.Sincos(xVal[i])
        tTan[i] = tSin[i] / tCos[i]
    }
    
    iSin := thieleInterpolator(tSin, xVal)
    iCos := thieleInterpolator(tCos, xVal)
    iTan := thieleInterpolator(tTan, xVal)
    
    fmt.Printf("%16.14f\n", 6*iSin(.5))
    fmt.Printf("%16.14f\n", 3*iCos(.5))
    fmt.Printf("%16.14f\n", 4*iTan(1))
}

func thieleInterpolator(x, y []float64) func(float64) float64 {
    n := len(x)
    ρ := make([][]float64, n)
    for i := range ρ {
        ρ[i] = make([]float64, n-i)
        ρ[i][0] = y[i]
    }
    for i := 0; i < n-1; i++ {
        ρ[i][1] = (x[i] - x[i+1]) / (ρ[i][0] - ρ[i+1][0])
    }
    for i := 2; i < n; i++ {
        for j := 0; j < n-i; j++ {
            ρ[j][i] = (x[j]-x[j+i])/(ρ[j][i-1]-ρ[j+1][i-1]) + ρ[j+1][i-2]
        }
    }
    
    ρ0 := ρ[0]
    return func(xin float64) float64 {
        var a float64
        for i := n - 1; i > 1; i-- {
            a = (xin - x[i-1]) / (ρ0[i] - ρ0[i-2] + a)
        }
        return y[0] + (xin-x[0])/(ρ0[1]+a)
    }
}








Ada: with Ada.Numerics.Generic_Real_Arrays;

generic
   type Real is digits <>;
package Thiele is
   package Real_Arrays is new Ada.Numerics.Generic_Real_Arrays (Real);
   subtype Real_Array is Real_Arrays.Real_Vector;

   type Thiele_Interpolation (Length : Natural) is private;

   function Create (X, Y : Real_Array) return Thiele_Interpolation;
   function Inverse (T : Thiele_Interpolation; X : Real) return Real;
private
   type Thiele_Interpolation (Length : Natural) is record
      X, Y, RhoX : Real_Array (1 .. Length);
   end record;
end Thiele;
Task: Hello world_Line printer




Go: package main

import (
	"fmt"
	"os"
)

func main() {
	lp0, err := os.Create("/dev/lp0")

	if err != nil {
		panic(err)
	}

	defer lp0.Close()

	fmt.Fprintln(lp0, "Hello World!")
}








Ada: with Ada.Text_IO; use Ada.Text_IO;

procedure Print_Line is
   Printer : File_Type;
begin
   begin
      Open (Printer, Mode => Out_File, Name => "/dev/lp0");
   exception
      when others =>
         Put_Line ("Unable to open printer.");
         return;
   end;

   Set_Output (Printer);
   Put_Line ("Hello World!");
   Close (Printer);
end Print_Line;
Task: Magic squares of odd order




Go: package main

import (
    "fmt"
    "log"
)

func ms(n int) (int, []int) {
    M := func(x int) int { return (x + n - 1) % n }
    if n <= 0 || n&1 == 0 {
        n = 5
        log.Println("forcing size", n)
    }
    m := make([]int, n*n)
    i, j := 0, n/2
    for k := 1; k <= n*n; k++ {
        m[i*n+j] = k
        if m[M(i)*n+M(j)] != 0 {
            i = (i + 1) % n
        } else {
            i, j = M(i), M(j)
        }
    }
    return n, m
}

func main() {
    n, m := ms(5)
    i := 2
    for j := 1; j <= n*n; j *= 10 {
        i++
    }
    f := fmt.Sprintf("%%%dd", i)
    for i := 0; i < n; i++ {
        for j := 0; j < n; j++ {
            fmt.Printf(f, m[i*n+j])
        }
        fmt.Println()
    }
}








Ada: with Ada.Text_IO, Ada.Command_Line;

procedure Magic_Square is
   N: constant Positive := Positive'Value(Ada.Command_Line.Argument(1));
   
   subtype Constants is Natural range 1 .. N*N;
   package CIO is new Ada.Text_IO.Integer_IO(Constants);
   Undef: constant Natural := 0;

   subtype Index is Natural range 0 .. N-1;
   function Inc(I: Index) return Index is (if I = N-1 then 0 else I+1);
   function Dec(I: Index) return Index is (if I = 0 then N-1 else I-1);
    
   A: array(Index, Index) of Natural := (others => (others => Undef));
     
  
   X: Index := 0; Y: Index := N/2; 
begin
   for I in Constants loop 
      A(X, Y) := I; 
      if A(Dec(X), Inc(Y)) = Undef then 
	 X := Dec(X); Y := Inc(Y); 
      else
	 X := Inc(X); 
      end if;
   end loop;
   
   for Row in Index loop 
      for Collumn in Index loop
	 CIO.Put(A(Row, Collumn), 
		 Width => (if N*N < 10 then 2 elsif N*N < 100 then 3 else 4));
      end loop;
      Ada.Text_IO.New_Line;
   end loop;
end Magic_Square;
Task: Pascal matrix generation







Python: from pprint import pprint as pp

def pascal_upp(n):
    s = [[0] * n for _ in range(n)]
    s[0] = [1] * n
    for i in range(1, n):
        for j in range(i, n):
            s[i][j] = s[i-1][j-1] + s[i][j-1]
    return s

def pascal_low(n):
    
    return [list(x) for x in zip(*pascal_upp(n))]

def pascal_sym(n):
    s = [[1] * n for _ in range(n)]
    for i in range(1, n):
        for j in range(1, n):
            s[i][j] = s[i-1][j] + s[i][j-1]
    return s
    

if __name__ == "__main__":
    n = 5
    print("\nUpper:")
    pp(pascal_upp(n))
    print("\nLower:")
    pp(pascal_low(n))
    print("\nSymmetric:")
    pp(pascal_sym(n))




Fortran: module pascal

implicit none

contains
    function pascal_lower(n) result(a)
        integer :: n, i, j
        integer, allocatable :: a(:, :)
        allocate(a(n, n))
        a = 0
        do i = 1, n
            a(i, 1) = 1
        end do
        do i = 2, n
            do j = 2, i
                a(i, j) = a(i - 1, j) + a(i - 1, j - 1)
            end do
        end do
    end function
    
    function pascal_upper(n) result(a)
        integer :: n, i, j
        integer, allocatable :: a(:, :)
        allocate(a(n, n))
        a = 0
        do i = 1, n
            a(1, i) = 1
        end do
        do i = 2, n
            do j = 2, i
                a(j, i) = a(j, i - 1) + a(j - 1, i - 1)
            end do
        end do
    end function

    function pascal_symmetric(n) result(a)
        integer :: n, i, j
        integer, allocatable :: a(:, :)
        allocate(a(n, n))
        a = 0
        do i = 1, n
            a(i, 1) = 1
            a(1, i) = 1
        end do
        do i = 2, n
            do j = 2, n
                a(i, j) = a(i - 1, j) + a(i, j - 1)
            end do
        end do
    end function

    subroutine print_matrix(a)
        integer :: a(:, :)
        integer :: n, i
        n = ubound(a, 1)
        do i = 1, n
            print *, a(i, :)
        end do
    end subroutine
end module

program ex_pascal
    use pascal
    implicit none
    integer :: n
    integer, allocatable :: a(:, :)
    print *, "Size?"
    read *, n
    print *, "Lower Pascal Matrix"
    a = pascal_lower(n)
    call print_matrix(a)
    print *, "Upper Pascal Matrix"
    a = pascal_upper(n)
    call print_matrix(a)
    print *, "Symmetric Pascal Matrix"
    a = pascal_symmetric(n)
    call print_matrix(a)
end program
Task: Long year







Python: 

from datetime import date



def longYear(y):
    
    return 52 < date(y, 12, 28).isocalendar()[1]




def main():
    
    for year in [
            x for x in range(2000, 1 + 2100)
            if longYear(x)
    ]:
        print(year)



if __name__ == '__main__':
    main()




Fortran: program longyear
    use iso_fortran_env, only: output_unit, input_unit
    implicit none

    integer             :: start, ende, i, counter
    integer, parameter  :: line_break=10

    write(output_unit,*) "Enter beginning of interval"
    read(input_unit,*) start
    write(output_unit,*) "Enter end of interval"
    read(input_unit,*) ende

    if (start>=ende) error stop "Last year must be after first year

    counter = 0
    do i = start, ende
        if (is_long_year(i)) then
            write(output_unit,'(I0,x)', advance="no") i
            counter = counter + 1
            if (modulo(counter,line_break) == 0) write(output_unit,*)
        end if
    end do
contains
    pure function p(year)
        integer, intent(in) :: year
        integer             :: p

        p = modulo(year + year/4 - year/100 + year/400, 7)
    end function p

    pure function is_long_year(year)
        integer, intent(in) :: year
        logical             :: is_long_year

        is_long_year = p(year) == 4 .or. p(year-1) == 3
    end function is_long_year
end program longyear
Task: Magic 8-ball







Python: import random

s = ('It is certain', 'It is decidedly so', 'Without a doubt', 'Yes, definitely',
 'You may rely on it', 'As I see it, yes', 'Most likely', 'Outlook good',
 'Signs point to yes', 'Yes', 'Reply hazy, try again', 'Ask again later',
 'Better not tell you now', 'Cannot predict now', 'Concentrate and ask again',
 "Don't bet on it", 'My reply is no', 'My sources say no', 'Outlook not so good',
 'Very doubtful')

q_and_a = {}

while True:
    question = input('Ask your question:')
    if len(question) == 0: break
        
    if question in q_and_a:
        print('Your question has already been answered')
    else:
        answer = random.choice(s)
        q_and_a[question] = answer
        print(answer)




Fortran: PROGRAM EIGHT_BALL
    CHARACTER(LEN=100) :: RESPONSE
    CHARACTER(LEN=100) :: QUESTION
    CHARACTER(LEN=100), DIMENSION(20) :: RESPONSES
    REAL :: R

    CALL RANDOM_SEED()

    RESPONSES(1) = "It is certain" 
    RESPONSES(2) = "It is decidedly so"
    RESPONSES(3) = "Without a doubt"
    RESPONSES(4) = "Yes, definitely"
    RESPONSES(5) = "You may rely on it"
    RESPONSES(6) = "As I see it, yes"
    RESPONSES(7) = "Most likely"
    RESPONSES(8) = "Outlook good"
    RESPONSES(9) = "Signs point to yes"
    RESPONSES(10) = "Yes"
    RESPONSES(11) = "Reply hazy, try again"
    RESPONSES(12) = "Ask again later"
    RESPONSES(13) = "Better not tell you now"
    RESPONSES(14) = "Cannot predict now"
    RESPONSES(15) = "Concentrate and ask again"
    RESPONSES(16) = "Don't bet on it"
    RESPONSES(17) = "My reply is no"
    RESPONSES(18) = "My sources say no"
    RESPONSES(19) = "Outlook not so good"
    RESPONSES(20) = "Very doubtful"

    WRITE(*,*) "Welcome to 8 Ball
    WRITE(*,*) "you seek, type either 'quit' or 'q' to exit", NEW_LINE('A')

    DO WHILE(.TRUE.)
        PRINT*, "Ask your question: "
        READ(*,*) QUESTION
        IF(QUESTION == "q" .OR. QUESTION == "quit") THEN
            CALL EXIT(0)
        ENDIF
        CALL RANDOM_NUMBER(R)
        PRINT*, "Response: ", TRIM(RESPONSES(FLOOR(R*20))), NEW_LINE('A')
    ENDDO
END PROGRAM EIGHT_BALL
Task: Validate International Securities Identification Number







Python: def check_isin(a):
    if len(a) != 12 or not all(c.isalpha() for c in a[:2]) or not all(c.isalnum() for c in a[2:]):
        return False
    s = "".join(str(int(c, 36)) for c in a)
    return 0 == (sum(sum(divmod(2 * (ord(c) - 48), 10)) for c in s[-2::-2]) +
                 sum(ord(c) - 48 for c in s[::-2])) % 10


def check_isin_alt(a):
    if len(a) != 12:
        return False
    s = []
    for i, c in enumerate(a):
        if c.isdigit():
            if i < 2:
                return False
            s.append(ord(c) - 48)
        elif c.isupper():
            if i == 11:
                return False
            s += divmod(ord(c) - 55, 10)
        else:
            return False
    v = sum(s[::-2])
    for k in s[-2::-2]:
        k = 2 * k
        v += k - 9 if k > 9 else k
    return v % 10 == 0

[check_isin(s) for s in ["US0378331005", "US0373831005", "U50378331005", "US03378331005",
                         "AU0000XVGZA3", "AU0000VXGZA3", "FR0000988040"]]






Fortran: program isin
    use ctype
    implicit none
    character(20) :: test(7) = ["US0378331005        ", &
                                "US0373831005        ", &
                                "U50378331005        ", &
                                "US03378331005       ", &
                                "AU0000XVGZA3        ", &
                                "AU0000VXGZA3        ", &
                                "FR0000988040        "]
    print *, check_isin(test)
contains
    elemental logical function check_isin(a)
        character(*), intent(in) :: a
        integer :: s(24)
        integer :: i, j, k, n, v

        check_isin = .false.

        n = len_trim(a)
        if (n /= 12) return
        
        
        j = 0
        do i = 1, n
            k = iachar(a(i:i))
            if (k >= 48 .and. k <= 57) then
                if (i < 3) return
                k = k - 48
                j = j + 1
                s(j) = k
            else if (k >= 65 .and. k <= 90) then
                if (i == 12) return
                k = k - 65 + 10
                j = j + 1
                s(j) = k / 10
                j = j + 1
                s(j) = mod(k, 10)
            else
                return
            end if
        end do

        
        v = 0
        do i = j - 1, 1, -2
            k = 2 * s(i)
            if (k > 9) k = k - 9
            v = v + k
        end do
        do i = j, 1, -2
            v = v + s(i)
        end do
        
        check_isin = 0 == mod(v, 10)
    end function
end program
Task: Input_Output for pairs of numbers







Python: def do_stuff(a, b):
	return a + b

t = input()
for x in range(0, t):
	a, b = raw_input().strip().split()
	print do_stuff(int(a), int(b))




Fortran: program i_o_pairs
  implicit none

  integer :: npairs
  integer :: i
  integer, allocatable :: pairs(:,:)

  read(*,*) npairs
  allocate(pairs(npairs,2))
 
  do i = 1, npairs
    read(*,*) pairs(i,:)
  end do
  write(*, "(i0)") sum(pairs, 2)

end program
Task: Kahan summation







Python: epsilon = 1.0
while 1.0 + epsilon != 1.0:
    epsilon = epsilon / 2.0




Fortran:       FUNCTION SUMC(A,N)
COMPENSATED SUMMATION. C WILL NOT STAY ZERO, DESPITE MATHEMATICS.
       DIMENSION A(12345)
        S = 0.0
        C = 0.0
        DO 1 I = 1,N
          Y = A(I) - C
          T = S + Y
          C = (T - S) - Y
          S = T
    1   CONTINUE
        SUMC = S
      END
      DIMENSION A(3)
      A(1) = 10000.0
      A(2) = 3.14159
      A(3) = 2.71828
      TYPE 1, A(1) + A(2) + A(3)
      TYPE 1, SUMC(A,3)
    1 FORMAT (6HSUM = ,F12.1)
      END
Task: Two identical strings







Python: def bits(n):
    
    r = 0
    while n:
        n >>= 1
        r += 1
    return r
    
def concat(n):
    
    return n << bits(n) | n
    
n = 1
while concat(n) <= 1000:
    print("{0}: {0:b}".format(concat(n)))
    n += 1




Fortran:       program IdentStr
          implicit none
          integer n, concat, bits
          
          n = 1
  100     if (concat(n) .lt. 1000) then
              write (*,'(I3,2X,I11)') concat(n), bits(concat(n))
              n = n + 1
              goto 100
          end if
          stop
      end

C     Concatenate binary representation of number with itself      
      integer function concat(num)
          integer num, sl, sr
          sl = num
          sr = num
  100     if (sr .gt. 0) then
              sl = sl * 2
              sr = sr / 2
              goto 100
          end if
          concat = num + sl
      end

C     Calculate binary representation of number
      integer function bits(num)
          integer num, n, bx
          n = num
          bits = 0
          bx = 1
  100     if (n .gt. 0) then
              bits = bits + bx * mod(n,2)
              bx = bx * 10
              n = n / 2
              goto 100
          end if
      end
Task: Verify distribution uniformity_Chi-squared test







Python: import math
import random

def GammaInc_Q( a, x):
    a1 = a-1
    a2 = a-2
    def f0( t ):
        return t**a1*math.exp(-t)

    def df0(t):
        return (a1-t)*t**a2*math.exp(-t)
    
    y = a1
    while f0(y)*(x-y) >2.0e-8 and y < x: y += .3
    if y > x: y = x

    h = 3.0e-4
    n = int(y/h)
    h = y/n
    hh = 0.5*h
    gamax = h * sum( f0(t)+hh*df0(t) for t in ( h*j for j in xrange(n-1, -1, -1)))

    return gamax/gamma_spounge(a)

c = None
def gamma_spounge( z):
    global c
    a = 12

    if c is None:
       k1_factrl = 1.0
       c = []
       c.append(math.sqrt(2.0*math.pi))
       for k in range(1,a):
          c.append( math.exp(a-k) * (a-k)**(k-0.5) / k1_factrl )
          k1_factrl *= -k
    
    accm = c[0]
    for k in range(1,a):
        accm += c[k] / (z+k)
    accm *= math.exp( -(z+a)) * (z+a)**(z+0.5)
    return accm/z;

def chi2UniformDistance( dataSet ):
    expected = sum(dataSet)*1.0/len(dataSet)
    cntrd = (d-expected for d in dataSet)
    return sum(x*x for x in cntrd)/expected

def chi2Probability(dof, distance):
    return 1.0 - GammaInc_Q( 0.5*dof, 0.5*distance)

def chi2IsUniform(dataSet, significance):
    dof = len(dataSet)-1
    dist = chi2UniformDistance(dataSet)
    return chi2Probability( dof, dist ) > significance

dset1 = [ 199809, 200665, 199607, 200270, 199649 ]
dset2 = [ 522573, 244456, 139979,  71531,  21461 ]

for ds in (dset1, dset2):
    print "Data set:", ds
    dof = len(ds)-1
    distance =chi2UniformDistance(ds)
    print "dof: %d distance: %.4f" % (dof, distance),
    prob = chi2Probability( dof, distance)
    print "probability: %.4f"%prob,
    print "uniform? ", "Yes"if chi2IsUniform(ds,0.05) else "No"




Fortran: module gsl_mini_bind_m

    use iso_c_binding
    implicit none
    private

    public :: p_value

    interface
        function gsl_cdf_chisq_q(x, nu) bind(c, name='gsl_cdf_chisq_Q')
            import
            real(c_double), value :: x
            real(c_double), value :: nu
            real(c_double) :: gsl_cdf_chisq_q
        end function gsl_cdf_chisq_q
    end interface

contains

    
    real function p_value(x, df)
        real, intent(in) :: x
        integer, intent(in) :: df

        p_value = real(gsl_cdf_chisq_q(real(x, c_double), real(df, c_double)))

    end function p_value

end module gsl_mini_bind_m
Task: CSV to HTML translation







Python: csvtxt = 

from cgi import escape

def _row2tr(row, attr=None):
    cols = escape(row).split(',')
    return ('<TR>'
            + ''.join('<TD>%s</TD>' % data for data in cols)
            + '</TR>')

def csv2html(txt):
    htmltxt = '<TABLE summary="csv2html program output">\n'
    for rownum, row in enumerate(txt.split('\n')):
        htmlrow = _row2tr(row)
        htmlrow = '  <TBODY>%s</TBODY>\n' % htmlrow
        htmltxt += htmlrow
    htmltxt += '</TABLE>\n'
    return htmltxt

htmltxt = csv2html(csvtxt)
print(htmltxt)




Fortran:       SUBROUTINE CSVTEXT2HTML(FNAME,HEADED)	
Converts without checking field counts, or noting special characters.
       CHARACTER*(*) FNAME	
       LOGICAL HEADED		
       INTEGER MANY		
       PARAMETER (MANY=666)	
       CHARACTER*(MANY) ALINE	
       INTEGER MARK(0:MANY + 1)	
       INTEGER I,L,N		
       CHARACTER*2 WOT(2)	
       PARAMETER (WOT = (/"th","td"/))	
       INTEGER IT		
       INTEGER KBD,MSG,IN		
       COMMON /IOUNITS/ KBD,MSG,IN	
        OPEN(IN,FILE=FNAME,STATUS="OLD",ACTION="READ",ERR=661)	
        WRITE (MSG,1)			
    1   FORMAT ("<Table border=1>")	
        MARK(0) = 0		
        N = 0			

   10   READ (IN,11,END = 20) L,ALINE(1:MIN(L,MANY))	
   11   FORMAT (Q,A)		
        N = N + 1		
        IF (L.GT.MANY) THEN	
          WRITE (MSG,12) N,L,MANY	
   12     FORMAT ("Line ",I0," has length ",I0,"
          L = MANY			
        END IF			
        IF (N.EQ.1 .AND. HEADED) THEN	
          WRITE (MSG,*) "<tHead>"	
          IT = 1			
         ELSE				
          IT = 2			
        END IF			
        NCOLS = 0		
        DO I = 1,L		
          IF (ICHAR(ALINE(I:I)).EQ.ICHAR(",")) THEN	
            NCOLS = NCOLS + 1		
            MARK(NCOLS) = I		
          END IF			
        END DO			
        NCOLS = NCOLS + 1	
        MARK(NCOLS) = L + 1	
        WRITE (MSG,13)		
     1   (WOT(IT),				
     2    ALINE(MARK(I - 1) + 1:MARK(I) - 1),	
     3    WOT(IT),				
     4    I = 1,NCOLS),			
     5   "/tr"			
   13   FORMAT (" <tr>",666("<",A,">",A,"</",A,">"))	
        IF (N.EQ.1 .AND. HEADED) WRITE (MSG,*) "</tHead>"	
        GO TO 10		

   20   CLOSE (IN)		
        WRITE (MSG,21)		
   21   FORMAT ("</Table>")	
       RETURN			
Confusions.
  661   WRITE (MSG,*) "Can't open file ",FNAME	
      END			

      INTEGER KBD,MSG,IN
      COMMON /IOUNITS/ KBD,MSG,IN
      KBD = 5	
      MSG = 6	
      IN = 10	

      CALL CSVTEXT2HTML("Text.csv",.FALSE.)	
      WRITE (MSG,*)
      CALL CSVTEXT2HTML("Text.csv",.TRUE.)	
      END
Task: Pythagorean triples







Python: from fractions import gcd


def pt1(maxperimeter=100):
    
    trips = []
    for a in range(1, maxperimeter):
        aa = a*a
        for b in range(a, maxperimeter-a+1):
            bb = b*b
            for c in range(b, maxperimeter-b-a+1):
                cc = c*c
                if a+b+c > maxperimeter or cc > aa + bb: break
                if aa + bb == cc:
                    trips.append((a,b,c, gcd(a, b) == 1))
    return trips

def pytrip(trip=(3,4,5),perim=100, prim=1):
    a0, b0, c0 = a, b, c = sorted(trip)
    t, firstprim = set(), prim>0
    while a + b + c <= perim:
        t.add((a, b, c, firstprim>0))
        a, b, c, firstprim = a+a0, b+b0, c+c0, False
    
    t2 = set()
    for a, b, c, firstprim in t:
        a2, a5, b2, b5, c2, c3, c7 = a*2, a*5, b*2, b*5, c*2, c*3, c*7
        if  a5 - b5 + c7 <= perim:
            t2 |= pytrip(( a - b2 + c2,  a2 - b + c2,  a2 - b2 + c3), perim, firstprim)
        if  a5 + b5 + c7 <= perim:
            t2 |= pytrip(( a + b2 + c2,  a2 + b + c2,  a2 + b2 + c3), perim, firstprim)
        if -a5 + b5 + c7 <= perim:
            t2 |= pytrip((-a + b2 + c2, -a2 + b + c2, -a2 + b2 + c3), perim, firstprim)
    return t | t2

def pt2(maxperimeter=100):
    
    trips = pytrip((3,4,5), maxperimeter, 1)
    return trips

def printit(maxperimeter=100, pt=pt1):
    trips = pt(maxperimeter)
    print("  Up to a perimeter of %i there are %i triples, of which %i are primitive"
          % (maxperimeter,
             len(trips),
             len([prim for a,b,c,prim in trips if prim])))
  
for algo, mn, mx in ((pt1, 250, 2500), (pt2, 500, 20000)):
    print(algo.__doc__)
    for maxperimeter in range(mn, mx+1, mn):
        printit(maxperimeter, algo)




Fortran: module triples
  implicit none
  
  integer :: max_peri, prim, total
  integer :: u(9,3) = reshape((/ 1, -2, 2,  2, -1, 2,  2, -2, 3, &
                                 1,  2, 2,  2,  1, 2,  2,  2, 3, &
                                -1,  2, 2, -2,  1, 2, -2,  2, 3 /), &
                                (/ 9, 3 /))
                                
contains

recursive subroutine new_tri(in)
  integer, intent(in) :: in(:)
  integer :: i
  integer :: t(3), p

  p = sum(in)
  if (p > max_peri) return

  prim = prim + 1
  total = total + max_peri / p
  do i = 1, 3
    t(1) = sum(u(1:3, i) * in)
    t(2) = sum(u(4:6, i) * in)
    t(3) = sum(u(7:9, i) * in)
    call new_tri(t);
  end do
end subroutine new_tri
end module triples

program Pythagorean
  use triples
  implicit none

  integer :: seed(3) = (/ 3, 4, 5 /)
  
  max_peri = 10
  do
    total = 0
    prim = 0
    call new_tri(seed)
    write(*, "(a, i10, 2(i10, a))") "Up to", max_peri, total, " triples",  prim, " primitives"
    if(max_peri == 100000000) exit
    max_peri = max_peri * 10
  end do
end program Pythagorean
Task: Call a foreign-language function







Python: import ctypes
libc = ctypes.CDLL("/lib/libc.so.6")
libc.strcmp("abc", "def")     
libc.strcmp("hello", "hello") 




Fortran: module c_api
    use iso_c_binding
    implicit none

    interface
        function strdup(ptr) bind(C)
            import c_ptr
            type(c_ptr), value :: ptr
            type(c_ptr) :: strdup
        end function
    end interface
    
    interface
        subroutine free(ptr) bind(C)
            import c_ptr
            type(c_ptr), value :: ptr
        end subroutine
    end interface
    
    interface
        function puts(ptr) bind(C)
            import c_ptr, c_int
            type(c_ptr), value :: ptr
            integer(c_int) :: puts
        end function
    end interface
end module

program c_example
    use c_api
    implicit none

    character(20), target :: str = "Hello, World
    type(c_ptr) :: ptr
    integer(c_int) :: res
    
    ptr = strdup(c_loc(str))
    
    res = puts(c_loc(str))
    res = puts(ptr)
    
    print *, transfer(c_loc(str), 0_c_intptr_t), &
             transfer(ptr, 0_c_intptr_t)
    call free(ptr)
end program