WeixiangYan/CodeTransOcean huggingface dataset:
Task: Mertens function




Go: package main

import "fmt"

func mertens(to int) ([]int, int, int) {
    if to < 1 {
        to = 1
    }
    merts := make([]int, to+1)
    primes := []int{2}
    var sum, zeros, crosses int
    for i := 1; i <= to; i++ {
        j := i
        cp := 0      
        spf := false 
        for _, p := range primes {
            if p > j {
                break
            }
            if j%p == 0 {
                j /= p
                cp++
            }
            if j%p == 0 {
                spf = true
                break
            }
        }
        if cp == 0 && i > 2 {
            cp = 1
            primes = append(primes, i)
        }
        if !spf {
            if cp%2 == 0 {
                sum++
            } else {
                sum--
            }
        }
        merts[i] = sum
        if sum == 0 {
            zeros++
            if i > 1 && merts[i-1] != 0 {
                crosses++
            }
        }
    }
    return merts, zeros, crosses
}

func main() {
    merts, zeros, crosses := mertens(1000)
    fmt.Println("Mertens sequence - First 199 terms:")
    for i := 0; i < 200; i++ {
        if i == 0 {
            fmt.Print("    ")
            continue
        }
        if i%20 == 0 {
            fmt.Println()
        }
        fmt.Printf("  % d", merts[i])
    }
    fmt.Println("\n\nEquals zero", zeros, "times between 1 and 1000")
    fmt.Println("\nCrosses zero", crosses, "times between 1 and 1000")
}







Fortran:       program Mertens
      implicit none
      integer M(1000), n, k, zero, cross
       
C     Generate Mertens numbers       
      M(1) = 1
      do 10 n=2, 1000
          M(n) = 1
          do 10 k=2, n
              M(n) = M(n) - M(n/k)
 10   continue 

C     Print table
      write (*,"('The first 99 Mertens numbers are:')")
      write (*,"('   ')",advance='no')
      k = 9
      do 20 n=1, 99
          write (*,'(I3)',advance='no') M(n)
          k = k-1
          if (k .EQ. 0) then
              k=10
              write (*,*)
          end if
 20   continue
 
C     Calculate zeroes and crossings
      zero = 0
      cross = 0
      do 30 n=2, 1000
          if (M(n) .EQ. 0) then
              zero = zero + 1
              if (M(n-1) .NE. 0) cross = cross+1
          end if    
 30   continue 
 
 40   format("M(N) is zero ",I2," times.")
      write (*,40) zero
 50   format("M(N) crosses zero ",I2," times.")
      write (*,50) cross
      end program
Task: Two sum




Go: package main

import "fmt"

func twoSum(a []int, targetSum int) (int, int, bool) {
    len := len(a)
    if len < 2 {
        return 0, 0, false
    }
    for i := 0; i < len - 1; i++ {
        if a[i] <= targetSum {
            for j := i + 1; j < len; j++ {
                sum := a[i] + a[j]
                if sum == targetSum {
                    return i, j, true
                }
                if sum > targetSum {
                    break
                }
            }
        } else {
            break
        }
    }
    return 0, 0, false
}

func main() {
    a := []int {0, 2, 11, 19, 90}
    targetSum := 21
    p1, p2, ok := twoSum(a, targetSum)
    if (!ok) {
        fmt.Println("No two numbers were found whose sum is", targetSum)
    } else {
        fmt.Println("The numbers with indices", p1, "and", p2, "sum to", targetSum)
    }
}







Fortran: program twosum
  implicit none

  integer, parameter, dimension(5) :: list = (/ 0, 2, 11, 19, 90/)
  integer, parameter :: target_val = 21
  integer :: nelem
  integer :: i, j
  logical :: success = .false.

  nelem = size(list)
  outer:do i = 1,nelem
     do j = i+1,nelem
        success = list(i) + list(j) == target_val
        if (success) exit outer
     end do
  end do outer

  if (success) then
     
     print('("(",2(i3.1,1X),")",3(A1,i3.1))'), i,j, ":", list(i), "+", list(j), "=", target_val
  else
     print*, "Failed"
  end if

