WeixiangYan/CodeTransOcean huggingface dataset:
Task: MD5_Implementation







Python: import math

rotate_amounts = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
                  5,  9, 14, 20, 5,  9, 14, 20, 5,  9, 14, 20, 5,  9, 14, 20,
                  4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
                  6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]

constants = [int(abs(math.sin(i+1)) * 2**32) & 0xFFFFFFFF for i in range(64)]

init_values = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]

functions = 16*[lambda b, c, d: (b & c) | (~b & d)] + \
            16*[lambda b, c, d: (d & b) | (~d & c)] + \
            16*[lambda b, c, d: b ^ c ^ d] + \
            16*[lambda b, c, d: c ^ (b | ~d)]

index_functions = 16*[lambda i: i] + \
                  16*[lambda i: (5*i + 1)%16] + \
                  16*[lambda i: (3*i + 5)%16] + \
                  16*[lambda i: (7*i)%16]

def left_rotate(x, amount):
    x &= 0xFFFFFFFF
    return ((x<<amount) | (x>>(32-amount))) & 0xFFFFFFFF

def md5(message):

    message = bytearray(message) 
    orig_len_in_bits = (8 * len(message)) & 0xffffffffffffffff
    message.append(0x80)
    while len(message)%64 != 56:
        message.append(0)
    message += orig_len_in_bits.to_bytes(8, byteorder='little')

    hash_pieces = init_values[:]

    for chunk_ofst in range(0, len(message), 64):
        a, b, c, d = hash_pieces
        chunk = message[chunk_ofst:chunk_ofst+64]
        for i in range(64):
            f = functions[i](b, c, d)
            g = index_functions[i](i)
            to_rotate = a + f + constants[i] + int.from_bytes(chunk[4*g:4*g+4], byteorder='little')
            new_b = (b + left_rotate(to_rotate, rotate_amounts[i])) & 0xFFFFFFFF
            a, b, c, d = d, new_b, b, c
        for i, val in enumerate([a, b, c, d]):
            hash_pieces[i] += val
            hash_pieces[i] &= 0xFFFFFFFF
    
    return sum(x<<(32*i) for i, x in enumerate(hash_pieces))
        
def md5_to_hex(digest):
    raw = digest.to_bytes(16, byteorder='little')
    return '{:032x}'.format(int.from_bytes(raw, byteorder='big'))

if __name__=='__main__':
    demo = [b"", b"a", b"abc", b"message digest", b"abcdefghijklmnopqrstuvwxyz",
            b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
            b"12345678901234567890123456789012345678901234567890123456789012345678901234567890"]
    for message in demo:
        print(md5_to_hex(md5(message)),' <= "',message.decode('ascii'),'"', sep='')





Ada: package MD5 is

   type Int32 is mod 2 ** 32;
   type MD5_Hash is array (1 .. 4) of Int32;
   function MD5 (Input : String) return MD5_Hash;

   
   subtype MD5_String is String (1 .. 34);
   function To_String (Item : MD5_Hash) return MD5_String;

end MD5;
Task: Exponentiation with infix operators in (or operating on) the base







Python: from itertools import product

xx = '-5 +5'.split()
pp = '2 3'.split()
texts = '-x**p -(x)**p (-x)**p -(x**p)'.split()

print('Integer variable exponentiation')
for x, p in product(xx, pp):
    print(f'  x,p = {x:2},{p}; ', end=' ')
    x, p = int(x), int(p)
    print('; '.join(f"{t} =={eval(t):4}" for t in texts))

print('\nBonus integer literal exponentiation')
X, P = 'xp'
xx.insert(0, ' 5')
texts.insert(0, 'x**p')
for x, p in product(xx, pp):
    texts2 = [t.replace(X, x).replace(P, p) for t in texts]
    print(' ', '; '.join(f"{t2} =={eval(t2):4}" for t2 in texts2))





Ada: with Ada.Text_IO; use Ada.Text_IO;
with Ada.Float_Text_IO; use Ada.Float_Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;

procedure Main is
   ivalue : Integer := -5;
   fvalue : float   := -5.0;
