WeixiangYan/CodeTransOcean huggingface dataset:
Task: Old Russian measure of length







Python: from sys import argv
 
unit2mult = {"arshin": 0.7112, "centimeter": 0.01,     "diuym":   0.0254,
             "fut":    0.3048, "kilometer":  1000.0,   "liniya":  0.00254,
             "meter":  1.0,    "milia":      7467.6,   "piad":    0.1778,
             "sazhen": 2.1336, "tochka":     0.000254, "vershok": 0.04445,
             "versta": 1066.8}
 
if __name__ == '__main__':
    assert len(argv) == 3, 'ERROR. Need two arguments - number then units'
    try:
        value = float(argv[1])
    except:
        print('ERROR. First argument must be a (float) number')
        raise
    unit = argv[2]
    assert unit in unit2mult, ( 'ERROR. Only know the following units: ' 
                                + ' '.join(unit2mult.keys()) )

    print("%g %s to:" % (value, unit))
    for unt, mlt in sorted(unit2mult.items()):
        print('  %10s: %g' % (unt, value * unit2mult[unit] / mlt))




Fortran: PROGRAM RUS
 IMPLICIT NONE
 REAL, PARAMETER:: E_m = 1.
 REAL, PARAMETER:: E_mm = 1.E-3
 REAL, PARAMETER:: E_km = 1.E+3
 REAL, PARAMETER:: E_cm = 1.E-2
 REAL, PARAMETER:: E_arshin = 71.12 * E_cm
 REAL, PARAMETER:: E_fut = 3./7. * E_arshin
 REAL, PARAMETER:: E_piad = 1./4. * E_arshin
 REAL, PARAMETER:: E_vershok = 1./16. * E_arshin
 REAL, PARAMETER:: E_dyuim = 1./28. * E_arshin
 REAL, PARAMETER:: E_liniya = 1./280. * E_arshin
 REAL, PARAMETER:: E_tochka = 1./2800. * E_arshin
 REAL, PARAMETER:: E_ladon = 7.5 * E_cm
 REAL, PARAMETER:: E_lokot = 45 * E_cm
 REAL, PARAMETER:: E_sazhen = 3. * E_arshin
 REAL, PARAMETER:: E_versta = 1500. * E_arshin
 REAL, PARAMETER:: E_milya = 10500. * E_arshin
 INTEGER, PARAMETER:: N = 16
 CHARACTER(LEN=7), DIMENSION(N):: nam = (/&
  &'m      ', 'mm     ', 'km     ', 'cm     ',&
  &'arshin ', 'fut    ', 'piad   ', 'vershok',&
  &'dyuim  ', 'liniya ', 'tochka ', 'ladon  ',&
  &'lokot  ', 'sazhen ', 'versta ', 'milya  ' /)
 REAL, DIMENSION(N):: wert = (/ &
  &1., E_mm, E_km, E_cm,&
  &E_arshin, E_fut, E_piad, E_vershok,&
  &E_dyuim, E_liniya, E_tochka, E_ladon,&
  &E_lokot, E_sazhen, E_versta, E_milya /)
 CHARACTER(LEN=7):: RD_U
 REAL:: RD_V
 INTEGER:: I, J
 DO I=1, N
  WRITE(*, '(A, " ")', ADVANCE='NO')  nam(I)
 END DO
 WRITE (*, *)
 WRITE(*, '(A)', ADVANCE='NO') 'value unit -> '
 READ(*, *) RD_V, RD_U
 RD_U = ADJUSTL(RD_U)
 J = 1
 DO WHILE (NAM(J) .NE. RD_U)
  J = J + 1
  IF (J .GT. N) STOP "Unit not known: "//RD_U
 END DO
 RD_V = RD_V * wert(J)
 DO I=1, N
  J = J + 1
  IF (J .GT. N) J = 1
  WRITE (*, '(F20.3, " ", A)') RD_V / wert(J), nam(J)
 END DO
END PROGRAM RUS
Task: Test integerness







Python: >>> def isint(f): 
    return complex(f).imag == 0 and complex(f).real.is_integer()

>>> [isint(f) for f in (1.0, 2, (3.0+0.0j), 4.1, (3+4j), (5.6+0j))]
[True, True, True, False, False, False]