end program twosum
Task: I before E except after C




Go: package main

import (
	"bufio"
	"fmt"
	"log"
	"os"
	"regexp"
	"strings"
)

func main() {
	f, err := os.Open("unixdict.txt")
	if err != nil {
		log.Fatalln(err)
	}
	defer f.Close()

	s := bufio.NewScanner(f)
	rie := regexp.MustCompile("^ie|[^c]ie")
	rei := regexp.MustCompile("^ei|[^c]ei")
	var cie, ie int
	var cei, ei int
	for s.Scan() {
		line := s.Text()
		if strings.Contains(line, "cie") {
			cie++
		}
		if strings.Contains(line, "cei") {
			cei++
		}
		if rie.MatchString(line) {
			ie++
		}
		if rei.MatchString(line) {
			ei++
		}
	}
	err = s.Err()
	if err != nil {
		log.Fatalln(err)
	}

	if check(ie, ei, "I before E when not preceded by C") &&
		check(cei, cie, "E before I when preceded by C") {
		fmt.Println("Both plausable.")
		fmt.Println(`"I before E, except after C" is plausable.`)
	} else {
		fmt.Println("One or both implausable.")
		fmt.Println(`"I before E, except after C" is implausable.`)
	}
}



func check(a, b int, s string) bool {
	switch {
	case a > b*2:
		fmt.Printf("%q is plausible (%d vs %d).\n", s, a, b)
		return true
	case a >= b:
		fmt.Printf("%q is implausible (%d vs %d).\n", s, a, b)
	default:
		fmt.Printf("%q is implausible and contra-indicated (%d vs %d).\n",
			s, a, b)
	}
	return false
}







Fortran: 













program cia
  implicit none
  character (len=256) :: s
  integer :: ie, ei, cie, cei
  integer :: ios
  data ie, ei, cie, cei/4*0/
  do while (.true.)
    read(5,*,iostat = ios)s
    if (0 .ne. ios) then
      exit
    endif
    call lower_case(s)
    cie = cie + occurrences(s, 'cie')
    cei = cei + occurrences(s, 'cei')
    ie = ie + occurrences(s, 'ie')
    ei = ei + occurrences(s, 'ei')
  enddo
  write(6,'(1x,4(a4,1x))') 'ie','ei','cie','cei'
  write(6,'(1x,4(i4,1x))') ie,ei,cie,cei 
  write(6,'(1x,2(a,1x))') '        [^c]ie',plausibility(ie,ei)
  write(6,'(1x,2(a,1x))') '           cei',plausibility(cei,cie)
  write(6,'(1x,2(a,1x))') '([^c]ie)|(cei)',plausibility(ie+cei,ei+cie)

contains

  subroutine lower_case(s)
    character(len=*), intent(inout) :: s
    integer :: i
    do i=1, len_trim(s)
      s(i:i) = achar(ior(iachar(s(i:i)),32))
    enddo
  end subroutine lower_case

  integer function occurrences(a,b)
    character(len=*), intent(in) :: a, b
    integer :: i, j, n
    n = 0
    i = 0
    j = index(a, b)
    do while (0 .lt. j)
      n = n+1
      i = i+len(b)+j-1
      j = index(a(i:), b)
    end do
    occurrences = n
  end function occurrences

  character*(32) function plausibility(da, nyet)
    integer, intent(in) :: da, nyet
    
    if (nyet*2 .lt. da) then
      plausibility = 'plausible'
    else
      plausibility = 'implausible'
    endif
  end function plausibility
end program cia
Task: Arithmetic-geometric mean_Calculate Pi




Go: package main

import (
    "fmt"
    "math/big"
)