begin
   Put_Line("Integer exponentiation:");
   for i in 1..2 loop
      for power in 2..3 loop

         Put("x =" & ivalue'image & " p =" & power'image);
         Put("   -x ** p ");
         Put(item => -ivalue ** power, width => 4);
         Put("   -(x) ** p ");
         Put(item => -(ivalue) ** power, width => 4);
         Put("   (-x) ** p ");
         Put(Item => (- ivalue) ** power, Width => 4);
         Put("   -(x ** p) ");
         Put(Item => -(ivalue ** power), Width => 4);
         New_line;
      end loop;
      ivalue := 5;
      fvalue := 5.0;
   end loop;
   Put_Line("floating point exponentiation:");
   ivalue := -5;
   fvalue := -5.0;

   for i in 1..2 loop
      for power in 2..3 loop
         Put("x =" & fvalue'image & " p =" & power'image);
         Put("   -x ** p ");
         Put(item => -fvalue ** power, fore => 4, Aft => 1, Exp => 0);
         Put("   -(x) ** p ");
         Put(item => -(fvalue) ** power, fore => 4, Aft => 1, Exp => 0);
         Put("   (-x) ** p ");
         Put(Item => (- fvalue) ** power, fore => 4, Aft => 1, Exp => 0);
         Put("   -(x ** p) ");
         Put(Item => -(fvalue ** power), fore => 4, Aft => 1, Exp => 0);
         New_line;
      end loop;
      ivalue := 5;
      fvalue := 5.0;
   end loop;
end Main;
Task: History variables







Python: import sys

HIST = {}

def trace(frame, event, arg):
    for name,val in frame.f_locals.items():
        if name not in HIST:
            HIST[name] = []
        else:
            if HIST[name][-1] is val:
                continue
        HIST[name].append(val)
    return trace

def undo(name):
    HIST[name].pop(-1)
    return HIST[name][-1]

def main():
    a = 10
    a = 20

    for i in range(5):
        c = i

    print "c:", c, "-> undo x3 ->",
    c = undo('c')
    c = undo('c')
    c = undo('c')
    print c
    print 'HIST:', HIST

sys.settrace(trace)
main()





Ada: private with Ada.Containers.Indefinite_Vectors;
generic
   type Item_Type (<>) is private;
package History_Variables is

   type Variable is tagged limited private;

   
   procedure Set(V: in out Variable; Item: Item_Type);
   function Get(V: Variable) return Item_Type;

   
   function Defined(V: Variable) return Natural;

   
   function Peek(V: Variable; Generation: Natural := 1) return Item_Type;
   
   

   
   procedure Undo(V: in out Variable);
   
   
   

private
   package Vectors is new Ada.Containers.Indefinite_Vectors
     (Index_Type   => Positive,
      Element_Type => Item_Type);

   type Variable is tagged limited record
      History: Vectors.Vector;
   end record;
end History_Variables;
Task: Bioinformatics_Subsequence







Python:  
from random import choice
import regex as re 
import time

def generate_sequence(n: int ) -> str:
    return "".join([ choice(['A','C','G','T']) for _ in range(n) ])

def dna_findall(needle: str, haystack: str) -> None:

    if sum(1 for _ in re.finditer(needle, haystack, overlapped=True)) == 0:
        print("No matches found")
    else:
        print(f"Found {needle} at the following indices: ")
        for match in re.finditer(needle, haystack, overlapped=True):
            print(f"{match.start()}:{match.end()} ")

dna_seq = generate_sequence(200)
sample_seq = generate_sequence(4)

c = 1
for i in dna_seq:
    print(i, end="") if c % 20 != 0 else print(f"{i}")
    c += 1
print(f"\nSearch Sample: {sample_seq}")

dna_findall(sample_seq, dna_seq)





Ada: with Ada.Text_Io;
with Ada.Strings.Fixed;
with Ada.Numerics.Discrete_Random;

procedure Sub_Sequence is

   type Nucleotide is (A, C, G, T);

   function To_Character (N : Nucleotide) return Character
   is (case N is
          when A => 'A', when C => 'C',
          when G => 'G', when T => 'T');

   package Random_Nucleotide is new Ada.Numerics.Discrete_Random (Nucleotide);
   use Random_Nucleotide;

   package Position_Io is new Ada.Text_Io.Integer_Io (Natural);
   use Ada.Text_Io;

   procedure Put_Bases (Seq : String; Width : Positive) is
      First : Natural := Seq'First;
   begin
      while First < Seq'Last loop
         declare
            Last : constant Natural :=
              Natural'Min (First + Width - 1, Seq'Last);
         begin
            Position_Io.Put (First); Put ("..");
            Position_Io.Put (Last);  Put (" ");
            Put (Seq (First .. Last));
            New_Line;
            First := Last + 1;
         end;
      end loop;
   end Put_Bases;

   Gen       : Generator;
   Sequence  : String (1 .. 405);
   Substring : String (1 ..   4);
   Pos       : Natural := 0;