>>> 
...
>>> isint(25.000000)
True
>>> isint(24.999999)
False
>>> isint(25.000100)
False
>>> isint(-2.1e120)
True
>>> isint(-5e-2)
False
>>> isint(float('nan'))
False
>>> isint(float('inf'))
False
>>> isint(5.0+0.0j)
True
>>> isint(5-5j)
False




Fortran:       MODULE ZERMELO	
       CONTAINS
        LOGICAL FUNCTION ISINTEGRAL(X)	
         REAL*8 X	
         INTEGER*8 N	
          IF (ISNAN(X)) THEN	
            ISINTEGRAL = .FALSE.	
          ELSE			
            N = KIDINT(X)		
            ISINTEGRAL = N .EQ. X	
          END IF		
        END FUNCTION ISINTEGRAL	

        LOGICAL FUNCTION ISINTEGRALZ(Z)	
         DOUBLE COMPLEX Z	
          ISINTEGRALZ = ISINTEGRAL(DBLE(Z)) .AND. ISINTEGRAL(DIMAG(Z))	
        END FUNCTION ISINTEGRALZ
      END MODULE ZERMELO	

      PROGRAM TEST
      USE ZERMELO
      DOUBLE COMPLEX Z

      WRITE (6,*) "See if some numbers are integral..."
      WRITE (6,*) ISINTEGRAL(666D0),666D0
      Z = DCMPLX(-3D0,4*ATAN(1D0))
      WRITE (6,*) ISINTEGRALZ(Z),Z
      END
Task: Linux CPU utilization







Python: from __future__ import print_function
from time import sleep


last_idle = last_total = 0
while True:
    with open('/proc/stat') as f:
        fields = [float(column) for column in f.readline().strip().split()[1:]]
    idle, total = fields[3], sum(fields)
    idle_delta, total_delta = idle - last_idle, total - last_total
    last_idle, last_total = idle, total
    utilisation = 100.0 * (1.0 - idle_delta / total_delta)
    print('%5.1f%%' % utilisation, end='\r')
    sleep(5)




Fortran: Program CPUusage
    implicit none
    integer :: ios, i
    integer :: oldidle, oldsum, sumtimes = 0
    real :: percent = 0.
    character(len = 4) lineID 
    integer, dimension(9) :: times = 0

    write(*, *) 'CPU Usage'
    write(*, *) 'Press Ctrl<C> to end'
    do while (.true.)
        open(unit = 7, file = '/proc/stat', status = 'old', action = 'read', iostat = ios)
        if (ios /= 0) then
            print *, 'Error opening /proc/stat'
            stop
        else
            read(unit = 7, fmt = *, iostat = ios) lineID, (times(i), i = 1, 9)
            close(7)
            if (lineID /= 'cpu ') then
                print *, 'Error reading /proc/stat'
                stop
            end if
            sumtimes = sum(times)
            percent = (1. - real((times(4) - oldidle)) / real((sumtimes - oldsum))) * 100.
            write(*, fmt = '(F6.2,A2)') percent, '%'
            oldidle = times(4)
            oldsum = sumtimes
            call sleep(1)
        end if
    end do
end program CPUusage
Task: Special variables







Python: names = sorted((set(globals().keys()) | set(__builtins__.__dict__.keys())) - set('_ names i'.split()))
print( '\n'.join(' '.join(names[i:i+8]) for i in range(0, len(names), 8)) )




Fortran:            INQUIRE(FILE = FILENAME(1:L),EXIST = EXIST,	
     1      ERR = 666,IOSTAT = IOSTAT) 		
           IF (EXIST) THEN	
           ...etc.
Task: Sequence of primorial primes







Python: import pyprimes

def primorial_prime(_pmax=500):
    isprime = pyprimes.isprime
    n, primo = 0, 1
    for prime in pyprimes.nprimes(_pmax):
        n, primo = n+1, primo * prime
        if isprime(primo-1) or isprime(primo+1):
            yield n
        
if __name__ == '__main__':
    
    pyprimes.warn_probably = False  
    for i, n in zip(range(20), primorial_prime()):
        print('Primorial prime %2i at primorial index: %3i' % (i+1, n))