func main() {
    one := big.NewFloat(1)
    two := big.NewFloat(2)
    four := big.NewFloat(4)
    prec := uint(768) 

    a := big.NewFloat(1).SetPrec(prec)
    g := new(big.Float).SetPrec(prec)

    
    t := new(big.Float).SetPrec(prec)
    u := new(big.Float).SetPrec(prec)

    g.Quo(a, t.Sqrt(two))
    sum := new(big.Float)
    pow := big.NewFloat(2)

    for a.Cmp(g) != 0 {
        t.Add(a, g)
        t.Quo(t, two)
        g.Sqrt(u.Mul(a, g))
        a.Set(t)
        pow.Mul(pow, two)
        t.Sub(t.Mul(a, a), u.Mul(g, g))
        sum.Add(sum, t.Mul(t, pow))
    }

    t.Mul(a, a)
    t.Mul(t, four)
    pi := t.Quo(t, u.Sub(one, sum))
    fmt.Println(pi)
}







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




Go: package main

import (
	"fmt"
	"math/big"
	"time"

	"github.com/jbarham/primegen.go"
)

func main() {
	start := time.Now()
	pg := primegen.New()
	var i uint64
	p := big.NewInt(1)
	tmp := new(big.Int)
	for i <= 9 {
		fmt.Printf("primorial(%v) = %v\n", i, p)
		i++
		p = p.Mul(p, tmp.SetUint64(pg.Next()))
	}
	for _, j := range []uint64{1e1, 1e2, 1e3, 1e4, 1e5, 1e6} {
		for i < j {
			i++
			p = p.Mul(p, tmp.SetUint64(pg.Next()))
		}
		fmt.Printf("primorial(%v) has %v digits", i, len(p.String()))
		fmt.Printf("\t(after %v)\n", time.Since(start))
	}
}







Fortran:       B.DIGIT(I) = MOD(D,BIGBASE)
      C = D/BIGBASE
Task: Chaos game




Go: package main

import (
	"fmt"
	"image"
	"image/color"
	"image/draw"
	"image/gif"
	"log"
	"math"
	"math/rand"
	"os"
	"time"
)

var bwPalette = color.Palette{
	color.Transparent,
	color.White,
	color.RGBA{R: 0xff, A: 0xff},
	color.RGBA{G: 0xff, A: 0xff},
	color.RGBA{B: 0xff, A: 0xff},
}

func main() {
	const (
		width          = 160
		frames         = 100
		pointsPerFrame = 50
		delay          = 100 * time.Millisecond
		filename       = "chaos_anim.gif"
	)

	var tan60 = math.Sin(math.Pi / 3)
	height := int(math.Round(float64(width) * tan60))
	b := image.Rect(0, 0, width, height)
	vertices := [...]image.Point{
		{0, height}, {width, height}, {width / 2, 0},
	}

	
	m := image.NewPaletted(b, bwPalette)
	for y := b.Min.Y; y < b.Max.Y; y++ {
		bg := int(math.Round(float64(b.Max.Y-y) / 2 / tan60))
		for x := b.Min.X + bg; x < b.Max.X-bg; x++ {
			m.SetColorIndex(x, y, 1)
		}
	}

	
	var p image.Point
	rand.Seed(time.Now().UnixNano())
	p.Y = rand.Intn(height) + b.Min.Y
	p.X = rand.Intn(width) + b.Min.X 

	anim := newAnim(frames, delay)
	addFrame(anim, m)
	for i := 1; i < frames; i++ {
		for j := 0; j < pointsPerFrame; j++ {
			
			vi := rand.Intn(len(vertices))
			v := vertices[vi]
			
			p.X = (p.X + v.X) / 2
			p.Y = (p.Y + v.Y) / 2
			m.SetColorIndex(p.X, p.Y, uint8(2+vi))
		}
		addFrame(anim, m)
	}
	if err := writeAnim(anim, filename); err != nil {
		log.Fatal(err)
	}
	fmt.Printf("wrote to %q\n", filename)
}



