WeixiangYan/CodeTransOcean huggingface dataset:
Task: Bioinformatics_Subsequence




Go: package main

import (
    "fmt"
    "math/rand"
    "regexp"
    "time"
)

const base = "ACGT"

func findDnaSubsequence(dnaSize, chunkSize int) {
    dnaSeq := make([]byte, dnaSize)
    for i := 0; i < dnaSize; i++ {
        dnaSeq[i] = base[rand.Intn(4)]
    }
    dnaStr := string(dnaSeq)
    dnaSubseq := make([]byte, 4)
    for i := 0; i < 4; i++ {
        dnaSubseq[i] = base[rand.Intn(4)]
    }
    dnaSubstr := string(dnaSubseq)
    fmt.Println("DNA sequnence:")
    for i := chunkSize; i <= len(dnaStr); i += chunkSize {
        start := i - chunkSize
        fmt.Printf("%3d..%3d: %s\n", start+1, i, dnaStr[start:i])
    }
    fmt.Println("\nSubsequence to locate:", dnaSubstr)
    var r = regexp.MustCompile(dnaSubstr)
    var matches = r.FindAllStringIndex(dnaStr, -1)
    if len(matches) == 0 {
        fmt.Println("No matches found.")
    } else {
        fmt.Println("Matches found at the following indices:")
        for _, m := range matches {
            fmt.Printf("%3d..%-3d\n", m[0]+1, m[1])
        }
    }
}

func main() {
    rand.Seed(time.Now().UnixNano())
    findDnaSubsequence(200, 20)
    fmt.Println()
    findDnaSubsequence(600, 40)
}








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




Go: package main

import (
    "bytes"
    "fmt"
    "io/ioutil"
    "log"
    "runtime"
)

func main() {
    fileName1 := "rodgers.txt"
    fileName2 := "rodgers_reversed.txt"
    lineBreak := "\n"
    if runtime.GOOS == "windows" {
        lineBreak = "\r\n"
    }
    
    b, err := ioutil.ReadFile(fileName1)
    if err != nil {
        log.Fatal(err)
    }
    lines := bytes.Split(b, []byte(lineBreak))
    
    if len(lines[len(lines)-1]) == 0 {
        lines = lines[:len(lines)-1]
    }

    
    for i, j := 0, len(lines)-1; i < j; i, j = i+1, j-1 {
        lines[i], lines[j] = lines[j], lines[i]
    }
    b = bytes.Join(lines, []byte(lineBreak))
    if err = ioutil.WriteFile(fileName2, b, 0o666); err != nil {
        log.Fatal(err)
    }
    
    b, err = ioutil.ReadFile(fileName2)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(string(b))
}








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: User input_Graphical


C++: #ifndef TASK_H
#define TASK_H

#include <QWidget>

class QLabel ;
class QLineEdit ;
class QVBoxLayout ;
class QHBoxLayout ;

class EntryWidget : public QWidget {

   Q_OBJECT 
public :
   EntryWidget( QWidget *parent = 0 ) ;
private :
   QHBoxLayout *upperpart , *lowerpart ;
   QVBoxLayout *entryLayout ;
   QLineEdit *stringinput ;
   QLineEdit *numberinput ;
   QLabel *stringlabel ;
   QLabel *numberlabel ;
} ;

#endif
Task: Common sorted list


C++: #include <iostream>
#include <vector>
#include <set>
#include <algorithm>

template<typename T>
std::vector<T> common_sorted_list(const std::vector<std::vector<T>>& ll) {
    std::set<T> resultset;
    std::vector<T> result;
    for (auto& list : ll)
        for (auto& item : list)
            resultset.insert(item);
    for (auto& item : resultset)
        result.push_back(item);
    
    std::sort(result.begin(), result.end());
    return result;
}

int main() {
    std::vector<int> a = {5,1,3,8,9,4,8,7};
    std::vector<int> b = {3,5,9,8,4};
    std::vector<int> c = {1,3,7,9};
    std::vector<std::vector<int>> nums = {a, b, c};
    
    auto csl = common_sorted_list(nums);
    for (auto n : csl) std::cout << n << " ";
    std::cout << std::endl;
    
    return 0;
}
Task: Smarandache-Wellin primes