Fortran:       PROGRAM PRIMORIALP	
      USE PRIMEBAG		
      USE BIGNUMBERS		
      TYPE(BIGNUM) B		
      INTEGER MAXF		
      PARAMETER (MAXF = 18000000)	
      INTEGER I			
      INTEGER FU,FD		
      INTEGER NHIT,HIT(666)	
      CHARACTER*4 WOT		
      CHARACTER*66 ALINE	
      REAL T0,T1		
      MSG = 6	
      WRITE (MSG,1) BIGLIMIT,BIGBASE,HUGE(I)	
    1 FORMAT ('Calculates primorial "primes"',/,
     1 "A primorial prime is a value N such that",/,
     2 "    Primorial(N) - 1 is prime, OR",/,
     3 "    Primorial(N) + 1 is prime, or both.",/,
     4 "and Primorial(N) is the product of the first N prime numbers.",/
     5 "Working with up to ",I0," digits in base ",I0,"."/
     6 "The integer limit is ",I0,/)

c      CALL PREPARE PRIMES	
      IF (.NOT.GRASPPRIMEBAG(66)) STOP "Gan't grab my file
      WRITE (MSG,2)
    2 FORMAT ("Primorial#",3X,"Approx.",8X," -1 Factor +1 Factor Hit")

Commence prime mashing.
  100 NHIT = 0		
      B.LAST = 1	
      B.DIGIT(1) = 1	
      CALL CPU_TIME(T0)	
      DO I = 1,30	
        CALL BIGMULTN(B,PRIME(I))	
c        WRITE (MSG,101) I,PRIME(I),I,B.DIGIT(B.LAST:1:-1)	
  101   FORMAT ("Prime(",I0,") = ",I0,", Primorial(",I0,") = ",	
     1   I0,9I<BIGORDER>.<BIGORDER>,/,(10I<BIGORDER>.<BIGORDER>))	
        FU = -1		
        FD = -1		
        CALL BIGADDN(B,+1)	
        FU = BIGFACTOR(B,MAXF)	
        CALL BIGADDN(B,-2)	
        IF (FU.NE.1) FD = BIGFACTOR(B,MAXF)	
        IF (FU.EQ.1 .OR. FD.EQ.1) THEN	
          WOT = "Yes
          NHIT = NHIT + 1			
          HIT(NHIT) = I				
        ELSE IF (FU.GT.1 .AND. FD.GT.1) THEN	
          WOT = "No."				
        ELSE				
          WOT = "?"				
        END IF				
        CALL BIGADDN(B,1)		
        WRITE (ALINE,102) I,BIGVALUE(B),FD,FU,WOT	
  102   FORMAT (I10,1PE18.10,I10,I10,1X,A)	
        IF (FD.EQ.-1) ALINE(37:38) = ""		
        IF (FD.EQ. 0) ALINE(38:38) = "?"	
        IF (FU.EQ. 0) ALINE(48:48) = "?"	
        WRITE (MSG,"(A)") ALINE		
      END DO		
      CALL CPU_TIME(T1)	

Cast forth some pearls.
      WRITE (MSG,201) HIT(1:NHIT)	
  201 FORMAT (/,"Hit list: ",I0,666(",",I0:))	
      WRITE (MSG,*) "CPU time:",T1 - T0	
      END
Task: Arithmetic-geometric mean_Calculate Pi







Python: from decimal import *

D = Decimal
getcontext().prec = 100
a = n = D(1)
g, z, half = 1 / D(2).sqrt(), D(0.25), D(0.5)
for i in range(18):
    x = [(a + g) * half, (a * g).sqrt()]
    var = x[0] - a
    z -= var * var * n
    n += n
    a, g = x    
print(a * a / z)