func newAnim(frames int, delay time.Duration) *gif.GIF {
	const gifDelayScale = 10 * time.Millisecond
	g := &gif.GIF{
		Image: make([]*image.Paletted, 0, frames),
		Delay: make([]int, 1, frames),
	}
	g.Delay[0] = int(delay / gifDelayScale)
	return g
}
func addFrame(anim *gif.GIF, m *image.Paletted) {
	b := m.Bounds()
	dst := image.NewPaletted(b, m.Palette)
	draw.Draw(dst, b, m, image.ZP, draw.Src)
	anim.Image = append(anim.Image, dst)
	if len(anim.Delay) < len(anim.Image) {
		anim.Delay = append(anim.Delay, anim.Delay[0])
	}
}
func writeAnim(anim *gif.GIF, filename string) error {
	f, err := os.Create(filename)
	if err != nil {
		return err
	}
	err = gif.EncodeAll(f, anim)
	if cerr := f.Close(); err == nil {
		err = cerr
	}
	return err
}







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: Find first and last set bit of a long integer

C: #include <stdio.h>
#include <stdint.h>

uint32_t msb32(uint32_t n)
{
	uint32_t b = 1;
	if (!n) return 0;

#define step(x) if (n >= ((uint32_t)1) << x) b <<= x, n >>= x
	step(16); step(8); step(4); step(2); step(1);
#undef step
	return b;
}

int msb32_idx(uint32_t n)
{
	int b = 0;
	if (!n) return -1;

#define step(x) if (n >= ((uint32_t)1) << x) b += x, n >>= x
	step(16); step(8); step(4); step(2); step(1);
#undef step
	return b;
}

#define lsb32(n) ( (uint32_t)(n) & -(int32_t)(n) )


inline int lsb32_idx(uint32_t n) { return msb32_idx(lsb32(n)); }

int main()
{
	int32_t n;
	int i;

	for (i = 0, n = 1; ; i++, n *= 42) {
		printf("42**%d = %10d(x%08x): M x%08x(%2d) L x%03x(%2d)\n",
			i, n, n,
			msb32(n), msb32_idx(n),
			lsb32(n), lsb32_idx(n));

		if (n >= INT32_MAX / 42) break;
	}

	return 0;
}










Fortran: program bits
    implicit none
    integer :: n = 1, i

    do i = 1, 6
        print "(B32,2(' ',I2))", n, trailz(n), 31 - leadz(n)
        n = 42 * n
    end do
end program
Task: Enforced immutability

C: #define PI      3.14159265358979323
#define MINSIZE 10
#define MAXSIZE 100










Fortran: real, parameter :: pi = 3.141593
Task: Hofstadter Q sequence

C: #include <stdio.h>
#include <stdlib.h>

#define N 100000
int main()
{
	int i, flip, *q = (int*)malloc(sizeof(int) * N) - 1;

	q[1] = q[2] = 1;

	for (i = 3; i <= N; i++)
		q[i] = q[i - q[i - 1]] + q[i - q[i - 2]];
		
	for (i = 1; i <= 10; i++)
		printf("%d%c", q[i], i == 10 ? '\n' : ' ');

	printf("%d\n", q[1000]);

	for (flip = 0, i = 1; i < N; i++)
		flip += q[i] > q[i + 1];

	printf("flips: %d\n", flip);
	return 0;
}










Fortran: Calculate the Hofstadter Q-sequence, using a big array rather than recursion.
      INTEGER ENUFF
      PARAMETER (ENUFF = 100000)
      INTEGER Q(ENUFF)	

      Q(1) = 1		
      Q(2) = 1
      Q(3:) = -123456789
      DO I = 3,ENUFF	
        Q(I) = Q(I - Q(I - 1)) + Q(I - Q(I - 2))	
      END DO
Cast forth results as per the specification.
      WRITE (6,1) Q(1:10)		
    1 FORMAT ("First ten values:",10I2)	
      WRITE (6,*) "Q(1000) =",Q(1000)	
      WRITE (6,3) ENUFF,COUNT(Q(2:ENUFF) < Q(1:ENUFF - 1))	
    3 FORMAT ("Count of those elements 2:",I0,
     1 " which are less than their predecessor: ",I0)	
Curry favour by allowing enquiries.
   10 WRITE (6,11) ENUFF
   11 FORMAT ("Nominate an index (in 1:",I0,"): ",$)	
      READ (5,*,END = 999, ERR = 999) I	
      IF (I.GT.0 .AND. I.LE.ENUFF) THEN	
        WRITE (6,12) I,Q(I)		
   12   FORMAT ("Q(",I0,") = ",I0)	
        GO TO 10			
      END IF		