C++: #include <iomanip>
#include <iostream>
#include <string>

#include <primesieve.hpp>

#include <gmpxx.h>

using big_int = mpz_class;

class sw_number_generator {
public:
    sw_number_generator() { next(); }
    void next();
    const std::string& number() const { return number_; }
    uint64_t prime() const { return prime_; }
    int index() const { return index_; }
    std::string derived_number() const;

private:
    primesieve::iterator pi_;
    std::string number_;
    uint64_t prime_;
    int index_ = 0;
};

void sw_number_generator::next() {
    ++index_;
    prime_ = pi_.next_prime();
    number_ += std::to_string(prime_);
}

std::string sw_number_generator::derived_number() const {
    int count[10] = {};
    for (char c : number_)
        ++count[c - '0'];
    std::string str;
    for (int i = 0; i < 10; ++i) {
        if (!str.empty() || count[i] != 0)
            str += std::to_string(count[i]);
    }
    return str;
}

bool is_probably_prime(const big_int& n) {
    return mpz_probab_prime_p(n.get_mpz_t(), 25) != 0;
}

std::string abbreviate(const std::string& str, size_t n) {
    size_t len = str.size();
    if (len > n)
        return str.substr(0, n / 2) + "..." + str.substr(len - n / 2);
    return str;
}

void print_sw_primes() {
    std::cout
        << "Known Smarandache-Wellin primes:\n\n"
        << "  |Index|Digits|Last prime|         Smarandache-Wellin prime\n"
        << "----------------------------------------------------------------------\n";
    sw_number_generator swg;
    for (int n = 1; n <= 8; swg.next()) {
        std::string num = swg.number();
        if (is_probably_prime(big_int(num))) {
            std::cout << std::setw(2) << n << "|"
                      << std::setw(5) << swg.index() << "|"
                      << std::setw(6) << num.size() << "|"
                      << std::setw(10) << swg.prime() << "|"
                      << std::setw(43) << abbreviate(num, 40) << '\n';
            ++n;
        }
    }
}

void print_derived_sw_primes(int count) {
    std::cout << "First " << count << " Derived Smarandache-Wellin primes:\n\n"
              << "  |Index|Derived Smarandache-Wellin prime\n"
              << "-----------------------------------------\n";
    sw_number_generator swg;
    for (int n = 1; n <= count; swg.next()) {
        std::string num = swg.derived_number();
        if (is_probably_prime(big_int(num))) {
            std::cout << std::setw(2) << n << "|"
                      << std::setw(5) << swg.index() << "|"
                      << std::setw(32) << num << '\n';
            ++n;
        }
    }
}

int main() {
    print_sw_primes();
    std::cout << '\n';
    print_derived_sw_primes(20);
}
Task: Fermat pseudoprimes


C++: #include <cstdint>
#include <iomanip>
#include <iostream>

uint64_t modpow(uint64_t base, uint64_t exp, uint64_t mod) {
    if (mod == 1)
        return 0;
    uint64_t result = 1;
    base %= mod;
    for (; exp > 0; exp >>= 1) {
        if ((exp & 1) == 1)
            result = (result * base) % mod;
        base = (base * base) % mod;
    }
    return result;
}

bool is_prime(uint64_t n) {
    if (n < 2)
        return false;
    if (n % 2 == 0)
        return n == 2;
    if (n % 3 == 0)
        return n == 3;
    for (uint64_t p = 5; p * p <= n; p += 4) {
        if (n % p == 0)
            return false;
        p += 2;
        if (n % p == 0)
            return false;
    }
    return true;
}

bool is_fermat_pseudoprime(uint64_t a, uint64_t x) {
    return !is_prime(x) && modpow(a, x - 1, x) == 1;
}