Fortran: program CalcPi
    
    use iso_fortran_env, only: rf => real128
    implicit none
    real(rf) :: a,g,s,old_pi,new_pi
    real(rf) :: a1,g1,s1
    integer :: k,k1,i

    old_pi = 0.0_rf;
    a = 1.0_rf; g = 1.0_rf/sqrt(2.0_rf); s = 0.0_rf; k = 0

    do i=1,100
        call approx_pi_step(a,g,s,k,a1,g1,s1,k1)
        new_pi = 4.0_rf * (a1**2.0_rf) / (1.0_rf - s1)
        if (abs(new_pi - old_pi).lt.(2.0_rf*epsilon(new_pi))) then
            
            
            exit
        end if
        write(*,*) 'Iteration:',k1,' Diff:',abs(new_pi - old_pi),' Pi:',new_pi
        old_pi = new_pi
        a = a1; g = g1; s = s1; k = k1
    end do

    contains

    subroutine approx_pi_step(x,y,z,n,a,g,s,k)
        real(rf), intent(in) :: x,y,z
        integer, intent(in) :: n
        real(rf), intent(out) :: a,g,s
        integer, intent(out) :: k

        a = 0.5_rf*(x+y)
        g = sqrt(x*y)
        k = n + 1
        s = z + (2.0_rf)**(real(k)+1.0_rf) * (a**(2.0_rf) - g**(2.0_rf))
    end subroutine
end program CalcPi
Task: Primorial numbers







Python: from pyprimes import nprimes
from functools import reduce


primelist = list(nprimes(1000001))    

def primorial(n):
    return reduce(int.__mul__, primelist[:n], 1)

if __name__ == '__main__':
    print('First ten primorals:', [primorial(n) for n in range(10)])
    for e in range(7):
        n = 10**e
        print('primorial(%i) has %i digits' % (n, len(str(primorial(n)))))




Fortran:       B.DIGIT(I) = MOD(D,BIGBASE)
      C = D/BIGBASE
Task: Numerical integration_Gauss-Legendre Quadrature







Python: from numpy import *
 


def Legendre(n,x):
	x=array(x)
	if (n==0):
		return x*0+1.0
	elif (n==1):
		return x
	else:
		return ((2.0*n-1.0)*x*Legendre(n-1,x)-(n-1)*Legendre(n-2,x))/n
 


def DLegendre(n,x):
	x=array(x)
	if (n==0):
		return x*0
	elif (n==1):
		return x*0+1.0
	else:
		return (n/(x**2-1.0))*(x*Legendre(n,x)-Legendre(n-1,x))


def LegendreRoots(polyorder,tolerance=1e-20):
	if polyorder<2:
		err=1 
	else:
		roots=[]
		
		for i in range(1,int(polyorder)/2 +1):
			x=cos(pi*(i-0.25)/(polyorder+0.5))
			error=10*tolerance
		        iters=0
		        while (error>tolerance) and (iters<1000):
		                dx=-Legendre(polyorder,x)/DLegendre(polyorder,x)
		                x=x+dx
		                iters=iters+1
		                error=abs(dx)
			roots.append(x)
		
		roots=array(roots)
		if polyorder%2==0:
			roots=concatenate( (-1.0*roots, roots[::-1]) )
		else:
			roots=concatenate( (-1.0*roots, [0.0], roots[::-1]) )
		err=0 
	return [roots, err]


def GaussLegendreWeights(polyorder):
	W=[]
	[xis,err]=LegendreRoots(polyorder)
	if err==0:
		W=2.0/( (1.0-xis**2)*(DLegendre(polyorder,xis)**2) )
		err=0
	else:
		err=1 
	return [W, xis, err]






def GaussLegendreQuadrature(func, polyorder, a, b):
	[Ws,xs, err]= GaussLegendreWeights(polyorder)
	if err==0:
		ans=(b-a)*0.5*sum( Ws*func( (b-a)*0.5*xs+ (b+a)*0.5 ) )
	else: 
		
		err=1
		ans=None
	return [ans,err]


def func(x):
	return exp(x)


 
order=5
[Ws,xs,err]=GaussLegendreWeights(order)
if err==0:
	print "Order    : ", order
	print "Roots    : ", xs
	print "Weights  : ", Ws
else:
	print "Roots/Weights evaluation failed"
 

[ans,err]=GaussLegendreQuadrature(func , order, -3,3)
if err==0:
	print "Integral : ", ans
else:
	print "Integral evaluation failed"




Fortran: 