Closedown.
  999 WRITE (6,*) "Bye."
      END
Task: Count occurrences of a substring

C: #include <stdio.h>
#include <string.h>

int match(const char *s, const char *p, int overlap)
{
        int c = 0, l = strlen(p);

        while (*s != '\0') {
                if (strncmp(s++, p, l)) continue;
                if (!overlap) s += l - 1;
                c++;
        }
        return c;
}

int main()
{
        printf("%d\n", match("the three truths", "th", 0));
        printf("overlap:%d\n", match("abababababa", "aba", 1));
        printf("not:    %d\n", match("abababababa", "aba", 0));
        return 0;
}










Fortran: program Example
  implicit none
  integer :: n
  
  n = countsubstring("the three truths", "th")
  write(*,*) n
  n = countsubstring("ababababab", "abab")
  write(*,*) n
  n = countsubstring("abaabba*bbaba*bbab", "a*b")
  write(*,*) n
 
contains

function countsubstring(s1, s2) result(c)
  character(*), intent(in) :: s1, s2
  integer :: c, p, posn
 
  c = 0
  if(len(s2) == 0) return
  p = 1
  do 
    posn = index(s1(p:), s2)
    if(posn == 0) return
    c = c + 1
    p = p + posn + len(s2) - 1
  end do
end function
end program
Task: Carmichael 3 strong pseudoprimes

C: #include <stdio.h>


#define mod(n,m) ((((n) % (m)) + (m)) % (m))

int is_prime(unsigned int n)
{
    if (n <= 3) {
        return n > 1;
    }
    else if (!(n % 2) || !(n % 3)) {
        return 0;
    }
    else {
        unsigned int i;
        for (i = 5; i*i <= n; i += 6)
            if (!(n % i) || !(n % (i + 2)))
                return 0;
        return 1;
    }
}

void carmichael3(int p1)
{
    if (!is_prime(p1)) return;

    int h3, d, p2, p3;
    for (h3 = 1; h3 < p1; ++h3) {
        for (d = 1; d < h3 + p1; ++d) {
            if ((h3 + p1)*(p1 - 1) % d == 0 && mod(-p1 * p1, h3) == d % h3) {
                p2 = 1 + ((p1 - 1) * (h3 + p1)/d);
                if (!is_prime(p2)) continue;
                p3 = 1 + (p1 * p2 / h3);
                if (!is_prime(p3) || (p2 * p3) % (p1 - 1) != 1) continue;
                printf("%d %d %d\n", p1, p2, p3);
            }
        }
    }
}

int main(void)
{
    int p1;
    for (p1 = 2; p1 < 62; ++p1)
        carmichael3(p1);
    return 0;
}










Fortran:       LOGICAL FUNCTION ISPRIME(N)	
       INTEGER N			
       INTEGER F			
        ISPRIME = .FALSE.		
        DO F = 2,SQRT(DFLOAT(N))	
          IF (MOD(N,F).EQ.0) RETURN	
        END DO				
        ISPRIME = .TRUE.		
      END FUNCTION ISPRIME		

      PROGRAM CHASE
      INTEGER P1,P2,P3	
      INTEGER H3,D	
      INTEGER MSG	
      MSG = 6		
      WRITE (MSG,1)	
    1 FORMAT ("Carmichael numbers that are the product of three primes:"
     & /"    P1  x P2  x P3 =",9X,"C")
      DO P1 = 2,61	
        IF (ISPRIME(P1)) THEN	
          DO H3 = 2,P1 - 1		
            DO D = 1,H3 + P1 - 1		
              IF (MOD((H3 + P1)*(P1 - 1),D).EQ.0	
     &        .AND. (MOD(H3 + MOD(-P1**2,H3),H3) .EQ. MOD(D,H3))) THEN	
                P2 = 1 + (P1 - 1)*(H3 + P1)/D	
                IF (ISPRIME(P2)) THEN		
                  P3 = 1 + P1*P2/H3			
                  IF (ISPRIME(P3)) THEN			
                    IF (MOD(P2*P3,P1 - 1).EQ.1) THEN		
                      WRITE (MSG,2) P1,P2,P3, INT8(P1)*P2*P3		
    2                 FORMAT (3I6,I12)
                    END IF
                  END IF
                END IF
              END IF
            END DO
          END DO
        END IF
      END DO
      END