int main() {
    std::cout << "First 20 Fermat pseudoprimes:\n";
    for (uint64_t a = 1; a <= 20; ++a) {
        std::cout << "Base " << std::setw(2) << a << ": ";
        int count = 0;
        for (uint64_t x = 4; count < 20; ++x) {
            if (is_fermat_pseudoprime(a, x)) {
                ++count;
                std::cout << std::setw(5) << x << ' ';
            }
        }
        std::cout << '\n';
    }

    const uint64_t limits[] = {12000, 25000, 50000, 100000};
    std::cout << "\nCount <= ";
    for (uint64_t limit : limits) {
        std::cout << std::setw(6) << limit << ' ';
    }
    std::cout << "\n------------------------------------\n";
    for (uint64_t a = 1; a <= 20; ++a) {
        std::cout << "Base " << std::setw(2) << a << ": ";
        int count = 0;
        uint64_t x = 4;
        for (uint64_t limit : limits) {
            for (; x <= limit; ++x) {
                if (is_fermat_pseudoprime(a, x))
                    ++count;
            }
            std::cout << std::setw(6) << count << ' ';
        }
        std::cout << '\n';
    }
}
Task: Carmichael 3 strong pseudoprimes








VB: max_sieve = 1e7
dim isprime(max_sieve)

//set up sieve
for i = 3 to max_sieve step 2
  isprime(i) = 1
next i

isprime(2) = 1
for i = 3 to sqrt(max_sieve) step 2
  if isprime(i) = 1 then
    for j = i * i to max_sieve step i * 2
      isprime(j) = 0
    next j
  fi
next i

for i = 2 to 61
  carmichael3(i)
next i
end
 
sub carmichael3(p1) 
  local h3, d, p2, p3, t1, t2

  if isprime(p1) = 0  return
  for h3 = 1 to p1 -1
    t1 = (h3 + p1) * (p1 -1)
    t2 = mod((-p1 * p1), h3)
    if t2 < 0   t2 = t2 + h3
    for d = 1 to h3 + p1 -1
      if mod(t1, d) = 0 and t2 = mod(d, h3) then
        p2 = 1 + int(t1 / d)
        if isprime(p2) = 0  continue
        p3 = 1 + int(p1 * p2 / h3)
        if isprime(p3) = 0 or mod((p2 * p3), (p1 -1)) <> 1  continue
        print p1 using ("###"), " * ", p2 using ("####"), " * ", p3 using ("#####")
      fi
    next d
  next h3
end sub
Task: Verify distribution uniformity_Naive

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

inline int rand5()
{
	int r, rand_max = RAND_MAX - (RAND_MAX % 5);
	while ((r = rand()) >= rand_max);
	return r / (rand_max / 5) + 1;
}

inline int rand5_7()
{
	int r;
	while ((r = rand5() * 5 + rand5()) >= 27);
	return r / 3 - 1;
}


int check(int (*gen)(), int n, int cnt, double delta) 
{
	int i = cnt, *bins = calloc(sizeof(int), n);
	double ratio;
	while (i--) bins[gen() - 1]++;
	for (i = 0; i < n; i++) {
		ratio = bins[i] * n / (double)cnt - 1;
		if (ratio > -delta && ratio < delta) continue;

		printf("bin %d out of range: %d (%g%% vs %g%%), ",
			i + 1, bins[i], ratio * 100, delta * 100);
		break;
	}
	free(bins);
	return i == n;
}

int main()
{
	int cnt = 1;
	while ((cnt *= 10) <= 1000000) {
		printf("Count = %d: ", cnt);
		printf(check(rand5_7, 7, cnt, 0.03) ? "flat\n" : "NOT flat\n");
	}

	return 0;
}
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;
}
Task: Strange numbers

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

bool isPrime(int n) {
    if (n < 0) {
        n = -n;
    }
    return n == 2 || n == 3 || n == 5 || n == 7;
}

int main() {
    int count = 0;
    int i, j;
    int d[3];
    int dptr;

    printf("Strange numbers in the open interval (100, 500) are:\n");
    for (i = 101; i < 500; i++) {
        dptr = 0;
        j = i;
        while (j > 0) {
            d[dptr++] = j % 10;
            j /= 10;
        }
        if (isPrime(d[0] - d[1]) && isPrime(d[1] - d[2])) {
            printf("%d ", i);
            count++;
            if (count % 10 == 0) {
                printf("\n");
            }
        }
    }
    if (count % 10 != 0) {
        printf("\n");
    }
    printf("\n%d strange numbers in all.\n", count);

    return 0;
}
Task: Create an object at a given address

C: #include <stdio.h>