program gauss
  implicit none
  integer, parameter :: p = 16 
  integer            :: n = 10, k
  real(kind=p), allocatable :: r(:,:)
  real(kind=p)       :: z, a, b, exact
  do n = 1,20
    a = -3; b = 3
    r = gaussquad(n)
    z = (b-a)/2*dot_product(r(2,:),exp((a+b)/2+r(1,:)*(b-a)/2))
    exact = exp(3.0_p)-exp(-3.0_p)
    print "(i0,1x,g0,1x,g10.2)",n, z, z-exact
  end do
  
  contains 

  function gaussquad(n) result(r)
  integer                 :: n
  real(kind=p), parameter :: pi = 4*atan(1._p)
  real(kind=p)            :: r(2, n), x, f, df, dx
  integer                 :: i,  iter
  real(kind = p), allocatable :: p0(:), p1(:), tmp(:)
  
  p0 = [1._p]
  p1 = [1._p, 0._p]
  
  do k = 2, n
     tmp = ((2*k-1)*[p1,0._p]-(k-1)*[0._p, 0._p,p0])/k
     p0 = p1; p1 = tmp
  end do
  do i = 1, n
    x = cos(pi*(i-0.25_p)/(n+0.5_p))
    do iter = 1, 10
      f = p1(1); df = 0._p
      do k = 2, size(p1)
        df = f + x*df
        f  = p1(k) + x * f
      end do
      dx =  f / df
      x = x - dx
      if (abs(dx)<10*epsilon(dx)) exit
    end do
    r(1,i) = x
    r(2,i) = 2/((1-x**2)*df**2)
  end do
  end function
end program
Task: Chaos game







Python: from __future__ import division

size(300, 260)

background(255)  

x = floor(random(width))
y = floor(random(height))

for _ in range(30000):
    v = floor(random(3))
    if v == 0:
        x = x / 2
        y = y / 2
        colour = color(0, 255, 0)  
    elif v == 1:
        x = width / 2 + (width / 2 - x) / 2
        y = height - (height - y) / 2
        colour = color(255, 0, 0)  
    elif v == 2:
        x = width - (width - x) / 2
        y = y / 2
        colour = color(0, 0, 255)  

    set(x, height - y, colour)




Fortran: PROGRAM CHAOS
 IMPLICIT NONE
 REAL, DIMENSION(3):: KA, KN 
 REAL, DIMENSION(3):: DA, DB, DC 
 INTEGER:: I, Z
 INTEGER, PARAMETER:: UT = 17
 
 DA = (/    0., 0.,   0. /)
 DB = (/  600., 0.,   0. /)
 DC = (/  500., 0., 400. /)
 
 KA = (/  500., 0., 100. /)
 OPEN (UNIT = UT, FILE = 'aus.csv')
 DO I=1, 1000000
  Z = ZAHL()
  WRITE (UT, '(3(F12.6, ";"))') KA
  SELECT CASE (Z)
   CASE (1)
    CALL MITTELP(KA, DA, KN)
   CASE (2)
    CALL MITTELP(KA, DB, KN)
   CASE (3)
    CALL MITTELP(KA, DC, KN)
  END SELECT
  KA = KN
 END DO
 CLOSE (UT)
 CONTAINS
  
  SUBROUTINE MITTELP(P1, P2, MP)
   REAL, INTENT(IN), DIMENSION(3):: P1, P2
   REAL, INTENT(OUT), DIMENSION(3):: MP
   MP = (P1 + P2) / 2.
  END SUBROUTINE MITTELP
  
  INTEGER FUNCTION ZAHL()
   REAL:: ZZ
   CALL RANDOM_NUMBER(ZZ)
   ZZ = ZZ * 3.
   ZAHL = FLOOR(ZZ) + 1
   IF (ZAHL .GT. 3) ZAHL = 3
  END FUNCTION ZAHL
END PROGRAM CHAOS
Task: Vector







Python: v1 = PVector(5, 7)
v2 = PVector(2, 3)

println('{} {} {} {}\n'.format( v1.x, v1.y, v1.mag(), v1.heading()))


println(v1 + v2) 
println(v1 - v2) 
println(v1 * 11) 
println(v1 / 2)  
println('')


println(v1.sub(v1))  
println(v1.add(v2))  
println(v1.mult(10)) 
println(v1.div(10))  