Task: Rock-paper-scissors

C: #include <stdio.h>
#include <stdlib.h>
#define LEN 3 


int rand_idx(double *p, int n)
{
	double s = rand() / (RAND_MAX + 1.0);
	int i;
	for (i = 0; i < n - 1 && (s -= p[i]) >= 0; i++);
	return i;
}

int main()
{
	int user_action, my_action;
	int user_rec[] = {0, 0, 0};
	const char *names[] = { "Rock", "Paper", "Scissors" };
	char str[2];
	const char *winner[] = { "We tied.", "Meself winned.", "You win." };
	double  p[LEN] = { 1./3, 1./3, 1./3 };
 
	while (1) {
		my_action = rand_idx(p,LEN);
 
		printf("\nYour choice [1-3]:\n"
			"  1. Rock\n  2. Paper\n  3. Scissors\n> ");
 
		
		if (!scanf("%d", &user_action)) {
			scanf("%1s", str);
			if (*str == 'q') {
				printf("Your choices [rock : %d , paper :  %d , scissors %d] ",user_rec[0],user_rec[1], user_rec[2]); 
				return 0;
			}
			continue;
		}
		user_action --;
		if (user_action > 2 || user_action < 0) {
			printf("invalid choice; again\n");
			continue;
		}
		printf("You chose %s; I chose %s. %s\n",
			names[user_action], names[my_action],
			winner[(my_action - user_action + 3) % 3]);
 
		user_rec[user_action]++;
	}
}










Fortran: 


















program rpsgame

  integer, parameter :: COMPUTER=1, HAPLESSUSER=2
  integer, dimension(3) :: rps = (/1,1,1/)
  real, dimension(3) :: p
  character :: answer, cc 
  integer :: exhaustion, i
  real, dimension(2) :: score = (/0, 0/)
  character(len=8), dimension(3) :: choices = (/'rock    ','paper   ','scissors'/)
  real :: harvest
  do exhaustion = 1, 30
    p = rps/real(sum(rps))
    p(2) = p(2) + p(1)
    p(3) = p(3) + p(2)
    call random_number(harvest)
    i = sum(merge(1,0,harvest.le.p)) 
    cc = 'rsp'(i:i)
    write(6, "(2(A,', '),A,'?  ')", advance='no')(trim(choices(i)),i=1,size(choices))
    read(5, *) answer
    write(6, "('scoring computer choice (',A,') and your choice (',A,')')")cc,answer
    if (answer.eq.cc) then
      score = score + 0.5
    else
      i = HAPLESSUSER
      if (answer.eq.'r') then
        if (cc.eq.'p') i = COMPUTER
      else if (answer.eq.'p') then
        if (cc.eq.'s') i = COMPUTER
      else if (answer.eq.'s') then
        if (cc.eq.'r') i = COMPUTER
      else
        exit
      endif
      score(i) = score(i) + 1
    end if
    i = scan('rps',answer)
    rps(i) = rps(i) + 1
  end do
  if (25 .lt. exhaustion) write(6, *) "I'm bored out of my skull"
  write(6, *)"Who's keeping score anyway???"
  write(6, '(2f5.1)') score
  if (score(COMPUTER) .lt. score(HAPLESSUSER)) print*,'you won
end program rpsgame
Task: Benford's law

C: #include <stdio.h>
#include <stdlib.h>
#include <math.h>

float *benford_distribution(void)
{
    static float prob[9];
    for (int i = 1; i < 10; i++)
        prob[i - 1] = log10f(1 + 1.0 / i);

    return prob;
}