begin
   Position_Io.Default_Width := 3;

   Reset (Gen);

   Sequence  := (others => To_Character (Random (Gen)));
   Substring := (others => To_Character (Random (Gen)));

   Put_Line ("Search sequence:");
   Put_Bases (Sequence, Width => 50);
   New_Line;

   Put ("Substring to search: ");
   Put (Substring);
   New_Line;

   loop
      Pos := Ada.Strings.Fixed.Index (Sequence, Substring, Pos + 1);
      exit when Pos = 0;
      Put ("Found at position: ");
      Position_Io.Put (Pos); Put ("..");
      Position_Io.Put (Pos + Substring'Length - 1);
      New_Line;
   end loop;
end Sub_Sequence;
Task: Reverse the order of lines in a text file while preserving the contents of each line







Python: 

import sys

if len(sys.argv)!=2:
    print("Usage : python " + sys.argv[0] + " <filename>")
    exit()

dataFile = open(sys.argv[1],"r")

fileData = dataFile.read().split('\n')

dataFile.close()

[print(i) for i in fileData[::-1]]





Ada: with Ada.Text_Io;
with Ada.Containers.Indefinite_Vectors;
with Ada.Command_Line;

procedure Reverse_Lines_In_File is

   subtype Line_Number is Natural;

   package Line_Vectors
   is new Ada.Containers.Indefinite_Vectors
     (Index_Type   => Line_Number,
      Element_Type => String);

   use Line_Vectors,
     Ada.Text_Io,
     Ada.Command_Line;

   File   : File_Type;
   Buffer : Vector;
begin
   if Argument_Count = 1 then
      Open (File, In_File, Argument (1));
      Set_Input (File);
   end if;

   while not End_Of_File loop
      Buffer.Prepend (Get_Line);
   end loop;

   if Is_Open (File) then
      Close (File);
   end if;

   for Line of Buffer loop
      Put_Line (Line);
   end loop;

end Reverse_Lines_In_File;
Task: Positive decimal integers with the digit 1 occurring exactly twice







Python: 

from itertools import permutations

for i in range(0,10):
    if i!=1:
        baseList = [1,1]
        baseList.append(i)
        [print(int(''.join(map(str,j)))) for j in sorted(set(permutations(baseList)))]





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

procedure Positives_With_1_Twice is

   function One_Twice (N : Positive) return Boolean is
      NN        : Natural := N;
      One_Count : Natural := 0;
   begin
      while NN > 0 loop
         if NN mod 10 = 1 then
            One_Count := One_Count + 1;
         end if;
         NN := NN / 10;
      end loop;
      return One_Count = 2;
   end One_Twice;

begin
   for N in 1 .. 999 loop
      if One_Twice (N) then
         Put (N'Image); Put (" ");
      end if;
   end loop;
   New_Line;
end Positives_With_1_Twice;
Task: Unique characters in each string







Python: LIST = ["1a3c52debeffd", "2b6178c97a938stf", "3ycxdb1fgxa2yz"]

print(sorted([ch for ch in set([c for c in ''.join(LIST)]) if all(w.count(ch) == 1 for w in LIST)]))





Ada: with Ada.Text_Io;

procedure Unique_Characters is

   type Occurence_Count is array (Character) of Natural;
   type Occurence_List  is array (Positive range <>) of Occurence_Count;

   function Occurences (Item : String) return Occurence_Count is
      Count : Occurence_Count := (others => 0);
   begin
      for C of Item loop
         Count (C) := Count (C) + 1;
      end loop;
      return Count;
   end Occurences;

   procedure Put_Unique (List : Occurence_List) is
      use Ada.Text_Io;
   begin
      for C in List (List'First)'Range loop
         if (for all I in List'Range => List (I) (C) = 1) then
            Put (C);
            Put (' ');
         end if;
      end loop;
   end Put_Unique;

begin
   Put_Unique ((1 => Occurences ("1a3c52debeffd"),
                2 => Occurences ("2b6178c97a938stf"),
                3 => Occurences ("3ycxdb1fgxa2yz")));
end Unique_Characters;
Task: Compare sorting algorithms' performance







Python: def builtinsort(x):
    x.sort()

def partition(seq, pivot):
   low, middle, up = [], [], []
   for x in seq:
       if x < pivot:
           low.append(x)
       elif x == pivot:
           middle.append(x)
       else:
           up.append(x)
   return low, middle, up
import random
def qsortranpart(seq):
   size = len(seq)
   if size < 2: return seq
   low, middle, up = partition(seq, random.choice(seq))
   return qsortranpart(low) + middle + qsortranpart(up)
Task: Magic squares of singly even order







Python: import math
from sys import stdout

LOG_10 = 2.302585092994



def build_oms(s):
    if s % 2 == 0:
        s += 1
    q = [[0 for j in range(s)] for i in range(s)]
    p = 1
    i = s // 2
    j = 0
    while p <= (s * s):
        q[i][j] = p
        ti = i + 1
        if ti >= s: ti = 0
        tj = j - 1
        if tj < 0: tj = s - 1
        if q[ti][tj] != 0:
            ti = i
            tj = j + 1
        i = ti
        j = tj
        p = p + 1

    return q, s



def build_sems(s):
    if s % 2 == 1:
        s += 1
    while s % 4 == 0:
        s += 2

    q = [[0 for j in range(s)] for i in range(s)]
    z = s // 2
    b = z * z
    c = 2 * b
    d = 3 * b
    o = build_oms(z)

    for j in range(0, z):
        for i in range(0, z):
            a = o[0][i][j]
            q[i][j] = a
            q[i + z][j + z] = a + b
            q[i + z][j] = a + c
            q[i][j + z] = a + d

    lc = z // 2
    rc = lc
    for j in range(0, z):
        for i in range(0, s):
            if i < lc or i > s - rc or (i == lc and j == lc):
                if not (i == 0 and j == lc):
                    t = q[i][j]
                    q[i][j] = q[i][j + z]
                    q[i][j + z] = t

    return q, s


def format_sqr(s, l):
    for i in range(0, l - len(s)):
        s = "0" + s
    return s + " "


def display(q):
    s = q[1]
    print(" - {0} x {1}\n".format(s, s))
    k = 1 + math.floor(math.log(s * s) / LOG_10)
    for j in range(0, s):
        for i in range(0, s):
            stdout.write(format_sqr("{0}".format(q[0][i][j]), k))
        print()
    print("Magic sum: {0}\n".format(s * ((s * s) + 1) // 2))


stdout.write("Singly Even Magic Square")
display(build_sems(6))
Task: Addition chains







Python: def prepend(n, seq):
    return [n] + seq

def check_seq(pos, seq, n, min_len):
    if pos > min_len or seq[0] > n:
        return min_len, 0
    if seq[0] == n:
        return pos, 1
    if pos < min_len:
        return try_perm(0, pos, seq, n, min_len)
    return min_len, 0

def try_perm(i, pos, seq, n, min_len):
    if i > pos:
        return min_len, 0

    res1 = check_seq(pos + 1, prepend(seq[0] + seq[i], seq), n, min_len)
    res2 = try_perm(i + 1, pos, seq, n, res1[0])

    if res2[0] < res1[0]:
        return res2
    if res2[0] == res1[0]:
        return res2[0], res1[1] + res2[1]
    raise Exception("try_perm exception")

def init_try_perm(x):
    return try_perm(0, 0, [1], x, 12)

def find_brauer(num):
    res = init_try_perm(num)
    print
    print "N = ", num
    print "Minimum length of chains: L(n) = ", res[0]
    print "Number of minimum length Brauer chains: ", res[1]


nums = [7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379]
for i in nums:
    find_brauer(i)
Task: Geometric algebra







Python: import copy, random

def bitcount(n):
    return bin(n).count("1")

def reoderingSign(i, j):
    k = i >> 1
    sum = 0
    while k != 0:
        sum += bitcount(k & j)
        k = k >> 1
    return 1.0 if ((sum & 1) == 0) else -1.0

class Vector:
    def __init__(self, da):
        self.dims = da

    def dot(self, other):
        return (self * other + other * self) * 0.5

    def __getitem__(self, i):
        return self.dims[i]

    def __setitem__(self, i, v):
        self.dims[i] = v

    def __neg__(self):
        return self * -1.0

    def __add__(self, other):
        result = copy.copy(other.dims)
        for i in xrange(0, len(self.dims)):
            result[i] += self.dims[i]
        return Vector(result)

    def __mul__(self, other):
        if isinstance(other, Vector):
            result = [0.0] * 32
            for i in xrange(0, len(self.dims)):
                if self.dims[i] != 0.0:
                    for j in xrange(0, len(self.dims)):
                        if other.dims[j] != 0.0:
                            s = reoderingSign(i, j) * self.dims[i] * other.dims[j]
                            k = i ^ j
                            result[k] += s
            return Vector(result)
        else:
            result = copy.copy(self.dims)
            for i in xrange(0, len(self.dims)):
                self.dims[i] *= other
            return Vector(result)

    def __str__(self):
        return str(self.dims)

def e(n):
    assert n <= 4, "n must be less than 5"
    result = Vector([0.0] * 32)
    result[1 << n] = 1.0
    return result

def randomVector():
    result = Vector([0.0] * 32)
    for i in xrange(0, 5):
        result += Vector([random.uniform(0, 1)]) * e(i)
    return result

def randomMultiVector():
    result = Vector([0.0] * 32)
    for i in xrange(0, 32):
        result[i] = random.uniform(0, 1)
    return result

def main():
    for i in xrange(0, 5):
        for j in xrange(0, 5):
            if i < j:
                if e(i).dot(e(j))[0] != 0.0:
                    print "Unexpected non-null scalar product"
                    return
                elif i == j:
                    if e(i).dot(e(j))[0] == 0.0:
                        print "Unexpected non-null scalar product"

    a = randomMultiVector()
    b = randomMultiVector()
    c = randomMultiVector()
    x = randomVector()

    
    print (a * b) * c
    print a * (b * c)
    print

    
    print a * (b + c)
    print a * b + a * c
    print

    
    print (a + b) * c
    print a * c + b * c
    print

    
    print x * x

main()
Task: Enforced immutability





Java: final int immutableInt = 4;
int mutableInt = 4;
mutableInt = 6; 
immutableInt = 6; 






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





Java: import java.util.HashMap;
import java.util.Map;

public class HofQ {
	private static Map<Integer, Integer> q = new HashMap<Integer, Integer>(){{
		put(1, 1);
		put(2, 1);
	}};
	
	private static int[] nUses = new int[100001];
	
	public static int Q(int n){
		nUses[n]++;
		if(q.containsKey(n)){
			return q.get(n);
		}
		int ans = Q(n - Q(n - 1)) + Q(n - Q(n - 2));
		q.put(n, ans);
		return ans;
	}
	
	public static void main(String[] args){
		for(int i = 1; i <= 10; i++){
			System.out.println("Q(" + i + ") = " + Q(i));
		}
		int last = 6;
		int count = 0;
		for(int i = 11; i <= 100000; i++){
			int curr = Q(i);
			if(curr < last) count++;
			last = curr;
			if(i == 1000) System.out.println("Q(1000) = " + curr);
		}
		System.out.println("Q(i) is less than Q(i-1) for i <= 100000 " + count + " times");
		
		
		int maxUses = 0, maxN = 0;
		for(int i = 1; i<nUses.length;i++){
			if(nUses[i] > maxUses){
				maxUses = nUses[i];
				maxN = i;
			}
		}
		System.out.println("Q(" + maxN + ") was called the most with " + maxUses + " calls");
	}
}






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





Java: public class CountSubstring {
	public static int countSubstring(String subStr, String str){
		return (str.length() - str.replace(subStr, "").length()) / subStr.length();
	}
	
	public static void main(String[] args){
		System.out.println(countSubstring("th", "the three truths"));
		System.out.println(countSubstring("abab", "ababababab"));
		System.out.println(countSubstring("a*b", "abaabba*bbaba*bbab"));
	}
}






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





Java: public class Test {

    static int mod(int n, int m) {
        return ((n % m) + m) % m;
    }

    static boolean isPrime(int n) {
        if (n == 2 || n == 3)
            return true;
        else if (n < 2 || n % 2 == 0 || n % 3 == 0)
            return false;
        for (int div = 5, inc = 2; Math.pow(div, 2) <= n;
                div += inc, inc = 6 - inc)
            if (n % div == 0)
                return false;
        return true;
    }

    public static void main(String[] args) {
        for (int p = 2; p < 62; p++) {
            if (!isPrime(p))
                continue;
            for (int h3 = 2; h3 < p; h3++) {
                int g = h3 + p;
                for (int d = 1; d < g; d++) {
                    if ((g * (p - 1)) % d != 0 || mod(-p * p, h3) != d % h3)
                        continue;
                    int q = 1 + (p - 1) * g / d;
                    if (!isPrime(q))
                        continue;
                    int r = 1 + (p * q / h3);
                    if (!isPrime(r) || (q * r) % (p - 1) != 1)
                        continue;
                    System.out.printf("%d x %d x %d%n", p, q, r);
                }
            }
        }
    }
}






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