Fortran: MODULE ROSETTA_VECTOR
    IMPLICIT NONE

    TYPE VECTOR
        REAL :: X, Y
    END TYPE VECTOR


    INTERFACE OPERATOR(+)
       MODULE PROCEDURE VECTOR_ADD
    END INTERFACE

    INTERFACE OPERATOR(-)
       MODULE PROCEDURE VECTOR_SUB
    END INTERFACE

    INTERFACE OPERATOR(/)
       MODULE PROCEDURE VECTOR_DIV
    END INTERFACE

    INTERFACE OPERATOR(*)
       MODULE PROCEDURE VECTOR_MULT
    END INTERFACE

    CONTAINS

    FUNCTION VECTOR_ADD(VECTOR_1, VECTOR_2)
        TYPE(VECTOR), INTENT(IN) :: VECTOR_1, VECTOR_2
        TYPE(VECTOR) :: VECTOR_ADD
        VECTOR_ADD%X = VECTOR_1%X+VECTOR_2%X
        VECTOR_ADD%Y = VECTOR_1%Y+VECTOR_2%Y
    END FUNCTION VECTOR_ADD

    FUNCTION VECTOR_SUB(VECTOR_1, VECTOR_2)
        TYPE(VECTOR), INTENT(IN) :: VECTOR_1, VECTOR_2
        TYPE(VECTOR) :: VECTOR_SUB
        VECTOR_SUB%X = VECTOR_1%X-VECTOR_2%X
        VECTOR_SUB%Y = VECTOR_1%Y-VECTOR_2%Y
    END FUNCTION VECTOR_SUB

    FUNCTION VECTOR_DIV(VEC, SCALAR)
        TYPE(VECTOR), INTENT(IN) :: VEC
        REAL, INTENT(IN) :: SCALAR
        TYPE(VECTOR) :: VECTOR_DIV
        VECTOR_DIV%X = VEC%X/SCALAR
        VECTOR_DIV%Y = VEC%Y/SCALAR
    END FUNCTION VECTOR_DIV

    FUNCTION VECTOR_MULT(VEC, SCALAR)
        TYPE(VECTOR), INTENT(IN) :: VEC
        REAL, INTENT(IN) :: SCALAR
        TYPE(VECTOR) :: VECTOR_MULT
        VECTOR_MULT%X = VEC%X*SCALAR
        VECTOR_MULT%Y = VEC%Y*SCALAR
    END FUNCTION VECTOR_MULT

    FUNCTION FROM_RTHETA(R, THETA)
        REAL :: R, THETA
        TYPE(VECTOR) :: FROM_RTHETA
        FROM_RTHETA%X = R*SIN(THETA)
        FROM_RTHETA%Y = R*COS(THETA)
    END FUNCTION FROM_RTHETA

    FUNCTION FROM_XY(X, Y)
        REAL :: X, Y
        TYPE(VECTOR) :: FROM_XY
        FROM_XY%X = X
        FROM_XY%Y = Y
    END FUNCTION FROM_XY

    FUNCTION PRETTY_PRINT(VEC)
        TYPE(VECTOR), INTENT(IN) :: VEC
        CHARACTER(LEN=100) PRETTY_PRINT
        WRITE(PRETTY_PRINT,"(A, F0.5, A, F0.5, A)") "[", VEC%X, ", ", VEC%Y, "]"
    END FUNCTION PRETTY_PRINT
END MODULE ROSETTA_VECTOR

PROGRAM VECTOR_DEMO
    USE ROSETTA_VECTOR
    IMPLICIT NONE

    TYPE(VECTOR) :: VECTOR_1, VECTOR_2
    REAL, PARAMETER :: PI = 4*ATAN(1.0)
    REAL :: SCALAR

    SCALAR = 2.0

    VECTOR_1 = FROM_XY(2.0, 3.0)
    VECTOR_2 = FROM_RTHETA(2.0, PI/6.0)

    WRITE(*,*) "VECTOR_1 (X: 2.0, Y: 3.0)      : ", PRETTY_PRINT(VECTOR_1)
    WRITE(*,*) "VECTOR_2 (R: 2.0, THETA: PI/6) : ", PRETTY_PRINT(VECTOR_2)
    WRITE(*,*) NEW_LINE('A')
    WRITE(*,*) "VECTOR_1  +  VECTOR_2          = ", PRETTY_PRINT(VECTOR_1+VECTOR_2)
    WRITE(*,*) "VECTOR_1  -  VECTOR_2          = ", PRETTY_PRINT(VECTOR_1-VECTOR_2)
    WRITE(*,*) "VECTOR_1  /  2.0               = ", PRETTY_PRINT(VECTOR_1/SCALAR)
    WRITE(*,*) "VECTOR_1  *  2.0               = ", PRETTY_PRINT(VECTOR_1*SCALAR)