int main()
{
  int intspace;
  int *address;

  address = &intspace; 
  *address = 65535;
  printf("%p: %08x (=%08x)\n", address, *address, intspace);
  
  *((char*)address) = 0x00;
  *((char*)address+1) = 0x00;
  *((char*)address+2) = 0xff;
  *((char*)address+3) = 0xff; 
  
  printf("%p: %08x (=%08x)\n", address, *address, intspace);
  return 0;
}
Task: Start from a main routine

C: #include<stdio.h>

#define start main()

int start
{
	printf("Hello World !");
	return 0;
}
Task: Two's complement

C: int a = 3;
a = -a;
Task: Enforced immutability


C++: #include <iostream>

class MyOtherClass
{
public:
  const int m_x;
  MyOtherClass(const int initX = 0) : m_x(initX) { }

};

int main()
{
  MyOtherClass mocA, mocB(7);

  std::cout << mocA.m_x << std::endl; 
  std::cout << mocB.m_x << std::endl; 

  
  

  return 0;
}
Task: Pascal's triangle_Puzzle


C++: #include <iostream>
#include <iomanip>

inline int sign(int i) {
    return i < 0 ? -1 : i > 0;
}

inline int& E(int *x, int row, int col) {
    return x[row * (row + 1) / 2 + col];
}

int iter(int *v, int *diff) {
    
    E(v, 0, 0) = 151;
    E(v, 2, 0) = 40;
    E(v, 4, 1) = 11;
    E(v, 4, 3) = 4;

    
    for (auto i = 1u; i < 5u; i++)
        for (auto j = 0u; j <= i; j++) {
            E(diff, i, j) = 0;
            if (j < i)
                E(diff, i, j) += E(v, i - 1, j) - E(v, i, j + 1) - E(v, i, j);
            if (j)
                E(diff, i, j) += E(v, i - 1, j - 1) - E(v, i, j - 1) - E(v, i, j);
        }

    for (auto i = 0u; i < 4u; i++)
        for (auto j = 0u; j < i; j++)
            E(diff, i, j) += E(v, i + 1, j) + E(v, i + 1, j + 1) - E(v, i, j);

    E(diff, 4, 2) += E(v, 4, 0) + E(v, 4, 4) - E(v, 4, 2);

    
    uint sum;
    int e = 0;
    for (auto i = sum = 0u; i < 15u; i++) {
        sum += !!sign(e = diff[i]);

        
        if (e >= 4 || e <= -4)
            v[i] += e / 5;
        else if (rand() < RAND_MAX / 4)
            v[i] += sign(e);
    }
    return sum;
}

void show(int *x) {
    for (auto i = 0u; i < 5u; i++)
        for (auto j = 0u; j <= i; j++)
            std::cout << std::setw(4u) << *(x++) << (j < i ? ' ' : '\n');
}

int main() {
    int v[15] = { 0 }, diff[15] = { 0 };
    for (auto i = 1u, s = 1u; s; i++) {
        s = iter(v, diff);
        std::cout << "pass " << i << ": " << s << std::endl;
    }
    show(v);

    return 0;
}
Task: Create your own text control codes

C: int foo = 1;
int bar = 2;
int baz = foo + bar;
printf("%d plus %d is: %d",foo,bar,baz);
Task: Singular value decomposition

C: #include <stdio.h>
#include <gsl/gsl_linalg.h>


void gsl_matrix_print(const gsl_matrix *M) {
    int rows = M->size1;
    int cols = M->size2;
    for (int i = 0; i < rows; i++) {
        printf("|");
        for (int j = 0; j < cols; j++) {
            printf("% 12.10f ", gsl_matrix_get(M, i, j));
        }
        printf("\b|\n");
    }
    printf("\n");
}