float *get_actual_distribution(char *fn)
{
    FILE *input = fopen(fn, "r");
    if (!input)
    {
        perror("Can't open file");
        exit(EXIT_FAILURE);
    }

    int tally[9] = { 0 };
    char c;
    int total = 0;
    while ((c = getc(input)) != EOF)
    {
        
        while (c < '1' || c > '9')
            c = getc(input);

        tally[c - '1']++;
        total++;

        
        while ((c = getc(input)) != '\n' && c != EOF)
            ;
    }
    fclose(input);
    
    static float freq[9];
    for (int i = 0; i < 9; i++)
        freq[i] = tally[i] / (float) total;

    return freq;
}

int main(int argc, char **argv)
{
    if (argc != 2)
    {
        printf("Usage: benford <file>\n");
        return EXIT_FAILURE;
    }

    float *actual = get_actual_distribution(argv[1]);
    float *expected = benford_distribution();  

    puts("digit\tactual\texpected");
    for (int i = 0; i < 9; i++)
        printf("%d\t%.3f\t%.3f\n", i + 1, actual[i], expected[i]);

    return EXIT_SUCCESS;
}










Fortran: -*- mode: compilation; default-directory: "/tmp/" -*-
Compilation started at Sat May 18 01:13:00

a=./f && make $a && $a
f95 -Wall -ffree-form f.F -o f
  0.301030010      0.176091254      0.124938756       9.69100147E-02   7.91812614E-02   6.69467747E-02   5.79919666E-02   5.11525236E-02   4.57575098E-02 THE LAW
  0.300999999      0.177000001      0.125000000       9.60000008E-02   7.99999982E-02   6.70000017E-02   5.70000000E-02   5.29999994E-02   4.50000018E-02 LEADING FIBONACCI DIGIT

Compilation finished at Sat May 18 01:13:00
Task: Hickerson series of almost integers

C: #include <stdio.h>
#include <mpfr.h>

void h(int n)
{
	MPFR_DECL_INIT(a, 200);
	MPFR_DECL_INIT(b, 200);

	mpfr_fac_ui(a, n, MPFR_RNDD);		

	mpfr_set_ui(b, 2, MPFR_RNDD);		
	mpfr_log(b, b, MPFR_RNDD);		
	mpfr_pow_ui(b, b, n + 1, MPFR_RNDD);	

	mpfr_div(a, a, b, MPFR_RNDD);		
	mpfr_div_ui(a, a, 2, MPFR_RNDD);	

	mpfr_frac(b, a, MPFR_RNDD);		
	mpfr_printf("%2d: %23.4Rf  %c\n", n, a,
		mpfr_cmp_d(b, .1) * mpfr_cmp_d(b, .9) > 0 ? 'Y' : 'N');
}

int main(void)
{
	int n;
	for (n = 1; n <= 17; n++) h(n);

	return 0;
}










Fortran: program hickerson
    implicit none
    integer, parameter :: q = selected_real_kind(30)
    integer, parameter :: l = selected_int_kind(15)
    real(q) :: s, l2
    integer :: i, n, k

    l2 = log(2.0_q)
    do n = 1, 17
        s = 0.5_q / l2
        do i = 1, n
            s = (s * i) / l2
        end do

        k = floor((s - floor(s, l)) * 10)
        if (k == 0 .or. k == 9) then
            print 1, n, s, ""
        else
            print 1, n, s, " NOT"
        endif
    end do
  1 format('h(',I2,') = ',F23.3,' is',A,' an almost-integer')
end program
Task: Case-sensitivity of identifiers

C: #include <stdio.h>

static const char *dog = "Benjamin";
static const char *Dog = "Samba";
static const char *DOG = "Bernie";

int main()
{
    printf("The three dogs are named %s, %s and %s.\n", dog, Dog, DOG);
    return 0;
}










Fortran: program Example
  implicit none

  character(8) :: dog, Dog, DOG

  dog = "Benjamin"
  Dog = "Samba"
  DOG = "Bernie"

  if (dog == DOG) then
    write(*,*) "There is just one dog named ", dog
  else
    write(*,*) "The three dogs are named ", dog, Dog, " and ", DOG
  end if

end program Example