END PROGRAM VECTOR_DEMO
Task: Prime conspiracy







Python: def isPrime(n):
    if n < 2:
        return False
    if n % 2 == 0:
        return n == 2
    if n % 3 == 0:
        return n == 3

    d = 5
    while d * d <= n:
        if n % d == 0:
            return False
        d += 2

        if n % d == 0:
            return False
        d += 4
    return True

def generatePrimes():
    yield 2
    yield 3

    p = 5
    while p > 0:
        if isPrime(p):
            yield p
        p += 2
        if isPrime(p):
            yield p
        p += 4

g = generatePrimes()
transMap = {}
prev = None
limit = 1000000
for _ in xrange(limit):
    prime = next(g)
    if prev:
        transition = (prev, prime %10)
        if transition in transMap:
            transMap[transition] += 1
        else:
            transMap[transition] = 1
    prev = prime % 10

print "First {:,} primes. Transitions prime % 10 > next-prime % 10.".format(limit)
for trans in sorted(transMap):
    print "{0} -> {1} count {2:5} frequency: {3}%".format(trans[0], trans[1], transMap[trans], 100.0 * transMap[trans] / limit)




Fortran:       PROGRAM INHERIT	
      USE PRIMEBAG	
      INTEGER MBASE,P0,NHIC	
      PARAMETER (MBASE = 13, P0 = 2, NHIC = 100000000)	
      INTEGER N(0:MBASE - 1,0:MBASE - 1,2:MBASE)	
      INTEGER I,B,D1,D2	
      INTEGER P,PP	

      MSG = 6		
      WRITE (MSG,1) MBASE,P0,NHIC	
    1 FORMAT ("Working in base 2 to ",I0," count the transitions "
     1 "from the low-order digit of one prime number ",/,
     2 "to the low-order digit of its successor. Starting with ",I0,
     3 " and making ",I0," advances.")
      IF (.NOT.GRASPPRIMEBAG(66)) STOP "Gan't grab my file

Chug through the primes.
   10 N = 0	
      P = P0	
      DO I = 1,NHIC	
        PP = P			
        P = NEXTPRIME(P)	
        DO B = 2,MBASE		
          D1 = MOD(PP,B)		
          D2 = MOD(P,B)			
          N(D1,D2,B) = N(D1,D2,B) + 1	
        END DO			
      END DO		
      WRITE (MSG,11) P	
   11 FORMAT ("Ending with ",I0)	

Cast forth the results.
   20 DO B = 2,MBASE	
        WRITE (MSG,21) B		
   21   FORMAT (/,"For base ",I0)	
        WRITE (MSG,22) (D1, D1 = 0,B - 1)	
   22   FORMAT (" Last digit ending  ",I2,66I9)	
        DO D2 = 0,B - 1		
          IF (ALL(N(0:B - 1,D2,B).EQ.0)) CYCLE	
          WRITE (MSG,23) D2,N(0:B - 1,D2,B)	
   23     FORMAT (" next prime ends",I3,":",I2,66I9)	
        END DO			
      END DO		
      END
Task: Statistics_Normal distribution







Python: from __future__ import division
import matplotlib.pyplot as plt 
import random

mean, stddev, size = 50, 4, 100000
data = [random.gauss(mean, stddev) for c in range(size)]

mn = sum(data) / size
sd = (sum(x*x for x in data) / size 
      - (sum(data) / size) ** 2) ** 0.5

print("Sample mean = %g; Stddev = %g; max = %g; min = %g for %i values" 
      % (mn, sd, max(data), min(data), size))

plt.hist(data,bins=50)