int main(){
    double a[] = {3, 0, 4, 5};
    gsl_matrix_view A = gsl_matrix_view_array(a, 2, 2);
    gsl_matrix *V = gsl_matrix_alloc(2, 2);
    gsl_vector *S = gsl_vector_alloc(2);
    gsl_vector *work = gsl_vector_alloc(2);

    
    gsl_linalg_SV_decomp(&A.matrix, V, S, work);
    gsl_matrix_transpose(V);
    double s[] = {S->data[0], 0, 0, S->data[1]};
    gsl_matrix_view SM = gsl_matrix_view_array(s, 2, 2);

    printf("U:\n");
    gsl_matrix_print(&A.matrix);

    printf("S:\n");
    gsl_matrix_print(&SM.matrix);

    printf("VT:\n");
    gsl_matrix_print(V);
    
    gsl_matrix_free(V);
    gsl_vector_free(S);
    gsl_vector_free(work);
    return 0;
}
Task: Verify distribution uniformity_Naive







Python: from collections import Counter
from pprint import pprint as pp

def distcheck(fn, repeats, delta):
    
    bin = Counter(fn() for i in range(repeats))
    target = repeats // len(bin)
    deltacount = int(delta / 100. * target)
    assert all( abs(target - count) < deltacount
                for count in bin.values() ), "Bin distribution skewed from %i +/- %i: %s" % (
                    target, deltacount, [ (key, target - count)
                                          for key, count in sorted(bin.items()) ]
                    )
    pp(dict(bin))




Fortran: subroutine distcheck(randgen, n, delta)

  interface
    function randgen
      integer :: randgen 
    end function randgen
  end interface
  
  real, intent(in) :: delta
  integer, intent(in) :: n
  integer :: i, mval, lolim, hilim
  integer, allocatable :: buckets(:)
  integer, allocatable :: rnums(:)
  logical :: skewed = .false.
     
  allocate(rnums(n))
  
  do i = 1, n
    rnums(i) = randgen()
  end do

  mval = maxval(rnums)
  allocate(buckets(mval))
  buckets = 0
  
  do i = 1, n
    buckets(rnums(i)) = buckets(rnums(i)) + 1
  end do

  lolim = n/mval - n/mval*delta
  hilim = n/mval + n/mval*delta
  
  do i = 1, mval  
    if(buckets(i) < lolim .or. buckets(i) > hilim) then
      write(*,"(a,i0,a,i0,a,i0)") "Distribution potentially skewed for bucket ", i, "   Expected: ", &
                                   n/mval, "   Actual: ", buckets(i)
      skewed = .true.
    end if
  end do 

  if (.not. skewed) write(*,"(a)") "Distribution uniform"
  
  deallocate(rnums)
  deallocate(buckets)
    
end subroutine
Task: Use another language to call a function







Python: 

def query(buffer_length):
    message = b'Here am I'
    L = len(message)
    return message[0:L*(L <= buffer_length)]




Fortran: 


function  fortran_query(data, length) result(answer) bind(c, name='Query')
   use, intrinsic  :: iso_c_binding, only: c_char, c_int, c_size_t, c_null_char
   implicit none
   character(len=1,kind=c_char), dimension(length),  intent(inout) ::  data
   integer(c_size_t), intent(inout) :: length
   integer(c_int) :: answer
   answer = 0
   if(length<10) return
   data = transfer("Here I am"//c_null_char, data)
   length = 10_c_size_t
   answer = 1
end function fortran_query
Task: Find first and last set bit of a long integer







Python: def msb(x):
    return x.bit_length() - 1

def lsb(x):
    return msb(x & -x)

for i in range(6):
    x = 42 ** i
    print("%10d MSB: %2d LSB: %2d" % (x, msb(x), lsb(x)))

for i in range(6):
    x = 1302 ** i
    print("%20d MSB: %2d LSB: %2d" % (x, msb(x), lsb(x)))




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: Hofstadter Q sequence







Python: def q(n):
    if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1")
    try:
        return q.seq[n]
    except IndexError:
        ans = q(n - q(n - 1)) + q(n - q(n - 2))
        q.seq.append(ans)
        return ans
q.seq = [None, 1, 1]

if __name__ == '__main__':
    first10 = [q(i) for i in range(1,11)]
    assert first10 == [1, 1, 2, 3, 3, 4, 5, 5, 6, 6], "Q() value error(s)"
    print("Q(n) for n = [1..10] is:", ', '.join(str(i) for i in first10))
    assert q(1000) == 502, "Q(1000) value error"
    print("Q(1000) =", q(1000))




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







Python: >>> "the three truths".count("th")
3
>>> "ababababab".count("abab")
2




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