Fortran: program Normal_Distribution
  implicit none

  integer, parameter :: i64 = selected_int_kind(18)
  integer, parameter :: r64 = selected_real_kind(15)
  integer(i64), parameter :: samples = 1000000_i64
  real(r64) :: mean, stddev
  real(r64) :: sumn = 0, sumnsq = 0
  integer(i64) :: n = 0 
  integer(i64) :: bin(-50:50) = 0
  integer :: i, ind
  real(r64) :: ur1, ur2, nr1, nr2, s
  
  n = 0
  do while(n <= samples)
    call random_number(ur1)
    call random_number(ur2)
    ur1 = ur1 * 2.0 - 1.0
    ur2 = ur2 * 2.0 - 1.0
    
    s = ur1*ur1 + ur2*ur2  
    if(s >= 1.0_r64) cycle
      
    nr1 = ur1 * sqrt(-2.0*log(s)/s)
    ind = floor(5.0*nr1)
    bin(ind) = bin(ind) + 1_i64
    sumn = sumn + nr1
    sumnsq = sumnsq + nr1*nr1
    
    nr2 = ur2 * sqrt(-2.0*log(s)/s)
    ind = floor(5.0*nr2)
    bin(ind) = bin(ind) + 1_i64
    sumn = sumn + nr2
    sumnsq = sumnsq + nr2*nr2
    n = n + 2_i64
  end do
 
  mean = sumn / n
  stddev = sqrt(sumnsq/n - mean*mean)
  
  write(*, "(a, i0)") "sample size = ", samples
  write(*, "(a, f17.15)") "Mean :   ", mean,
  write(*, "(a, f17.15)") "Stddev : ", stddev
  
  do i = -15, 15 
    write(*, "(f4.1, a, a)") real(i)/5.0, ": ", repeat("=", int(bin(i)*500/samples))
  end do
       
end program
Task: The sieve of Sundaram







Python: from numpy import log

def sieve_of_Sundaram(nth, print_all=True):
    
    assert nth > 0, "nth must be a positive integer"
    k = int((2.4 * nth * log(nth)) // 2)  
    integers_list = [True] * k
    for i in range(1, k):
        j = i
        while i + j + 2 * i * j < k:
            integers_list[i + j + 2 * i * j] = False
            j += 1
    pcount = 0
    for i in range(1, k + 1):
        if integers_list[i]:
            pcount += 1
            if print_all:
                print(f"{2 * i + 1:4}", end=' ')
                if pcount % 10 == 0:
                    print()

            if pcount == nth:
                print(f"\nSundaram primes start with 3. The {nth}th Sundaram prime is {2 * i + 1}.\n")
                break



sieve_of_Sundaram(100, True)

sieve_of_Sundaram(1000000, False)




Fortran:       PROGRAM SUNDARAM
      IMPLICIT NONE



      INTEGER(8)  ::  curr_index
      INTEGER(8)  ::  i
      INTEGER(8)  ::  j
      INTEGER  ::  lim
      INTEGER(8)  ::  mid
      INTEGER  ::  primcount
      LOGICAL*1 , ALLOCATABLE , DIMENSION(:)  ::  primes 
      lim = 10000000 
      ALLOCATE(primes(lim))
      primes(1:lim) = .TRUE.
                        
      mid = lim/2
 

      DO j = 1 , mid
         DO i = 1 , j
            curr_index = i + j + (2*i*j)
            IF( curr_index>lim )EXIT        
            primes(curr_index) = .FALSE.    
         END DO
      END DO

      i = 0
      j = 0
      WRITE(6 , *)'The first 100 primes:'
      DO WHILE ( i < 100 )
         j = j + 1
         IF( primes(j) )THEN
            WRITE(6 , 34 , ADVANCE = 'no')j*2 + 1   
 34         FORMAT(I0 , 1x)
            i = i + 1                       
            IF( MOD(i,10)==0 )WRITE(6 , *)' '
         END IF
      END DO

      primcount = 0
      DO i = 1 , lim
         IF( primes(i) )THEN
            primcount = primcount + 1
            IF( primcount==1000000 )THEN
               WRITE(6 , 35)'1 millionth Prime Found: ' , (i*2) + 1
 35            FORMAT(/ , a , i0)
               EXIT
            END IF
         END IF
      END DO
      DEALLOCATE(primes)
      STOP
      END PROGRAM SUNDARAM