Jump to content

Prime numbers whose neighboring pairs are tetraprimes

From Rosetta Code
Task
Prime numbers whose neighboring pairs are tetraprimes
You are encouraged to solve this task according to the task description, using any language you may know.
Definitions

The following definitions are needed for this task.

A tetraprime is a positive integer which is the product of four distinct primes. For example, 1155 is a tetraprime because 1155 = 3 x 5 x 7 x 11.

The neighboring pairs of a prime are the two consecutive numbers immediately preceding or immediately following that prime. For example, (5, 6) and (8, 9) are the neighboring pairs of the prime 7.

Task

1. Find and show here all primes less than 100,000 whose preceding neighboring pair are both tetraprimes.

2. Find and show here all primes less than 100,000 whose following neighboring pair are both tetraprimes.

3. Of the primes in 1 and 2 above how many have a neighboring pair one of whose members has a prime factor of 7?

4. For the primes in 1 and 2 above, consider the gaps between consecutive primes. What are the minimum, median and maximum gaps?

5. Repeat these calculations for all primes less than 1 million but for 1 and 2 just show the number of primes - don't print them out individually.

If it is difficult for your language to meet all of these requirements, then just do what you reasonably can.


Stretch

Repeat the calculations for all primes less than 10 million.


References


ALGOL 68

Library: ALGOL 68-rows

Constructs a table of prime factors without using division/modulo operations.
To run this with Algol 68G, you will need to specify a large heap size, with e.g.: -heap 256M on the command line.

BEGIN # find primes whose neighbouring pairs are tetraprimes - i.e. have 4   #
      # distinct prime factors                                               #

    PR read "rows.incl.a68" PR     # include row utilities, including MEDIAN #
    INT max prime = 10 000 000;     # the largest possible prime to comsider #
    # construct table of prime factor counts                                 #
    # numbers with non-distinct prime factors will have negative counts      #
    [ 0 : max prime + 2 ]INT pfc;
    FOR i FROM LWB pfc TO UPB pfc DO pfc[ i ] := 0 OD;
    FOR n FROM 2 TO UPB pfc OVER 2 DO
        IF pfc[ n ] = 0 THEN                                    # i is prime #
            INT power      := 1;
            INT n to power := n;
            INT start n    := n + n;
            WHILE FOR j FROM start n BY n to power TO UPB pfc DO
                      IF pfc[ j ] >= 0 THEN
                          # no duplicate factors yet                         #
                          pfc[ j ] +:= 1
                      ELSE
                          # already have a duplicate factor                  #
                          pfc[ j ] +:= -1
                      FI;
                      IF power > 1 THEN
                          IF pfc[ j ] > 0 THEN pfc[ j ] := - pfc[ j ] FI
                      FI
                  OD;
                  power +:= 1;
                  LONG INT long n to power := LENG n to power * n;
                  long n to power <= UPB pfc
            DO
                start n := n to power := SHORTEN long n to power
            OD
        FI
    OD;

    # show the statistics and optionally the primes with a tetraprime pair   #
    #                     at offset 1 and offset 2 from the prime            #
    PROC show neighbour pairs = ( INT max n, BOOL show primes, INT offset 1, offset 2 )VOID:
         BEGIN
            # array of prime gaps, used to find the median gap               #
            # should be large enough for the stretch task                    #
            [ 1 : 12 000 ]INT gaps; FOR i TO UPB gaps DO gaps[ i ] := 0 OD;
            INT t count := 0, f7 count := 0;
            INT prev prime := 0;
            INT min gap := max int, max gap := 0, gap pos := 0;
            # note the lowest tetraprime is 210                              #
            FOR i FROM 211 BY 2 TO max n DO
                IF pfc[ i ] = 0 THEN
                    # have a prime                                           #
                    IF pfc[ i + offset 1 ] = 4 AND pfc[ i + offset 2 ] = 4 THEN
                        # the previous pair are tetraprimes                  #
                        IF prev prime > 0 THEN
                            INT this gap = i - prev prime;
                            IF min gap > this gap THEN min gap := this gap FI;
                            IF max gap < this gap THEN max gap := this gap FI;
                            gaps[ gap pos +:= 1 ] := this gap
                        FI;
                        prev prime := i;
                        IF ( i + offset 1 ) MOD 7 = 0 OR ( i + offset 2 ) MOD 7 = 0 THEN
                            f7 count +:= 1
                        FI;
                        t count +:= 1;
                        IF show primes THEN
                            print( ( " ", whole( i, -5 ) ) );
                            IF t count MOD 10 = 0 THEN print( ( newline ) ) FI
                        FI
                    FI
                FI
            OD;
            IF show primes THEN print( ( newline ) ) ELSE print( ( "       " ) ) FI;
            print( ( "Found ", whole( t count, 0 ), " such primes", " of which " ) );
            print( ( whole( f7 count, 0 ), " have 7 as a factor of one of the pair", newline ) );
            IF NOT show primes THEN print( ( "       " ) ) FI;
            print( ( "      gaps between the primes: min: ", whole( min gap, 0 ) ) );
            print( ( ", average: ", whole( ROUND AVERAGE gaps[ : gap pos ], 0 ) ) );
            print( ( ", median: ",  whole( ROUND MEDIAN  gaps[ : gap pos ], 0 ) ) );
            print( ( ", max: ", whole( max gap, 0 ), newline, newline ) )
        END # show neighbour paris # ;

    # show some tetraprimes and statistics about them                        #
    PROC show tetraprime neighbours = ( INT max n, BOOL show primes )VOID:
         BEGIN
            print( ( "Primes below ", whole( max n, 0 ) ) );
            print( ( " preceded by a tetraprime pair:", newline ) );
            show neighbour pairs( max n, show primes, -1, -2 );
            print( ( "Primes below ", whole( max n, 0 ) ) );
            print( ( " followed by a tetraprime pair:", newline ) );
            show neighbour pairs( max n, show primes,  1,  2 )
         END # show tetraprime pairs # ;

    # task                                                                   #
    show tetraprime neighbours(    100 000, TRUE  );
    show tetraprime neighbours(  1 000 000, FALSE );
    show tetraprime neighbours( 10 000 000, FALSE )

END
Output:
Primes below 100000 preceded by a tetraprime pair:
  8647 15107 20407 20771 21491 23003 23531 24767 24971 27967
 29147 33287 34847 36779 42187 42407 42667 43331 43991 46807
 46867 51431 52691 52747 53891 54167 58567 63247 63367 69379
 71711 73607 73867 74167 76507 76631 76847 80447 83591 84247
 86243 87187 87803 89387 93887 97547 97847 98347 99431
Found 49 such primes of which 31 have 7 as a factor of one of the pair
      gaps between the primes: min: 56, average: 1891, median: 1208, max: 6460

Primes below 100000 followed by a tetraprime pair:
  8293 16553 17389 18289 22153 26893 29209 33409 35509 36293
 39233 39829 40493 41809 45589 48109 58393 59629 59753 59981
 60493 60913 64013 64921 65713 66169 69221 71329 74093 75577
 75853 77689 77933 79393 79609 82913 84533 85853 87589 87701
 88681 91153 93889 96017 97381 98453
Found 46 such primes of which 36 have 7 as a factor of one of the pair
      gaps between the primes: min: 112, average: 2004, median: 1460, max: 10284

Primes below 1000000 preceded by a tetraprime pair:
       Found 885 such primes of which 503 have 7 as a factor of one of the pair
             gaps between the primes: min: 4, average: 1119, median: 756, max: 7712

Primes below 1000000 followed by a tetraprime pair:
       Found 866 such primes of which 492 have 7 as a factor of one of the pair
             gaps between the primes: min: 4, average: 1146, median: 832, max: 10284

Primes below 10000000 preceded by a tetraprime pair:
       Found 10815 such primes of which 5176 have 7 as a factor of one of the pair
             gaps between the primes: min: 4, average: 924, median: 648, max: 9352

Primes below 10000000 followed by a tetraprime pair:
       Found 10551 such primes of which 5069 have 7 as a factor of one of the pair
             gaps between the primes: min: 4, average: 947, median: 660, max: 10284

C

Translation of: Wren
Library: primesieve
Library: GLib
/* gcc -O3 `pkg-config --cflags glib-2.0` tetraprime.c -o tp `pkg-config --libs glib-2.0` -lprimesieve */

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <locale.h>
#include <primesieve.h>
#include <glib.h>

#define TEN_MILLION 10000000

size_t size;
int* primes;

void init() {
    primes = (int*) primesieve_generate_primes(2, TEN_MILLION, &size, INT_PRIMES);
}

bool isTetraPrime(int n) {
    size_t i;
    int p,limit, count = 0, prevFact = 1;
    for (i = 0; i < size; ++i) {
        p = primes[i];
        limit = p*p;
        switch (count){
        case 0: 
            limit *= limit;
            break;
        case 1: 
            limit *= p;
            break;
        }  
        if (limit <= n) {
            while(!(n%p)) {
                if (count == 4 || p == prevFact) return false;
                ++count;
                n /= p;
                prevFact = p;
            }
        } else {
            break;
        }
    }
    if (n > 1) {
        if (count == 4 || p == prevFact) return false;
        ++count;
    }
    return count == 4;
}

int prevPrime(int n) {
    size_t l = 0, r = size, m;
    while (l < r) {
        m = (l + r)/2;
        if (primes[m] > n) {
            r = m;
        } else {
            l = m + 1;
        }
    }
    return primes[r-1];
}

int compare(const void* a, const void* b) {
    int arg1 = *(const int*)a;
    int arg2 = *(const int*)b;
    if (arg1 < arg2) return -1;
    if (arg1 > arg2) return 1;
    return 0;
}

// Note that 'gaps' will only contain even numbers here.
int median(int *gaps, int length) {
    int m = length/2;
    if (length & 1 == 1) return gaps[m];
    return (gaps[m] + gaps[m-1])/2;
}

int main() {
    size_t s;
    int i, p, c, k, length, sevens, min, max, med;
    int j = 100000, sevens1 = 0, sevens2 = 0;
    int *gaps;
    const char *t;
    GArray *tetras1 = g_array_new(FALSE, FALSE, sizeof(int));
    GArray *tetras2 = g_array_new(FALSE, FALSE, sizeof(int));
    GArray *tetras;
    init();
    int highest5 = prevPrime(100000);
    int highest6 = prevPrime(1000000);
    int highest7 = primes[size - 1];
    setlocale(LC_NUMERIC, "");
    for (s = 0; s < size; ++s) {
        p = primes[s];

        // process even numbers first as likely to have most factors
        if (isTetraPrime(p-1) && isTetraPrime(p-2)) {
            g_array_append_val(tetras1, p);
            if ((p-1)%7 == 0 || (p-2)%7 == 0) ++sevens1;                
        }

        if (isTetraPrime(p+1) && isTetraPrime(p+2)) {
            g_array_append_val(tetras2, p);
            if ((p+1)%7 == 0 || (p+2)%7 == 0) ++sevens2;
        }
        
        if (p == highest5 || p == highest6 || p == highest7) {
            for (i = 0; i < 2; ++i) {
                tetras = (i == 0) ? tetras1 : tetras2;
                sevens = (i == 0) ? sevens1 : sevens2;
                c = tetras->len;
                t = (i == 0) ? "preceding" : "following";
                printf("Found %'d primes under %'d whose %s neighboring pair are tetraprimes", c, j, t);
                if (p == highest5) {
                    printf(":\n");
                    for (k = 0; k < tetras->len; ++k) {
                        printf("%5d  ", g_array_index(tetras, int, k));
                        if (!((k+1) % 10)) printf("\n");
                    }
                    printf("\n");
                }
                printf("\nof which %'d have a neighboring pair one of whose factors is 7.\n\n", sevens);
                length = c - 1;
                gaps = (int *)malloc(length * sizeof(int));
                for (k = 0; k < length; ++k) {
                    gaps[k] = g_array_index(tetras, int, k+1) - g_array_index(tetras, int, k);
                }
                qsort(gaps, length, sizeof(int), compare);
                min = gaps[0];
                max = gaps[length - 1];
                med = median(gaps, length);
                printf("Minimum gap between those %'d primes : %'d\n", c, min);
                printf("Median  gap between those %'d primes : %'d\n", c, med);
                printf("Maximum gap between those %'d primes : %'d\n", c, max);
                printf("\n");
                free(gaps);
            }
            j *= 10;
        }
    }
    g_array_free(tetras1, FALSE);
    g_array_free(tetras2, FALSE);
    primesieve_free(primes);
    return 0;
}
Output:
Identical to Wren example.


C#

Translation of: Java
using System;
using System.Collections.Generic;

public class PrimeNumbersNeighboringPairsTetraprimes
{
    private static List<int> primes;

    public static void Main(string[] args)
    {
        ListPrimeNumbers(10_000_000);

        int largestPrime5 = LargestLessThan(100_000);
        int largestPrime6 = LargestLessThan(1_000_000);
        int largestPrime7 = primes[primes.Count - 1];
        var tetrasPreceding = new List<int>();
        var tetrasFollowing = new List<int>();
        int sevensPreceding = 0;
        int sevensFollowing = 0;
        int limit = 100_000;

        foreach (var prime in primes)
        {
            if (IsTetraPrime(prime - 1) && IsTetraPrime(prime - 2))
            {
                tetrasPreceding.Add(prime);
                if ((prime - 1) % 7 == 0 || (prime - 2) % 7 == 0)
                {
                    sevensPreceding++;
                }
            }

            if (IsTetraPrime(prime + 1) && IsTetraPrime(prime + 2))
            {
                tetrasFollowing.Add(prime);
                if ((prime + 1) % 7 == 0 || (prime + 2) % 7 == 0)
                {
                    sevensFollowing++;
                }
            }

            if (prime == largestPrime5 || prime == largestPrime6 || prime == largestPrime7)
            {
                for (int i = 0; i <= 1; i++)
                {
                    List<int> tetras = (i == 0) ? new List<int>(tetrasPreceding) : new List<int>(tetrasFollowing);
                    int size = tetras.Count;
                    int sevens = (i == 0) ? sevensPreceding : sevensFollowing;
                    string text = (i == 0) ? "preceding" : "following";

                    Console.Write("Found " + size + " primes under " + limit + " whose " + text + " neighboring pair are tetraprimes");
                    if (prime == largestPrime5)
                    {
                        Console.WriteLine(":");
                        for (int j = 0; j < size; j++)
                        {
                            Console.Write($"{tetras[j],7}{(j % 10 == 9 ? "\n" : "")}");
                        }
                        Console.WriteLine();
                    }
                    Console.WriteLine();
                    Console.WriteLine("of which " + sevens + " have a neighboring pair one of whose factors is 7.");
                    Console.WriteLine();

                    var gaps = new List<int>();
                    for (int k = 0; k < size - 1; k++)
                    {
                        gaps.Add(tetras[k + 1] - tetras[k]);
                    }
                    gaps.Sort();
                    int minimum = gaps[0];
                    int maximum = gaps[gaps.Count - 1];
                    int middle = Median(gaps);
                    Console.WriteLine("Minimum gap between those " + size + " primes: " + minimum);
                    Console.WriteLine("Median gap between those " + size + " primes: " + middle);
                    Console.WriteLine("Maximum gap between those " + size + " primes: " + maximum);
                    Console.WriteLine();
                }
                limit *= 10;
            }
        }
    }

    private static bool IsTetraPrime(int number)
    {
        int count = 0;
        int previousFactor = 1;
        foreach (var prime in primes)
        {
            int limit = prime * prime;
            if (count == 0)
            {
                limit *= limit;
            }
            else if (count == 1)
            {
                limit *= prime;
            }
            if (limit <= number)
            {
                while (number % prime == 0)
                {
                    if (count == 4 || prime == previousFactor)
                    {
                        return false;
                    }
                    count++;
                    number /= prime;
                    previousFactor = prime;
                }
            }
            else
            {
                break;
            }
        }

        if (number > 1)
        {
            if (count == 4 || number == previousFactor)
            {
                return false;
            }
            count++;
        }
        return count == 4;
    }

    private static int Median(List<int> list)
    {
        int size = list.Count;
        if (size % 2 == 0)
        {
            return (list[size / 2 - 1] + list[size / 2]) / 2;
        }
        return list[size / 2];
    }

    private static int LargestLessThan(int number)
    {
        int index = primes.BinarySearch(number);
        if (index > 0)
        {
            return primes[index - 1];
        }
        return primes[~index - 2];
    }

    private static void ListPrimeNumbers(int limit)
    {
        int halfLimit = (limit + 1) / 2;
        var composite = new bool[halfLimit];
        for (int i = 1, p = 3; i < halfLimit; p += 2, i++)
        {
            if (!composite[i])
            {
                for (int j = i + p; j < halfLimit; j += p)
                {
                    composite[j] = true;
                }
            }
        }

        primes = new List<int> { 2 };
        for (int i = 1, p = 3; i < halfLimit; p += 2, i++)
        {
            if (!composite[i])
            {
                primes.Add(p);
            }
        }
    }
}
Output:
Found 49 primes under 100000 whose preceding neighboring pair are tetraprimes:
   8647  15107  20407  20771  21491  23003  23531  24767  24971  27967
  29147  33287  34847  36779  42187  42407  42667  43331  43991  46807
  46867  51431  52691  52747  53891  54167  58567  63247  63367  69379
  71711  73607  73867  74167  76507  76631  76847  80447  83591  84247
  86243  87187  87803  89387  93887  97547  97847  98347  99431

of which 31 have a neighboring pair one of whose factors is 7.

Minimum gap between those 49 primes: 56
Median gap between those 49 primes: 1208
Maximum gap between those 49 primes: 6460

Found 46 primes under 100000 whose following neighboring pair are tetraprimes:
   8293  16553  17389  18289  22153  26893  29209  33409  35509  36293
  39233  39829  40493  41809  45589  48109  58393  59629  59753  59981
  60493  60913  64013  64921  65713  66169  69221  71329  74093  75577
  75853  77689  77933  79393  79609  82913  84533  85853  87589  87701
  88681  91153  93889  96017  97381  98453

of which 36 have a neighboring pair one of whose factors is 7.

Minimum gap between those 46 primes: 112
Median gap between those 46 primes: 1460
Maximum gap between those 46 primes: 10284

Found 885 primes under 1000000 whose preceding neighboring pair are tetraprimes
of which 503 have a neighboring pair one of whose factors is 7.

Minimum gap between those 885 primes: 4
Median gap between those 885 primes: 756
Maximum gap between those 885 primes: 7712

Found 866 primes under 1000000 whose following neighboring pair are tetraprimes
of which 492 have a neighboring pair one of whose factors is 7.

Minimum gap between those 866 primes: 4
Median gap between those 866 primes: 832
Maximum gap between those 866 primes: 10284

Found 10815 primes under 10000000 whose preceding neighboring pair are tetraprimes
of which 5176 have a neighboring pair one of whose factors is 7.

Minimum gap between those 10815 primes: 4
Median gap between those 10815 primes: 648
Maximum gap between those 10815 primes: 9352

Found 10551 primes under 10000000 whose following neighboring pair are tetraprimes
of which 5069 have a neighboring pair one of whose factors is 7.

Minimum gap between those 10551 primes: 4
Median gap between those 10551 primes: 660
Maximum gap between those 10551 primes: 10284


C++

#include <algorithm>
#include <cstdint>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>

std::vector<uint32_t> primes;

void sieve_primes(const uint32_t& limit) {
	std::vector<bool> marked_prime(limit + 1, true);

	for ( uint32_t i = 2; i * i <= limit; ++i ) {
		if ( marked_prime[i] ) {
			for ( uint32_t j = i * i; j <= limit; j += i ) {
				marked_prime[j] = false;
			}
		}
	}

	for ( uint32_t i = 2; i <= limit; ++i ) {
		if ( marked_prime[i] ) {
			primes.emplace_back(i);
		}
	}
}

uint32_t largest_less_than(const uint32_t& n) {
    auto lower = std::lower_bound(primes.begin(), primes.end(), n);
    return primes[std::distance(primes.begin(), lower) - 1];
}

uint32_t median(const std::vector<uint32_t>& list) {
	if ( list.size() % 2 == 0 ) {
		return ( list[list.size() / 2 - 1] + list[list.size() / 2] ) / 2;
	}
	return list[list.size() / 2];
}

bool is_tetraPrime(uint32_t n) {
    uint32_t count = 0;
    uint32_t previous_factor = 1;
    for ( uint32_t prime : primes ) {
        uint64_t limit = prime * prime;
        if ( count == 0 ) {
            limit *= limit;
        } else if ( count == 1 ) {
            limit *= prime;
        }
        if ( limit <= n ) {
            while ( n % prime == 0 ) {
                if ( count == 4 || prime == previous_factor ) {
                	return false;
                }
                count++;
                n /= prime;
                previous_factor = prime;
            }
        } else {
            break;
        }
    }

    if ( n > 1 ) {
        if ( count == 4 || n == previous_factor ) {
        	return false;
        }
        count++;
    }
    return count == 4;
}

int main() {
	sieve_primes(10'000'000);

	const uint32_t largest_prime_5 = largest_less_than(100'000);
	const uint32_t largest_prime_6 = largest_less_than(1'000'000);
	const uint32_t largest_prime_7 = primes.back();
	std::vector<uint32_t> tetras_preceeding;
	std::vector<uint32_t> tetras_following;
	uint32_t sevens_preceeding = 0;
	uint32_t sevens_following = 0;
	uint32_t limit = 100'000;

	for ( const uint32_t& prime : primes ) {
	    if ( is_tetraPrime(prime - 1) && is_tetraPrime(prime - 2) ) {
	        tetras_preceeding.emplace_back(prime);
	        if ( ( prime - 1 ) % 7 == 0 || ( prime - 2 ) % 7 == 0 ) {
	        	sevens_preceeding++;
	        }
	    }

	    if ( is_tetraPrime(prime + 1) && is_tetraPrime(prime + 2) ) {
	        tetras_following.emplace_back(prime);
	        if ( ( prime + 1 ) % 7 == 0 || ( prime + 2 ) % 7 == 0 ) {
	        	sevens_following++;
	        }
	    }

	    if ( prime == largest_prime_5 || prime == largest_prime_6 || prime == largest_prime_7 ) {
	        for ( uint32_t i = 0; i <= 1; ++i ) {
	            std::vector<uint32_t> tetras = ( i == 0 ) ? tetras_preceeding : tetras_following;
	            const uint64_t size = tetras.size();
	            const uint32_t sevens = ( i == 0 ) ? sevens_preceeding : sevens_following;
	            const std::string text = ( i == 0 ) ? "preceding" : "following";

	            std::cout << "Found " << size << " primes under " << limit << " whose "
	            		  << text << " neighboring pair are tetraprimes";
	            if ( prime == largest_prime_5 ) {
	                std::cout << ":" << std::endl;
	                for ( uint64_t j = 0; j < size; ++j ) {
	                	std::cout << std::setw(7) << tetras[j] << ( ( j % 10 == 9 ) ? "\n" : "" );
	                }
	                std::cout << std::endl;
	            }
	            std::cout << std::endl;
	            std::cout << "of which " << sevens << " have a neighboring pair one of whose factors is 7."
	            		  << std::endl << std::endl;

	            std::vector<uint32_t> gaps(size - 1, 0);
	            for ( uint64_t k = 0; k < size - 1; ++k ) {
	            	gaps[k] = tetras[k + 1] - tetras[k];
	            }
	            std::sort(gaps.begin(), gaps.end());
	            const uint32_t minimum = gaps.front();
	            const uint32_t maximum = gaps.back();
	            const uint32_t middle = median(gaps);
	            std::cout << "Minimum gap between those " << size << " primes: " << minimum << std::endl;
	            std::cout << "Median  gap between those " << size << " primes: " << middle << std::endl;
	            std::cout << "Maximum gap between those " << size << " primes: " << maximum << std::endl;
	            std::cout << std::endl;
	        }
	        limit *= 10;
	    }
	}
}
Output:
Found 49 primes under 100000 whose preceding neighboring pair are tetraprimes:
   8647  15107  20407  20771  21491  23003  23531  24767  24971  27967
  29147  33287  34847  36779  42187  42407  42667  43331  43991  46807
  46867  51431  52691  52747  53891  54167  58567  63247  63367  69379
  71711  73607  73867  74167  76507  76631  76847  80447  83591  84247
  86243  87187  87803  89387  93887  97547  97847  98347  99431

of which 31 have a neighboring pair one of whose factors is 7.

Minimum gap between those 49 primes: 56
Median  gap between those 49 primes: 1208
Maximum gap between those 49 primes: 6460

Found 46 primes under 100000 whose following neighboring pair are tetraprimes:
   8293  16553  17389  18289  22153  26893  29209  33409  35509  36293
  39233  39829  40493  41809  45589  48109  58393  59629  59753  59981
  60493  60913  64013  64921  65713  66169  69221  71329  74093  75577
  75853  77689  77933  79393  79609  82913  84533  85853  87589  87701
  88681  91153  93889  96017  97381  98453

of which 36 have a neighboring pair one of whose factors is 7.

Minimum gap between those 46 primes: 112
Median  gap between those 46 primes: 1460
Maximum gap between those 46 primes: 10284

Found 885 primes under 1000000 whose preceding neighboring pair are tetraprimes
of which 503 have a neighboring pair one of whose factors is 7.

Minimum gap between those 885 primes: 4
Median  gap between those 885 primes: 756
Maximum gap between those 885 primes: 7712

Found 866 primes under 1000000 whose following neighboring pair are tetraprimes
of which 492 have a neighboring pair one of whose factors is 7.

Minimum gap between those 866 primes: 4
Median  gap between those 866 primes: 832
Maximum gap between those 866 primes: 10284

Found 10815 primes under 10000000 whose preceding neighboring pair are tetraprimes
of which 5176 have a neighboring pair one of whose factors is 7.

Minimum gap between those 10815 primes: 4
Median  gap between those 10815 primes: 648
Maximum gap between those 10815 primes: 9352

Found 10551 primes under 10000000 whose following neighboring pair are tetraprimes
of which 5069 have a neighboring pair one of whose factors is 7.

Minimum gap between those 10551 primes: 4
Median  gap between those 10551 primes: 660
Maximum gap between those 10551 primes: 10284

FreeBASIC

Translation of: XPL0
#include "isprime.bas"

Dim Shared As Boolean Have7              'A tetraprime factor is 7

Function isTetraprime(n As Integer) As Boolean
    Dim As Boolean distinto
    Dim As Integer div = 2, count = 0
    While n >= div*div
        distinto = True
        While n Mod div = 0
            If Not distinto Then Return False
            distinto = False
            count += 1
            If div = 7 Then Have7 = True
            n /= div
        Wend
        div += 1
    Wend
    If n > 1 Then count += 1
    Return count = 4
End Function

Dim As Integer signo = -1
Dim As Integer TenPower = 1e5
Dim As Integer f, g, n, m, count, count7
Dim As Integer Gap, GapMin, GapMax, GapSum
For f = 5 To 7
    For g = 1 To 2       'preceding or following neighboring pairs
        count = 0  
        count7 = 0 
        m = 0 
        GapMin = -1
        GapMax = 0  
        GapSum = 0
        If f = 5 Then Print '100_000
        For n = 3 To TenPower-1
            If isPrime(n) Then
                Have7 = False
                If isTetraprime(n+1*signo) Then
                    If isTetraprime(n+2*signo) Then
                        count += 1
                        If f = 5 Then
                            Print Using "#######"; n;
                            If count Mod 10 = 0 Then Print
                        End If
                        If Have7 Then count7 += 1
                        If m <> 0 Then
                            Gap = n - m
                            If Gap <= GapMin Then GapMin = Gap
                            If Gap > GapMax Then GapMax = Gap
                            GapSum += Gap
                        End If
                        m = n
                    End If
                End If
                n += 1
            End If
        Next n
        Print Using !"\nFound ##,### primes under ##,###,### whose preceding neighboring pair are tetraprimes"; count; TenPower
        Print Using "of which #,### have a neighboring pair, one of whose factors is 7."; count7
        Print Using !"\nMinimum gap between & primes : ##,###"; count; GapMin
        Print Using "Average gap between & primes : ##,###"; count; (GapSum / (count-1))
        Print Using "Maximum gap between & primes : ##,###"; count; GapMax
        signo = signo * -1
    Next g
    TenPower *= 10
Next f

Sleep
Output:
   8647  15107  20407  20771  21491  23003  23531  24767  24971  27967
  29147  33287  34847  36779  42187  42407  42667  43331  43991  46807
  46867  51431  52691  52747  53891  54167  58567  63247  63367  69379
  71711  73607  73867  74167  76507  76631  76847  80447  83591  84247
  86243  87187  87803  89387  93887  97547  97847  98347  99431
Found     49 primes under    100,000 whose preceding neighboring pair are tetraprimes
of which    31 have a neighboring pair, one of whose factors is 7.

Minimum gap between 49 primes :     56
Average gap between 49 primes :  1,891
Maximum gap between 49 primes :  6,460

   8293  16553  17389  18289  22153  26893  29209  33409  35509  36293
  39233  39829  40493  41809  45589  48109  58393  59629  59753  59981
  60493  60913  64013  64921  65713  66169  69221  71329  74093  75577
  75853  77689  77933  79393  79609  82913  84533  85853  87589  87701
  88681  91153  93889  96017  97381  98453
Found     46 primes under    100,000 whose preceding neighboring pair are tetraprimes
of which    36 have a neighboring pair, one of whose factors is 7.

Minimum gap between 46 primes :    112
Average gap between 46 primes :  2,004
Maximum gap between 46 primes : 10,284

Found    885 primes under  1,000,000 whose preceding neighboring pair are tetraprimes
of which   503 have a neighboring pair, one of whose factors is 7.

Minimum gap between 885 primes :      4
Average gap between 885 primes :  1,119
Maximum gap between 885 primes :  7,712

Found    866 primes under  1,000,000 whose preceding neighboring pair are tetraprimes
of which   492 have a neighboring pair, one of whose factors is 7.

Minimum gap between 866 primes :      4
Average gap between 866 primes :  1,146
Maximum gap between 866 primes : 10,284

Found 10,815 primes under 10,000,000 whose preceding neighboring pair are tetraprimes
of which 5,176 have a neighboring pair, one of whose factors is 7.

Minimum gap between 10815 primes :      4
Average gap between 10815 primes :    924
Maximum gap between 10815 primes :  9,352

Found 10,551 primes under 10,000,000 whose preceding neighboring pair are tetraprimes
of which 5,069 have a neighboring pair, one of whose factors is 7.

Minimum gap between 10551 primes :      4
Average gap between 10551 primes :    947
Maximum gap between 10551 primes : 10,284

Go

Translation of: Wren
Library: Go-rcu
package main

import (
    "fmt"
    "rcu"
    "sort"
)

const LIMIT = int(1e7)
var primes = rcu.Primes(LIMIT)

func isTetraPrime(n int) bool {
    count := 0;
    prevFact := 1
    for _, p := range primes {
        limit := p * p
        if count == 0 {
            limit *= limit
        } else if count == 1 {
            limit *= p
        }
        if limit <= n {
            for n % p == 0 {
                if count == 4 || p == prevFact {
                    return false
                }
                count++
                n /= p
                prevFact = p
            }
        } else {
            break
        }
    }
    if n > 1 {
        if count == 4 || n == prevFact {
            return false
        }
        count++
    }
    return count == 4
}    
       
// Note that 'gaps' will only contain even numbers here.
func median(gaps []int) int {
    le := len(gaps)
    m := le / 2
    if le&1 == 1 {
        return gaps[m]
    }
    return (gaps[m] + gaps[m-1]) / 2
}

func main() {
    highest5 := primes[sort.SearchInts(primes, int(1e5))-1]
    highest6 := primes[sort.SearchInts(primes, int(1e6))-1]
    highest7 := primes[len(primes)-1]
    var tetras1, tetras2 []int
    sevens1, sevens2 := 0, 0
    j := 100_000
    for _, p := range primes {
        // process even numbers first as likely to have most factors
        if isTetraPrime(p-1) && isTetraPrime(p-2) {
            tetras1 = append(tetras1, p)
            if (p-1)%7 == 0 || (p-2)%7 == 0 {
                sevens1++
            }
        }

        if isTetraPrime(p+1) && isTetraPrime(p+2) {
            tetras2 = append(tetras2, p)
            if (p+1)%7 == 0 || (p+2)%7 == 0 {
                sevens2++
            }
        }

        if p == highest5 || p == highest6 || p == highest7 {
            for i := 0; i < 2; i++ {
                tetras := tetras1
                if i == 1 {
                    tetras = tetras2
                }
                sevens := sevens1
                if i == 1 {
                    sevens = sevens2
                }
                c := len(tetras)
                t := "preceding"
                if i == 1 {
                    t = "following"
                }
                fmt.Printf("Found %s primes under %s whose %s neighboring pair are tetraprimes", rcu.Commatize(c), rcu.Commatize(j), t)
                if p == highest5 {
                    fmt.Printf(":\n")
                    for k := 0; k < c; k++ {
                        fmt.Printf("%5d ", tetras[k])
                        if (k+1)%10 == 0 {
                            fmt.Println()
                        }
                    }
                    fmt.Println()
                }
                fmt.Println()
                fmt.Printf("of which %s have a neighboring pair one of whose factors is 7.\n\n", rcu.Commatize(sevens))
                gaps := make([]int, c-1)
                for k := 0; k < c-1; k++ {
                    gaps[k] = tetras[k+1] - tetras[k]
                }
                sort.Ints(gaps)
                mins := rcu.Commatize(gaps[0])
                maxs := rcu.Commatize(gaps[c-2])
                meds := rcu.Commatize(median(gaps))
                cs := rcu.Commatize(c)
                fmt.Printf("Minimum gap between those %s primes : %s\n", cs, mins)
                fmt.Printf("Median  gap between those %s primes : %s\n", cs, meds)
                fmt.Printf("Maximum gap between those %s primes : %s\n", cs, maxs)
                fmt.Println()
            }
            j *= 10
        }
    }
}
Output:
Identical to Wren example.

J

For this task we could use a couple tools -- one to enumerate primes less than some limit, and one to determine if a number is a tetraprime:

primeslt=: i.&.(p:inv)

tetrap=: 0:`(4=#@~.)@.(4=#)@q: ::0:"0

Thus:

   NB. (1) primes less than 1e5 preceeded by two tetraprimes
   {{y#~*/tetrap 1 2-~/y}} primeslt 1e5
8647 15107 20407 20771 21491 23003 23531 24767 24971 27967 29147 33287 34847 36779 42187 42407 42667 43331 43991 46807 46867 51431 52691 52747 53891 54167 58567 63247 63367 69379 71711 73607 73867 74167 76507 76631 76847 80447 83591 84247 86243 87187 87803...
   NB. (2) primes less than 1e5 followed by two tetraprimes
   {{y#~*/tetrap 1 2+/y}} primeslt 1e5
8293 16553 17389 18289 22153 26893 29209 33409 35509 36293 39233 39829 40493 41809 45589 48109 58393 59629 59753 59981 60493 60913 64013 64921 65713 66169 69221 71329 74093 75577 75853 77689 77933 79393 79609 82913 84533 85853 87589 87701 88681 91153 93889...
   NB. (3a) how many primes from (1) have 7 in a factor of a number in the preceeding pair? 
   +/0+./ .=7|1 2-~/{{y#~*/tetrap 1 2-~/y}} primeslt 1e5
31
   NB. (3b) how many primes from (2) have 7 in a factor of a number in the following pair? 
   +/0+./ .=7|1 2+/{{y#~*/tetrap 1 2+/y}} primeslt 1e5
36
   NB. (4a) minimum, maximum gap between primes in (1)
   (<./,>./)2 -~/\{{y#~*/tetrap 1 2-~/y}} primeslt 1e5
56 6460
   NB. (4b) minimum, maximum gap between primes in (2)
   (<./,>./)2 -~/\{{y#~*/tetrap 1 2+/y}} primeslt 1e5
112 10284
   NB. number of type (1) primes but for primes less than 1e6
   #{{y#~*/tetrap 1 2-~/y}} primeslt 1e6
885
   NB. number of type (2) primes but for primes less than 1e6
   #{{y#~*/tetrap 1 2+/y}} primeslt 1e5
46
   NB. count of type (3a) for primes less than 1e6
   +/0+./ .=7|1 2-~/{{y#~*/tetrap 1 2-~/y}} primeslt 1e6
503
   NB. count of type (3b) for primes less than 1e6
   +/0+./ .=7|1 2+/{{y#~*/tetrap 1 2+/y}} primeslt 1e6
492
   NB. gaps of type (4a) for primes less than 1e6
   (<./,>./)2 -~/\{{y#~*/tetrap 1 2-~/y}} primeslt 1e6
4 7712
   NB. gaps of type (4b) for primes less than 1e6
   (<./,>./)2 -~/\{{y#~*/tetrap 1 2+/y}} primeslt 1e6
4 10284

Java

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public final class PrimeNumbersNeighboringPairsTetraprimes {

	public static void main(String[] aArgs) {
		listPrimeNumbers(10_000_000);

		final int largest_prime_5 = largestLessThan(100_000);
		final int largest_prime_6 = largestLessThan(1_000_000);
		final int largest_prime_7 = primes.get(primes.size() - 1);
		List<Integer> tetras_preceeding = new ArrayList<Integer>();
		List<Integer> tetras_following = new ArrayList<Integer>();
		int sevens_preceeding = 0;
		int sevens_following = 0;
		int limit = 100_000;

		for ( int prime : primes ) {
		    if ( isTetraPrime(prime - 1) && isTetraPrime(prime - 2) ) {
		        tetras_preceeding.add(prime);
		        if ( ( prime - 1 ) % 7 == 0 || ( prime - 2 ) % 7 == 0 ) {
		        	sevens_preceeding += 1;
		        }
		    }

		    if ( isTetraPrime(prime + 1) && isTetraPrime(prime + 2) ) {
		        tetras_following.add(prime);
		        if ( ( prime + 1 ) % 7 == 0 || ( prime + 2 ) % 7 == 0 ) {
		        	sevens_following += 1;
		        }
		    }

		    if ( prime == largest_prime_5 || prime == largest_prime_6 || prime == largest_prime_7 ) {
		        for ( int i = 0; i <= 1; i++ ) {
		            List<Integer> tetras = ( i == 0 ) ? 
		            	new ArrayList<Integer>(tetras_preceeding) : new ArrayList<Integer>(tetras_following);
		            final int size = tetras.size();
		            final int sevens = ( i == 0 ) ? sevens_preceeding : sevens_following;
		            final String text = ( i == 0 ) ? "preceding" : "following";

		            System.out.print("Found " + size + " primes under " + limit + " whose "
		            	+ text + " neighboring pair are tetraprimes");
		            if ( prime == largest_prime_5 ) {
		                System.out.println(":");
		                for ( int j = 0; j < size; j++ ) {
		                	System.out.print(String.format("%7d%s", tetras.get(j), ( j % 10 == 9 ) ? "\n" : "" ));
		                }
		                System.out.println();
		            }
		            System.out.println();
		            System.out.println("of which " + sevens + " have a neighboring pair one of whose factors is 7.");
		            System.out.println();

		            List<Integer> gaps = new ArrayList<Integer>(size - 1);
		            for ( int k = 0; k < size - 1; k++ ) {
		            	gaps.add(tetras.get(k + 1) - tetras.get(k));
		            }
		            Collections.sort(gaps);
		            final int minimum = gaps.get(0);
		            final int maximum = gaps.get(gaps.size() - 1);
		            final int middle = median(gaps);
		            System.out.println("Minimum gap between those " + size + " primes: " + minimum);
		            System.out.println("Median  gap between those " + size + " primes: " + middle);
		            System.out.println("Maximum gap between those " + size + " primes: " + maximum);
		            System.out.println();
		        }
		        limit *= 10;
		    }
		}
	}
	
	private static boolean isTetraPrime(int aNumber) {
	    int count = 0;
	    int previousFactor = 1;
	    for ( int prime : primes ) {
	        int limit = prime * prime;
	        if ( count == 0 ) {
	            limit *= limit;
	        } else if ( count == 1 ) {
	            limit *= prime;
	        }
	        if ( limit <= aNumber ) {
	            while ( aNumber % prime == 0 ) {
	                if ( count == 4 || prime == previousFactor ) {
	                	return false;
	                }
	                count += 1;
	                aNumber /= prime;
	                previousFactor = prime;
	            }
	        } else {
	            break;
	        }
	    }

	    if ( aNumber > 1 ) {
	        if ( count == 4 || aNumber == previousFactor ) {
	        	return false;
	        }
	        count += 1;
	    }
	    return count == 4;
	}
	
	private static int median(List<Integer> aList) {
		if ( aList.size() % 2 == 0 ) {
			return ( aList.get(aList.size() / 2 - 1) + aList.get(aList.size() / 2) ) / 2;
		}
		return aList.get(aList.size() / 2);
	}
	
	private static int largestLessThan(int aNumber) {
		final int index = Collections.binarySearch(primes, aNumber);
		if ( index > 0 ) {
			return primes.get(index - 1);
		}
		return primes.get(-index - 2);
	}
	
	private static void listPrimeNumbers(int aLimit) {
		final int halfLimit = ( aLimit + 1 ) / 2;
		boolean[] composite = new boolean[halfLimit];
		for ( int i = 1, p = 3; i < halfLimit; p += 2, i++ ) {
			if ( ! composite[i] ) {
				for ( int j = i + p; j < halfLimit; j += p ) {
					composite[j] = true;
				}
			}
		}
		
		primes = new ArrayList<Integer>();
		primes.add(2);
		for ( int i = 1, p = 3; i < halfLimit; p += 2, i++ ) {
			if ( ! composite[i] ) { 
				primes.add(p);
			}
		}
	}
	
	private static List<Integer> primes;

}
Output:
Found 49 primes under 100000 whose preceding neighboring pair are tetraprimes:
   8647  15107  20407  20771  21491  23003  23531  24767  24971  27967
  29147  33287  34847  36779  42187  42407  42667  43331  43991  46807
  46867  51431  52691  52747  53891  54167  58567  63247  63367  69379
  71711  73607  73867  74167  76507  76631  76847  80447  83591  84247
  86243  87187  87803  89387  93887  97547  97847  98347  99431

of which 31 have a neighboring pair one of whose factors is 7.

Minimum gap between those 49 primes: 56
Median  gap between those 49 primes: 1208
Maximum gap between those 49 primes: 6460

Found 46 primes under 100000 whose following neighboring pair are tetraprimes:
   8293  16553  17389  18289  22153  26893  29209  33409  35509  36293
  39233  39829  40493  41809  45589  48109  58393  59629  59753  59981
  60493  60913  64013  64921  65713  66169  69221  71329  74093  75577
  75853  77689  77933  79393  79609  82913  84533  85853  87589  87701
  88681  91153  93889  96017  97381  98453

of which 36 have a neighboring pair one of whose factors is 7.

Minimum gap between those 46 primes: 112
Median  gap between those 46 primes: 1460
Maximum gap between those 46 primes: 10284

Found 885 primes under 1000000 whose preceding neighboring pair are tetraprimes
of which 503 have a neighboring pair one of whose factors is 7.

Minimum gap between those 885 primes: 4
Median  gap between those 885 primes: 756
Maximum gap between those 885 primes: 7712

Found 866 primes under 1000000 whose following neighboring pair are tetraprimes
of which 492 have a neighboring pair one of whose factors is 7.

Minimum gap between those 866 primes: 4
Median  gap between those 866 primes: 832
Maximum gap between those 866 primes: 10284

Found 10815 primes under 10000000 whose preceding neighboring pair are tetraprimes
of which 5176 have a neighboring pair one of whose factors is 7.

Minimum gap between those 10815 primes: 4
Median  gap between those 10815 primes: 648
Maximum gap between those 10815 primes: 9352

Found 10551 primes under 10000000 whose following neighboring pair are tetraprimes
of which 5069 have a neighboring pair one of whose factors is 7.

Minimum gap between those 10551 primes: 4
Median  gap between those 10551 primes: 660
Maximum gap between those 10551 primes: 10284

jq

Adapted from Wren

Works with jq, the C implementation of jq

Works with gojq, the Go implementation of jq (*)

As in the task description, this entry adheres to the definition of a tetraprime as an integer with exactly four distinct prime factors.

(*) But gojq requires an inordinate amount of memory (6.7 GB) to complete the program as shown (i.e., test(1000000)).

# The following may be omitted if using the C implementation of jq
def _nwise($n):
  def n: if length <= $n then . else .[0:$n] , (.[$n:] | n) end;
  n;

### Generic functions

# Input is assumed to be an integer.
# Use a wheel with basis [2, 3, 5]
def is_prime:
  if . < 2 then false
  else . as $n
  | if   ($n % 2 == 0) then $n == 2
    elif ($n % 3 == 0) then $n == 3
    elif ($n % 5 == 0) then $n == 5
    else [4, 2, 4, 2, 4, 6, 2, 6] as $inc
    | { n: ., k: 7 }
    | .i = 0
    | first(
        while(.k * .k <= .n;
          if .n % .k == 0
          then .emit = 0
          else .k += $inc[.i]
          | .emit = null
          | .i = ((.i + 1) % 8)
          end)
        | (select(.emit) )) // true
    | . == true
    end
  end;

def inform(msg):
  (msg + "\n" | stderr | empty), .;

def lpad($len): tostring | ($len - length) as $l | (" " * $l) + .;

# tabular print
def tprint($columns; $width):
  reduce _nwise($columns) as $row ("";
     . + ($row|map(lpad($width)) | join(" ")) + "\n" );

# It is assumed the input is sorted
def median:
  (length/2) as $l2
  | if $l2 == 0 then null
    elif length % 2 == 0
    then ($l2 | floor) as $m | (.[$m-1] + .[$m])/2
    else .[$l2]
    end;

# . is assumed to be sorted
# Output: the index of $x in . or else the insertion point
def nearest($x):
  bsearch($x) as $ix
  | if $ix >= 0 then $ix
    else -($ix+1)
    end;

### Tetraprimes

# Input: a sufficiently large array of primes
def isTetraPrime($n):
  def sq: .*.;
  . as $primes
  | { $n,
      count: 0,
      prevFactor: 1 }
  | label $out
  | foreach $primes[] as $p (.;
      .emit = null
      | ($p | sq) as $p2
      | (if   .count == 0 then $p2 | sq
         elif .count == 1 then $p2*$p
         else $p2 end) as $limit
      | if $limit <= .n
        then until(.emit or .n % $p != 0;
               if (.count == 4 or $p == .prevFactor)
               then .emit=0, break $out
               else .count += 1
               | .n |= ((./$p)|floor)
               | .prevFactor = $p
               end)
        else .emit = 1, break $out
        end)
  | select(.emit)
  | if .emit == 0 then false
    else if .n > 1
         then if .count == 4 or .n == .prevFact then false
              else .count += 1
              | .count == 4
              end
         else .count == 4
         end
    end ;

### The task

# $n determines the number of primes to examine, normally 1e5 1e6 or 1e7
def task($n):
  def p($k): reduce range(0;$k) as $_ (1; .*10);
  def highest($k):
     p($k) as $p
     | if $n >= $p then .[nearest($p) - 1] else null end;

  [range(0;$n) | select(is_prime)]
  | . as $primes
  | highest(5) as $highest5
  | highest(6) as $highest6
  | highest(7) as $highest7
  | { tetras1: [],
      tetras2: [],
      sevens1:  0,
      sevens2:  0,
      j:   100000
   }
  | foreach $primes[] as $p (.;
      # process even numbers first as likely to have most factors
      if ($primes|isTetraPrime($p-1)) and ($primes|isTetraPrime($p-2)) 
      then .tetras1 += [$p]
      | if (($p-1)%7 == 0 or ($p-2)%7 == 0) then .sevens1 += 1 end
      end

      | if ($primes | isTetraPrime($p+1)) and ($primes|isTetraPrime($p+2))
        then .tetras2 += [$p]
        | if (($p+1)%7 == 0 or ($p+2)%7 == 0) then .sevens2 += 1 end
        end
      # Reporting ...
      | if $p | IN($highest5, $highest6, $highest7)
        then foreach (0,1) as $i (.;
              (if ($i == 0) then .tetras1 else .tetras2 end) as $tetras
            | (if ($i == 0) then .sevens1 else .sevens2 end) as $sevens
            | ($tetras|length) as $c
            | (if ($i == 0) then "preceding" else "following" end) as $t
            | inform("Found \($c) primes under \(.j) whose \($t) neighboring pair are tetraprimes:")
            | if ($p == $highest5) 
              then inform($tetras|tprint(10;5))
              end
            | inform("of which \($sevens) have a neighboring pair one of whose factors is 7.\n")
            | ([range(0; $c-1) | $tetras[.+1] - $tetras[.]] | sort) as $gaps
            | inform("Minimum gap between those \($c) primes : \($gaps[0])")
            | inform("Median  gap between those \($c) primes : \($gaps|median)")
            | inform("Maximum gap between those \($c) primes : \($gaps[-1])\n")
            )
         | .j *= 10
         end
      )
      | empty
;

task(1000000)
Output:
Found 49 primes under 100000 whose preceding neighboring pair are tetraprimes:
 8647 15107 20407 20771 21491 23003 23531 24767 24971 27967
29147 33287 34847 36779 42187 42407 42667 43331 43991 46807
46867 51431 52691 52747 53891 54167 58567 63247 63367 69379
71711 73607 73867 74167 76507 76631 76847 80447 83591 84247
86243 87187 87803 89387 93887 97547 97847 98347 99431

of which 31 have a neighboring pair one of whose factors is 7.

Minimum gap between those 49 primes : 56
Median  gap between those 49 primes : 1208
Maximum gap between those 49 primes : 6460

Found 46 primes under 100000 whose following neighboring pair are tetraprimes:
 8293 16553 17389 18289 22153 26893 29209 33409 35509 36293
39233 39829 40493 41809 45589 48109 58393 59629 59753 59981
60493 60913 64013 64921 65713 66169 69221 71329 74093 75577
75853 77689 77933 79393 79609 82913 84533 85853 87589 87701
88681 91153 93889 96017 97381 98453

of which 36 have a neighboring pair one of whose factors is 7.

Minimum gap between those 46 primes : 112
Median  gap between those 46 primes : 1460
Maximum gap between those 46 primes : 10284

Found 885 primes under 1000000 whose preceding neighboring pair are tetraprimes:
of which 503 have a neighboring pair one of whose factors is 7.

Minimum gap between those 885 primes : 4
Median  gap between those 885 primes : 756
Maximum gap between those 885 primes : 7712

Found 866 primes under 1000000 whose following neighboring pair are tetraprimes:
of which 492 have a neighboring pair one of whose factors is 7.

Minimum gap between those 866 primes : 4
Median  gap between those 866 primes : 832
Maximum gap between those 866 primes : 10284

Julia

Yet another "output an OEIS sequence as produced by a function which takes the prime number sequence as its input" task.

""" rosettacode.org/wiki/Prime_numbers_whose_neighboring_pairs_are_tetraprimes """

using Statistics
using Primes

istetraprime(n) = (a = map(last, factor(n).pe); length(a) == 4 && all(==(1), a))
are_following_tetraprimes(n, cnt = 2) = all(istetraprime, n+1:n+cnt)
are_preceding_tetraprimes(n, cnt = 2) = all(istetraprime, n-cnt:n-1)

let
    primes1M = primes(10^7)
    pre1M = filter(are_preceding_tetraprimes, primes1M)       
    fol1M = filter(are_following_tetraprimes, primes1M)
    pre100k = filter(<(100_000), pre1M)
    fol100k = filter(<(100_000), fol1M)

    pre1M_with7 = filter(i -> any(k -> (i - k) % 7 == 0, 1:2), pre1M)
    fol1M_with7 = filter(i -> any(k -> (i + k) % 7 == 0, 1:2), fol1M)
    pre100k_with7 = filter(<(100_000), pre1M_with7)
    fol100k_with7 = filter(<(100_000), fol1M_with7)

    p_gaps1M = [pre1M[i] - pre1M[i - 1] for i in 2:lastindex(pre1M)]
    f_gaps1M = [fol1M[i] - fol1M[i - 1] for i in 2:lastindex(fol1M)]
    p_gaps100k = [pre1M[i] - pre1M[i - 1] for i in 2:lastindex(pre1M) if pre1M[i] < 100_000]
    f_gaps100k = [fol1M[i] - fol1M[i - 1] for i in 2:lastindex(fol1M) if fol1M[i] < 100_000]

    pmin1M, pmedian1M, pmax1M = minimum(p_gaps1M), median(p_gaps1M), maximum(p_gaps1M)
    fmin1M, fmedian1M, fmax1M = minimum(f_gaps1M), median(f_gaps1M), maximum(f_gaps1M)
    pmin100k, pmedian100k, pmax100k = minimum(p_gaps100k), median(p_gaps100k), maximum(p_gaps100k)
    fmin100k, fmedian100k, fmax100k = minimum(f_gaps100k), median(f_gaps100k), maximum(f_gaps100k)

    for (tet, s, s2, tmin, tmed, tmax, t7) in [
        (pre100k, "100,000", "preceding", pmin100k, pmedian100k, pmax100k, pre100k_with7),
        (fol100k, "100,000", "following", fmin100k, fmedian100k, fmax100k, fol100k_with7),
        (pre1M, "1,000,000", "preceding", pmin1M, pmedian1M, pmax1M, pre1M_with7),
        (fol1M, "1,000,000", "following", fmin1M, fmedian1M, fmax1M, fol1M_with7),
    ]
        print("Found $(length(tet)) primes under $s whose $s2 neighboring pair are tetraprimes")
        if s == "100,000"
            println(":")
            foreach(p -> print(rpad(p[2], 6), p[1] % 10 == 0 ? "\n" : ""), enumerate(tet))
            println()
        else
            println(".")
        end
        println("Minimum, median, and maximum gaps between those primes: $tmin $tmed $tmax")
        println("Of those primes, $(length(t7)) have a neighboring pair one of whose factors is 7.\n")
    end
end
Output:
Found 49 primes under 100,000 whose preceding neighboring pair are tetraprimes:
8647  15107 20407 20771 21491 23003 23531 24767 24971 27967 
29147 33287 34847 36779 42187 42407 42667 43331 43991 46807
46867 51431 52691 52747 53891 54167 58567 63247 63367 69379
71711 73607 73867 74167 76507 76631 76847 80447 83591 84247
86243 87187 87803 89387 93887 97547 97847 98347 99431
Minimum, median, and maximum gaps between those primes: 56 1208.0 6460
Of those primes, 31 have a neighboring pair one of whose factors is 7.

Found 46 primes under 100,000 whose following neighboring pair are tetraprimes:
8293  16553 17389 18289 22153 26893 29209 33409 35509 36293
39233 39829 40493 41809 45589 48109 58393 59629 59753 59981
60493 60913 64013 64921 65713 66169 69221 71329 74093 75577 
75853 77689 77933 79393 79609 82913 84533 85853 87589 87701
88681 91153 93889 96017 97381 98453
Minimum, median, and maximum gaps between those primes: 112 1460.0 10284
Of those primes, 36 have a neighboring pair one of whose factors is 7.

Found 10815 primes under 1,000,000 whose preceding neighboring pair are tetraprimes.
Minimum, median, and maximum gaps between those primes: 4 648.0 9352
Of those primes, 5176 have a neighboring pair one of whose factors is 7.

Found 10551 primes under 1,000,000 whose following neighboring pair are tetraprimes.
Minimum, median, and maximum gaps between those primes: 4 660.0 10284
Of those primes, 5069 have a neighboring pair one of whose factors is 7.

Mathematica / Wolfram Language

ClearAll[ primesUpTo, tetraprimeQ, limit, primesUpToLimit, 
  primesWithPreceedingTetraprimePairs, 
  primesWithFollowingTetraprimePairs];

primesUpTo[n_Integer?Positive] := Prime[Range[PrimePi[n]]];

tetraprimeQ[n_Integer] := FactorInteger[n][[All, 2]] == {1, 1, 1, 1};

limit = 10^7;

primesUpToLimit = primesUpTo[limit];
primesWithPreceedingTetraprimePairs = Select[primesUpToLimit, tetraprimeQ[# - 1] && tetraprimeQ[# - 2] &];
primesWithFollowingTetraprimePairs = Select[primesUpToLimit, tetraprimeQ[# + 1] && tetraprimeQ[# + 2] &];

formatPrimesList[primes_List] := 
  TableForm@
   Partition[
    StringPadLeft[ToString[#], Length@IntegerDigits@Max@primes] & /@ 
     primes, UpTo[10]];

showOutput[n_Integer?Positive] :=  Module[{preceeding, following, numberFollowingWithOneOfPairDivisibleBy7, numberPreceedingWithOneOfPairDivisibleBy7, differences},

   	preceeding = Select[primesWithPreceedingTetraprimePairs, # <= n &];
   	numberPreceedingWithOneOfPairDivisibleBy7 = Length@Select[preceeding, 1 <= Mod[#, 7] <= 2 &];
   	following = Select[primesWithFollowingTetraprimePairs, # <= n &];
   	numberFollowingWithOneOfPairDivisibleBy7 = Length@Select[following, 5 <= Mod[#, 7] <= 6 &];
   
   	Print[StringJoin@ConstantArray["=", 80]];
   	Print["Found ", Length@preceeding, " primes below ", n, " whose preceeding pair are tetraprimes", 
    If[n <= 100000, ":", ","]];
   	If[n <= 100000,
    		Print@formatPrimesList@preceeding;];
   	Print["of which ", numberPreceedingWithOneOfPairDivisibleBy7, " have a neighboring pair one of whose factors is 7."];
   	differences = Differences@preceeding;
   	Print["Minimum gap between those ", Length@preceeding, " primes : ", Min@differences];
   	Print["Median  gap between those ", Length@preceeding, " primes : ", Median@differences];
   	Print["Maximum gap between those ", Length@preceeding, " primes : ", Max@differences];
   
   	Print[];
   
   	Print["Found ", Length@following, " primes below ", n, " whose following pair are tetraprimes", 
    If[n <= 100000, ":", ","]];
   	If [n <= 100000,
    		Print@formatPrimesList@following;];
   	Print["of which ", numberFollowingWithOneOfPairDivisibleBy7, " have a neighboring pair one of whose factors is 7."];
   	differences = Differences@following;
   	Print["Minimum gap between those ", Length@following, " primes : ", Min@differences];
   	Print["Median  gap between those ", Length@following, " primes : ", Median@differences];
   	Print["Maximum gap between those ", Length@following, " primes : ", Max@differences];
   ];

SetAttributes[showOutput, Listable];

showOutput[{10^5, 10^6, 10^7}];
Output:
================================================================================
Found 49 primes below 100000 whose preceeding pair are tetraprimes:
 8647	15107	20407	20771	21491	23003	23531	24767	24971	27967
29147	33287	34847	36779	42187	42407	42667	43331	43991	46807
46867	51431	52691	52747	53891	54167	58567	63247	63367	69379
71711	73607	73867	74167	76507	76631	76847	80447	83591	84247
86243	87187	87803	89387	93887	97547	97847	98347	99431	

of which 31 have a neighboring pair one of whose factors is 7.
Minimum gap between those 49 primes : 56
Median  gap between those 49 primes : 1208
Maximum gap between those 49 primes : 6460

Found 46 primes below 100000 whose following pair are tetraprimes:
 8293	16553	17389	18289	22153	26893	29209	33409	35509	36293
39233	39829	40493	41809	45589	48109	58393	59629	59753	59981
60493	60913	64013	64921	65713	66169	69221	71329	74093	75577
75853	77689	77933	79393	79609	82913	84533	85853	87589	87701
88681	91153	93889	96017	97381	98453				

of which 36 have a neighboring pair one of whose factors is 7.
Minimum gap between those 46 primes : 112
Median  gap between those 46 primes : 1460
Maximum gap between those 46 primes : 10284
================================================================================
Found 885 primes below 1000000 whose preceeding pair are tetraprimes,
of which 503 have a neighboring pair one of whose factors is 7.
Minimum gap between those 885 primes : 4
Median  gap between those 885 primes : 756
Maximum gap between those 885 primes : 7712

Found 866 primes below 1000000 whose following pair are tetraprimes,
of which 492 have a neighboring pair one of whose factors is 7.
Minimum gap between those 866 primes : 4
Median  gap between those 866 primes : 832
Maximum gap between those 866 primes : 10284
================================================================================
Found 10815 primes below 10000000 whose preceeding pair are tetraprimes,
of which 5176 have a neighboring pair one of whose factors is 7.
Minimum gap between those 10815 primes : 4
Median  gap between those 10815 primes : 648
Maximum gap between those 10815 primes : 9352

Found 10551 primes below 10000000 whose following pair are tetraprimes,
of which 5069 have a neighboring pair one of whose factors is 7.
Minimum gap between those 10551 primes : 4
Median  gap between those 10551 primes : 660
Maximum gap between those 10551 primes : 10284

Nim

To improve performance, we used int32 instead of int which are 64 bits long on 64 bits platforms. We also avoided to search all the factors by stopping if the number of factors is greater than four or if the same factor occurs more than one time.

import std/[algorithm, bitops, math, strformat, strutils, sugar]

### Sieve of Erathostenes.

type Sieve = object
  data: seq[byte]

func `[]`(sieve: Sieve; idx: Positive): bool =
  ## Return value of element at index "idx".
  let idx = idx shr 1
  let iByte = idx shr 3
  let iBit = idx and 7
  result = sieve.data[iByte].testBit(iBit)

func `[]=`(sieve: var Sieve; idx: Positive; val: bool) =
  ## Set value of element at index "idx".
  let idx = idx shr 1
  let iByte = idx shr 3
  let iBit = idx and 7
  if val: sieve.data[iByte].setBit(iBit)
  else: sieve.data[iByte].clearBit(iBit)

func newSieve(lim: Positive): Sieve =
  ## Create a sieve with given maximal index.
  result.data = newSeq[byte]((lim + 16) shr 4)

func initPrimes(lim: int32): seq[int32] =
  ## Initialize the list of primes from 3 to "lim".
  var composite = newSieve(lim)
  composite[1] = true
  for n in countup(3, sqrt(lim.toFloat).int, 2):
    if not composite[n]:
      for k in countup(n * n, lim, 2 * n):
        composite[k] = true
  for n in countup(3i32, lim, 2):
    if not composite[n]:
      result.add n


### Task functions.

func isTetraPrime(n: int32): bool =
  ## Return true if "n" is a tetraprime.
  var n = n
  if n < 2: return
  const Inc = [4, 2, 4, 2, 4, 6, 2, 6]    # Wheel.
  var count = 0

  if (n and 1) == 0:
    inc count
    n = n shr 1
    if (n and 1) == 0: return
  if n mod 3 == 0:
    inc count
    n = n div 3
    if n mod 3 == 0: return
  if n mod 5 == 0:
    inc count
    n = n div 5
    if n mod 5 == 0: return
  var k = 7i32
  var i = 0
  while k * k <= n:
    if n mod k == 0:
      inc count
      n = n div k
      if count > 4 or n mod k == 0: return
    inc k, Inc[i]
    i = (i + 1) and 7
  if n > 1: inc count
  result = count == 4

func median(a: openArray[int32]): int32 =
  ## Return the median value of "a".
  let m = a.len div 2
  result = if (a.len and 1) == 0: (a[m] + a[m-1]) div 2 else: a[m]


type Position {.pure.} = enum Preceding = "preceding", Following = "following"

proc printResult(list: seq[int32]; count: int; lim: int; pos: Position; display: bool) =
  ## Print the result for the given list and the given count.
  let c = if display: ':' else: '.'
  let lim = insertSep($lim)
  echo &"Found {list.len} primes under {lim} whose {pos} neighboring pair are tetraprimes{c}"
  if display:
    for i, p in list:
      stdout.write &"{p:5}"
      stdout.write if i mod 10 == 9 or i == list.high: '\n' else: ' '
    echo()
  echo &"  Of which {count} have a neighboring pair one of whose factors is 7.\n"
  var gaps = collect(for i in 1..list.high: list[i] - list[i - 1])
  gaps.sort()
  echo &"  Minimum gap between those {list.len} primes: {gaps[0]}"
  echo &"  Median  gap between those {list.len} primes: {gaps.median}"
  echo &"  Maximum gap between those {list.len} primes: {gaps[^1]}"
  echo()


const Steps = [int32 100_000, 1_000_000, 10_000_000]

var list1: seq[int32]  # Prime whose preceding neighboring pair are tetraprimes.
var list2: seq[int32]  # Prime whose following neighboring pair are tetraprimes.
var count1 = 0         # Number of primes from "list1" with one value of the pairs multiple of 7.
var count2 = 0         # Number of primes from "list2" with one value of the pairs multiple of 7.

let primes = initPrimes(Steps[^1])

var limit = Steps[0]
var iLimit = 0
var display = true      # True to display the primes.
var last = primes[^1]

for p in primes:

  if p >= limit or p == last:
    printResult(list1, count1, limit, Preceding, display)
    printResult(list2, count2, limit, Following, display)
    if iLimit == Steps.high: break
    inc iLimit
    limit = Steps[iLimit]
    display = false   # Don't display next primes.

  if isTetraPrime(p - 2) and isTetraPrime(p - 1):
    list1.add p
    if (p - 2) mod 7 in [0, 6]:
      inc count1

  if isTetraPrime(p + 1) and isTetraPrime(p + 2):
    list2.add p
    if (p + 1) mod 7 in [0, 6]:
      inc count2
Output:
Found 49 primes under 100_000 whose preceding neighboring pair are tetraprimes:
 8647 15107 20407 20771 21491 23003 23531 24767 24971 27967
29147 33287 34847 36779 42187 42407 42667 43331 43991 46807
46867 51431 52691 52747 53891 54167 58567 63247 63367 69379
71711 73607 73867 74167 76507 76631 76847 80447 83591 84247
86243 87187 87803 89387 93887 97547 97847 98347 99431

  Of which 31 have a neighboring pair one of whose factors is 7.

  Minimum gap between those 49 primes: 56
  Median  gap between those 49 primes: 1208
  Maximum gap between those 49 primes: 6460

Found 46 primes under 100_000 whose following neighboring pair are tetraprimes:
 8293 16553 17389 18289 22153 26893 29209 33409 35509 36293
39233 39829 40493 41809 45589 48109 58393 59629 59753 59981
60493 60913 64013 64921 65713 66169 69221 71329 74093 75577
75853 77689 77933 79393 79609 82913 84533 85853 87589 87701
88681 91153 93889 96017 97381 98453

  Of which 36 have a neighboring pair one of whose factors is 7.

  Minimum gap between those 46 primes: 112
  Median  gap between those 46 primes: 1460
  Maximum gap between those 46 primes: 10284

Found 885 primes under 1_000_000 whose preceding neighboring pair are tetraprimes.
  Of which 503 have a neighboring pair one of whose factors is 7.

  Minimum gap between those 885 primes: 4
  Median  gap between those 885 primes: 756
  Maximum gap between those 885 primes: 7712

Found 866 primes under 1_000_000 whose following neighboring pair are tetraprimes.
  Of which 492 have a neighboring pair one of whose factors is 7.

  Minimum gap between those 866 primes: 4
  Median  gap between those 866 primes: 832
  Maximum gap between those 866 primes: 10284

Found 10815 primes under 10_000_000 whose preceding neighboring pair are tetraprimes.
  Of which 5176 have a neighboring pair one of whose factors is 7.

  Minimum gap between those 10815 primes: 4
  Median  gap between those 10815 primes: 648
  Maximum gap between those 10815 primes: 9352

Found 10551 primes under 10_000_000 whose following neighboring pair are tetraprimes.
  Of which 5069 have a neighboring pair one of whose factors is 7.

  Minimum gap between those 10551 primes: 4
  Median  gap between those 10551 primes: 660
  Maximum gap between those 10551 primes: 10284

Pascal

Free Pascal

uses Extensible_prime_generator
Generating and bitmarking all tetraprimes up to limit.So no time consuming check has to be done.

program TetraPrimes;
{$IFDEF FPC}{$MODE DELPHI}{$OPTIMIZATION ON,ALL}
   {$CodeAlign proc=1,loop=1} // for Ryzen 5xxx
{$ENDIF}
{$IFDEF Windows}{$APPTYPE CONSOLE}{$ENDIF}
uses
  sysutils,primsieve;
const
  cLimit =1000*1000*1000;  

  MinTriple = 2*3*5; 
  MInQuad =  MinTriple*7;
  cBits2pow = 6; // 2^ 6 = 64-Bit
  cMask = 1 shl cBits2pow-1;

type
  tIdx = 0..1 shl cBits2pow-1;
  tSetBits = set of tIdx; 
  tMyResult = record
               mr_Limit,
               mr_cnt,
               mr_cnt7,
               mr_min,
               mr_median,
               mr_gapsum,
               mr_max  : Uint32;
               mr_dir : boolean;
             end;
var
  MarkTetraPrimes : array of tSetBits;  
  MyPrimes : array of Uint32;
  GapCnt: array[0..14660 shr 2] of Uint32;
  SmallTetraPrimes : array[0..49] of Uint32;
  MyResult : tMyResult;
  MaxPrime,HighMyPrimes,count : Uint32;  
  
procedure GenerateTetraPrimes(Factor:NativeUint;MinIdx,CountOfFactors:Uint32);
var
  fp,
  p : NativeUint;
begin
  dec(CountOfFactors);
  If (CountOfFactors = 0) then 
  begin
    For MinIdx := MinIdx to HighMyPrimes do
    begin
      fp := Factor * MyPrimes[MinIdx];
      if fp > cLimit then
        BREAK;
      inc(count);  
      include(MarkTetraPrimes[fp SHR cBits2pow],fp AND cMask);
    end;
  end
  else
    For MinIdx := MinIdx to HighMyPrimes-CountOfFactors do
    begin
      p := MyPrimes[MinIdx];
      fp :=p*Factor;
      case CountOfFactors of
        2 : p *= p;
        3 : p *= p*p;
      else  
      end;  
      if fp*p < cLimit then
        GenerateTetraPrimes(fp,MinIdx+1,CountOfFactors);
    end;
end;
  
procedure GetTetraPrimes(Limit:Uint32);  
var 
  l,
  p,i : Uint32;  
Begin
  setlength(MarkTetraPrimes, Limit shr cBits2pow);
  //estimate count of primes  
  if limit < 10 then
    setlength(MyPrimes,4)
  else  
    setlength(MyPrimes,round(Limit/(ln(limit)-1.5)));

  InitPrime;
  L :=Limit DIV  MinTriple;
  i := 0;  
  repeat
    p := NextPrime;
    MyPrimes[i] := p;
    inc(i);
  until p > l;  
  HighMyPrimes := i;
  repeat
    p := NextPrime;
    MyPrimes[i] := p;
    inc(i);
  until p > limit;  
  setlength(MyPrimes,i-1);     
  MaxPrime := MyPrimes[HighMyPrimes];
  
  GenerateTetraPrimes(1,0,4);
end;

function TwoInRow(p : NativeUint;dirUp:Boolean = false):boolean;
var
  delta : NativeUint;
begin
  if (p < minquad) then
    EXIT(false);
  delta := ORD(DirUp)*2-1;//= +1,-1  
  if  2*delta+p >cLimit then
    EXIT(false);
  p += delta; 
  if (p AND cMask) in MarkTetraPrimes[p SHR cBits2pow] then
  begin
    p += delta; 
    if (p AND cMask) in MarkTetraPrimes[p SHR cBits2pow] then
      EXIT(true);
  end;
  EXIT(false);    
end;

procedure CheckLimitDirUp(var Res:tMyResult;Limit:NativeUint;dirUp:boolean);
var
  p,Last,GapSum,cnt,cnt7 : UInt32;
  i,d : Int32;
Begin
  FillChar(GapCnt,SizeOf(GapCnt),#0);
  Last := 0;
  cnt := 0;
  cnt7 := 0;
  GapSum := 0;
  if dirUp then
    d := 1
  else  
    d := -1;
    
  for i := 0 to High(myPrimes) do
  begin
    p := MyPrimes[i];
    If p > Limit then
      BREAK;
    if TwoInRow(p,dirUp) then
    Begin
      If Last <> 0 then 
      Begin
        Last := (p-Last) shr 2;
        GapSum+=Last;
        Inc(GapCnt[Last]);
      end;  
      Last := p;  
      if limit <= 100*1000 then
        SmallTetraPrimes[cnt] := p;

      inc(cnt);
      p += d;
      if p MOD 7 = 0 then
        inc(cnt7)
      else
        if (p+d) MOD 7 = 0 then
          inc(cnt7);
    end;      
  end;  
  with res do
  begin
    mr_limit:= Limit;
    mr_cnt := cnt;
    mr_cnt7 := cnt7;
    mr_dir := dirUp;
  end;  
  If cnt > 1 then
  Begin
    For i := 0 to High(GapCnt) do
      IF GapCnt[i] <> 0 then
      begin
        res.mr_min := i shl 2;
        BREAK;
      end; 
    For i := High(GapCnt) downto 0 do
      IF GapCnt[i] <> 0 then
      begin
        res.mr_max := i shl 2;
        BREAK;
      end;       
    //median;
    Limit := cnt DIV 2;
    p := 0;  
    For i := 0 to res.mr_max do
    Begin
      inc(p,GapCnt[i]);
      IF p >= Limit then
      begin
        res.mr_median := i*4;
        BREAK;
      end; 
    end;
    
    res.mr_GapSum := GapSum*4;
  end;  
  if limit <= 100*1000 then  
    writeln;
end;

procedure Out_Res(const res:tMyResult);
const
  Direction : array[Boolean]of string =(' preceded ',' followed '); 
var
  i : integer;  
begin
  with res do
  Begin
    writeln('Primes below ',mr_limit,Direction[mr_dir],' by a tetraprime pair:');
    if mr_cnt < 50 then
    begin
      For i := 0 to mr_cnt-1 do
      Begin
        write(SmallTetraPrimes[i]:7);
        if (i+1) MOD 10 = 0 then
          writeln;
      end;
      writeln;     
    end;
    writeln(#9,'Found ',mr_cnt,' such primes of which ',mr_cnt7,' have 7 as a factor of one of the pair');
    writeln(#9#9'GapCnt between the primes: min: ',mr_min,
            ', average: ',mr_GapSum/(mr_cnt-1):0:1,
            ', median: ',mr_median,
            ', max: ',mr_max);
  end;
end;

procedure CheckLimit(Limit:NativeUint);
const 
  preceded = false;
  followed = true;

var
  myResult :TMyResult;
begin
  CheckLimitDirUp(myResult,Limit,preceded);
  Out_Res(myResult);
  CheckLimitDirUp(myResult,Limit,followed); 
  Out_Res(myResult);
  writeln;  
end;

var 
  i : Uint32;
Begin
  GetTetraPrimes(cLimit);
  GenerateTetraPrimes(1,0,4);
  i := 100000;
  repeat
    CheckLimit(i);    
    i *= 10
  until i >= cLimit;
  CheckLimit(cLimit);
end.
@home ( 5600G @ 4.4 Ghz ):
Primes below 100000 preceded  by a tetraprime pair:
   8647  15107  20407  20771  21491  23003  23531  24767  24971  27967
  29147  33287  34847  36779  42187  42407  42667  43331  43991  46807
  46867  51431  52691  52747  53891  54167  58567  63247  63367  69379
  71711  73607  73867  74167  76507  76631  76847  80447  83591  84247
  86243  87187  87803  89387  93887  97547  97847  98347  99431
	Found 49 such primes of which 31 have 7 as a factor of one of the pair
		GapCnt between the primes: min: 56, average: 1891.3, median: 1180, max: 6460

Primes below 100000 followed  by a tetraprime pair:
   8293  16553  17389  18289  22153  26893  29209  33409  35509  36293
  39233  39829  40493  41809  45589  48109  58393  59629  59753  59981
  60493  60913  64013  64921  65713  66169  69221  71329  74093  75577
  75853  77689  77933  79393  79609  82913  84533  85853  87589  87701
  88681  91153  93889  96017  97381  98453
	Found 46 such primes of which 36 have 7 as a factor of one of the pair
		GapCnt between the primes: min: 112, average: 2003.6, median: 1460, max: 10284


Primes below 1000000 preceded  by a tetraprime pair:
	Found 885 such primes of which 503 have 7 as a factor of one of the pair
		GapCnt between the primes: min: 4, average: 1119.5, median: 756, max: 7712

Primes below 1000000 followed  by a tetraprime pair:
	Found 866 such primes of which 492 have 7 as a factor of one of the pair
		GapCnt between the primes: min: 4, average: 1146.0, median: 832, max: 10284


Primes below 10000000 preceded  by a tetraprime pair:
	Found 10815 such primes of which 5176 have 7 as a factor of one of the pair
		GapCnt between the primes: min: 4, average: 923.9, median: 648, max: 9352

Primes below 10000000 followed  by a tetraprime pair:
	Found 10551 such primes of which 5069 have 7 as a factor of one of the pair
		GapCnt between the primes: min: 4, average: 947.0, median: 660, max: 10284
//real    0m0,033s

Primes below 100000000 preceded  by a tetraprime pair:
	Found 110865 such primes of which 47197 have 7 as a factor of one of the pair
		GapCnt between the primes: min: 4, average: 901.9, median: 632, max: 11892

Primes below 100000000 followed  by a tetraprime pair:
	Found 110192 such primes of which 47308 have 7 as a factor of one of the pair
		GapCnt between the primes: min: 4, average: 907.4, median: 640, max: 11000
//real    0m0,458s

Primes below 1000000000 preceded  by a tetraprime pair:
	Found 1081567 such primes of which 423195 have 7 as a factor of one of the pair
		GapCnt between the primes: min: 4, average: 924.6, median: 648, max: 14660
Primes below 1000000000 followed  by a tetraprime pair:
	Found 1081501 such primes of which 423572 have 7 as a factor of one of the pair
		GapCnt between the primes: min: 4, average: 924.6, median: 648, max: 12100

real    0m10,578s

Phix

constant primes = get_primes_le(1e7)
sequence tetras = {{},{}},
         sevens = {0,0},
          highs = {1e5,1e6,1e7},
         highdx = apply(true,binary_search,{highs,{primes}}),
        highest = extract(primes,sq_sub(sq_abs(highdx),1))
integer hdx = 1
for p in primes from 2 do
    -- for all odd primes, both p-1 and p+1 are divisible by 2.
    -- one of them will be divisible by 4 and hence not a tetraprime.
    integer d = odd((p-1)/2),
           dx = iff(d?-1:+1)
    sequence f3 = prime_powers((p+dx)/2)
    if length(f3)=3 and vslice(f3,2)={1,1,1} then
        sequence f4 = prime_powers(p+2*dx)
        if length(f4)=4 and vslice(f4,2)={1,1,1,1} then
            tetras[2-d] &= p
            if find(7,vslice(f3,1)) 
            or find(7,vslice(f4,1)) then
                sevens[2-d] += 1
            end if
        end if
    end if
    if p=highest[hdx] then
        for t,ti in tetras do
            integer c = length(ti) 
            printf(1,"Found %,d primes under %,d whose %sing neighboring pair are tetraprimes%s\n",
                     {c, highs[hdx], {"preced","follow"}[t],iff(hdx=1?":":"")})
            if hdx=1 then printf(1,"%s\n",{join_by(ti,1,10,fmt:="%5d")}) end if
            printf(1,"of which %,d have a neighboring pair one of whose factors is 7.\n\n",sevens[t])
            sequence gaps = sort(sq_sub(ti[2..-1],ti[1..-2]))
            printf(1,"Minimum gap between those %,d primes : %,d\n",{c,gaps[1]})
--          printf(1,"Average gap between those %,d primes : %,d\n",{c,average(gaps)})
            printf(1,"Median  gap between those %,d primes : %,d\n",{c,median(gaps)})
            printf(1,"Maximum gap between those %,d primes : %,d\n\n",{c,gaps[$]})
        end for
        hdx += 1
    end if
end for
Output:

Same as Wren

Raku

Translation of: Wren
# 20230721 Raku programming solution

my @primes = (2..1e7).grep: *.is-prime; # cannot do lazy here 

sub median { # based on https://rosettacode.org/wiki/Averages/Median#Raku
   return { ( .[(*-1) div 2] + .[* div 2] ) / 2 }(@_) # for already sorted
}

sub isTetraPrime ($n is copy) { # is cached {
   my ($count,$prevFact) = 0, 1;
   for @primes -> \p {
      my $limit = p * p;
      if $count == 0 {
         $limit = $limit * $limit
      } elsif $count == 1 {
         $limit *= p
      }
      if $limit <= $n {
         while $n %% p {
            return False if ( $count == 4 or p == $prevFact );
            $count++;
            $n div= p;
            $prevFact = p
         }
      } else {
         last      
      }
   }
   if $n > 1 {
      return False if ( $count == 4 or $n == $prevFact );
      $count++
   }
   return $count == 4
}

my ( $j, @tetras1, @tetras2, $sevens1, $sevens2 ) = 1e5;

my \highest7 = @primes.[*-1];
my \highest6 = @primes.first: * < 1e6, :end;
my \highest5 = @primes.first: * < 1e5, :end; 

for @primes -> \p {
   if isTetraPrime p-1 and isTetraPrime p-2 {
      @tetras1.push: p;
      $sevens1++ if ( (p-1) %% 7 or (p-2) %% 7 );
   }
   if isTetraPrime p+1 and isTetraPrime p+2 {
      @tetras2.push: p;
      $sevens2++ if ( (p+1) %% 7 or (p+2) %% 7 ); 
   }
   if p == highest5 | highest6 | highest7 {
      for 0,1 -> \i {
         my (\sevens, \t, @tetras) := i == 0 
            ?? ( $sevens1, "preceding", @tetras1 )
            !! ( $sevens2, "following", @tetras2 ); 
         my \c = @tetras.elems;

         say "Found {c} primes under $j whose {t} neighboring pair are tetraprimes:";
         if p == highest5 {
            say [~] $_>>.fmt('%6s') for @tetras.rotor(10,:partial);       
         }
         say "of which {sevens} have a neighboring pair one of whose factors is 7.\n";
         my \gaps = ( @tetras.rotor(2=>-1).map: { .[1] - .[0] } ).sort;
         
         my (\Min,\Max,\Med) = gaps[0], gaps[*-1], median(gaps);
         say "Minimum gap between those {c} primes : {Min}";
         say "Median  gap between those {c} primes : {Med}";
         say "Maximum gap between those {c} primes : {Max}"; 
         say()
      }
      $j *= 10
   } 
}
Output:

Same as Wren

Sidef

func display(arr, p, f, g, type, limit, display_primes) {

    var s = arr.map(f).grep{.is_prime}
    print "Found #{s.len.commify} primes under #{limit.commify} whose #{type} neighboring pair are tetraprimes"

    if (display_primes) {
        say ':'
        s.slices(10).each{.map { "%#{limit.len+1}s" % _ }.join.say }
    }

    with (p) {|p|
        var c = s.count {|a| is_div(g(a), p) || is_div(g(g(a)), p) }
        say "\nof which #{c.commify} have a neighboring pair one of whose factors is #{p}.\n"
    }

    var D = s.diffs

    func median(a) {
        var l = a.len
        var j = l>>1
        l.is_even ? ((a[j-1] + a[j]) >> 1) : a[j]
    }

    say("Minimum gap between those #{s.len.commify} primes: ", D.min)
    say("Median  gap between those #{s.len.commify} primes: ", median(D.sort))
    say("Maximum gap between those #{s.len.commify} primes: ", D.max)
    say ''
}

for limit in (1e5, 1e6, 1e7) {
    var arr = 4.squarefree_almost_primes(limit).cons(2).grep_2d{|a,b| b-a == 1 }
    display(arr, 7, {.last.inc},  {.dec}, "preceding", limit, limit <= 1e5)
    display(arr, 7, {.first.dec}, {.inc}, "following", limit, limit <= 1e5)
}
Output:
Found 49 primes under 100,000 whose preceding neighboring pair are tetraprimes:
   8647  15107  20407  20771  21491  23003  23531  24767  24971  27967
  29147  33287  34847  36779  42187  42407  42667  43331  43991  46807
  46867  51431  52691  52747  53891  54167  58567  63247  63367  69379
  71711  73607  73867  74167  76507  76631  76847  80447  83591  84247
  86243  87187  87803  89387  93887  97547  97847  98347  99431

of which 31 have a neighboring pair one of whose factors is 7.

Minimum gap between those 49 primes: 56
Median  gap between those 49 primes: 1208
Maximum gap between those 49 primes: 6460

Found 46 primes under 100,000 whose following neighboring pair are tetraprimes:
   8293  16553  17389  18289  22153  26893  29209  33409  35509  36293
  39233  39829  40493  41809  45589  48109  58393  59629  59753  59981
  60493  60913  64013  64921  65713  66169  69221  71329  74093  75577
  75853  77689  77933  79393  79609  82913  84533  85853  87589  87701
  88681  91153  93889  96017  97381  98453

of which 36 have a neighboring pair one of whose factors is 7.

Minimum gap between those 46 primes: 112
Median  gap between those 46 primes: 1460
Maximum gap between those 46 primes: 10284

Found 885 primes under 1,000,000 whose preceding neighboring pair are tetraprimes
of which 503 have a neighboring pair one of whose factors is 7.

Minimum gap between those 885 primes: 4
Median  gap between those 885 primes: 756
Maximum gap between those 885 primes: 7712

Found 866 primes under 1,000,000 whose following neighboring pair are tetraprimes
of which 492 have a neighboring pair one of whose factors is 7.

Minimum gap between those 866 primes: 4
Median  gap between those 866 primes: 832
Maximum gap between those 866 primes: 10284

Found 10,815 primes under 10,000,000 whose preceding neighboring pair are tetraprimes
of which 5,176 have a neighboring pair one of whose factors is 7.

Minimum gap between those 10,815 primes: 4
Median  gap between those 10,815 primes: 648
Maximum gap between those 10,815 primes: 9352

Found 10,551 primes under 10,000,000 whose following neighboring pair are tetraprimes
of which 5,069 have a neighboring pair one of whose factors is 7.

Minimum gap between those 10,551 primes: 4
Median  gap between those 10,551 primes: 660
Maximum gap between those 10,551 primes: 10284

Wren

Library: Wren-math
Library: Wren-sort
Library: Wren-fmt
import "./math" for Int, Nums
import "./sort" for Find
import "./fmt" for Fmt

var primes = Int.primeSieve(1e7)

var isTetraPrime = Fn.new { |n|
    var count = 0
    var prevFact = 1
    for (p in primes) {
        var limit = p * p
        if (count == 0) {
            limit = limit * limit
        } else if (count == 1) {
            limit = limit * p
        }
        if (limit <= n) {
            while (n % p == 0) {
                if (count == 4 || p == prevFact) return false
                count = count + 1
                n = (n/p).floor
                prevFact = p
            }
        } else {
            break
        }
    }
    if (n > 1) {
        if (count == 4 || n == prevFact) return false
        count = count + 1
    }
    return count == 4
}

var highest5 = primes[Find.nearest(primes, 1e5) - 1]
var highest6 = primes[Find.nearest(primes, 1e6) - 1]
var highest7 = primes[-1]
var tetras1 = []
var tetras2 = []
var sevens1 = 0
var sevens2 = 0
var j = 1e5
for (p in primes) {
    // process even numbers first as likely to have most factors
    if (isTetraPrime.call(p-1) && isTetraPrime.call(p-2)) {
        tetras1.add(p)
        if ((p-1)%7 == 0 || (p-2)%7 == 0) sevens1 = sevens1 + 1
    }

    if (isTetraPrime.call(p+1) && isTetraPrime.call(p+2)) {
        tetras2.add(p)
        if ((p+1)%7 == 0 || (p+2)%7 == 0) sevens2 = sevens2 + 1
    }

    if (p == highest5 || p == highest6 || p == highest7) {
        for (i in 0..1) {
            var tetras = (i == 0) ? tetras1 : tetras2
            var sevens = (i == 0) ? sevens1 : sevens2
            var c = tetras.count
            var t = (i == 0) ? "preceding" : "following"
            Fmt.write("Found $,d primes under $,d whose $s neighboring pair are tetraprimes", c, j, t)
            if (p == highest5) {
                Fmt.print(":")
                Fmt.tprint("$5d ", tetras, 10)
            }
            Fmt.print("\nof which $,d have a neighboring pair one of whose factors is 7.\n", sevens)
            var gaps = List.filled(c-1, 0)
            for (k in 0...c-1) gaps[k] = tetras[k+1] - tetras[k]
            gaps.sort()
            var min = gaps[0]
            var max = gaps[-1]
            var med = Nums.median(gaps)
            Fmt.print("Minimum gap between those $,d primes : $,d", c, min)
            Fmt.print("Median  gap between those $,d primes : $,d", c, med)
            Fmt.print("Maximum gap between those $,d primes : $,d", c, max)
            Fmt.print()
        }
        j = j * 10
    }
}
Output:
Found 49 primes under 100,000 whose preceding neighboring pair are tetraprimes:
 8647  15107  20407  20771  21491  23003  23531  24767  24971  27967 
29147  33287  34847  36779  42187  42407  42667  43331  43991  46807 
46867  51431  52691  52747  53891  54167  58567  63247  63367  69379 
71711  73607  73867  74167  76507  76631  76847  80447  83591  84247 
86243  87187  87803  89387  93887  97547  97847  98347  99431 

of which 31 have a neighboring pair one of whose factors is 7.

Minimum gap between those 49 primes : 56
Median  gap between those 49 primes : 1,208
Maximum gap between those 49 primes : 6,460

Found 46 primes under 100,000 whose following neighboring pair are tetraprimes:
 8293  16553  17389  18289  22153  26893  29209  33409  35509  36293 
39233  39829  40493  41809  45589  48109  58393  59629  59753  59981 
60493  60913  64013  64921  65713  66169  69221  71329  74093  75577 
75853  77689  77933  79393  79609  82913  84533  85853  87589  87701 
88681  91153  93889  96017  97381  98453 

of which 36 have a neighboring pair one of whose factors is 7.

Minimum gap between those 46 primes : 112
Median  gap between those 46 primes : 1,460
Maximum gap between those 46 primes : 10,284

Found 885 primes under 1,000,000 whose preceding neighboring pair are tetraprimes
of which 503 have a neighboring pair one of whose factors is 7.

Minimum gap between those 885 primes : 4
Median  gap between those 885 primes : 756
Maximum gap between those 885 primes : 7,712

Found 866 primes under 1,000,000 whose following neighboring pair are tetraprimes
of which 492 have a neighboring pair one of whose factors is 7.

Minimum gap between those 866 primes : 4
Median  gap between those 866 primes : 832
Maximum gap between those 866 primes : 10,284

Found 10,815 primes under 10,000,000 whose preceding neighboring pair are tetraprimes
of which 5,176 have a neighboring pair one of whose factors is 7.

Minimum gap between those 10,815 primes : 4
Median  gap between those 10,815 primes : 648
Maximum gap between those 10,815 primes : 9,352

Found 10,551 primes under 10,000,000 whose following neighboring pair are tetraprimes
of which 5,069 have a neighboring pair one of whose factors is 7.

Minimum gap between those 10,551 primes : 4
Median  gap between those 10,551 primes : 660
Maximum gap between those 10,551 primes : 10,284

XPL0

Works on Raspberry Pi.

include xpllib;         \for IsPrime, Sort, and Print

func Median(A, Len);    \Return median value of (sorted) array A
int  A, Len, M;
[M:= Len/2;
return if rem(0) then A(M) else (A(M-1) + A(M)) / 2;
];

int Have7;              \Boolean: a tetraprime factor is 7

func IsTetraprime(N);   \Return 'true' if N is a tetraprime
int  N;
int  Div, Count, Distinct;
[Div:= 2;  Count:= 0;
while N >= Div*Div do
    [Distinct:= true;
    while rem(N/Div) = 0 do
        [if not Distinct then return false;
        Distinct:= false;
        Count:= Count+1;
        if Div = 7 then Have7:= true;
        N:= N/Div;
        ];
    Div:= Div+1;
    ];
if N > 1 then Count:= Count+1;
return Count = 4;
];

int Sign, TenPower, TP, Case, N, N0, Count, Count7, Gaps;
[Sign:= -1;  TenPower:= 100_000;
for TP:= 5 to 7 do
    [for Case:= 1 to 2 do       \preceding or following neighboring pairs
        [Count:= 0;  Count7:= 0;  N0:= 0;  Gaps:= 0;
        if TP = 5 then CrLf(0); \100_000
        for N:= 3 to TenPower-1 do
            [if IsPrime(N) then
                [Have7:= false;
                if IsTetraprime(N+1*Sign) then
                    if IsTetraprime(N+2*Sign) then
                        [Count:= Count+1;
                        if TP = 5 then
                            [Print("%7d", N);
                            if rem(Count/10) = 0 then CrLf(0);
                            ];
                        if Have7 then Count7:= Count7+1;
                        if N0 # 0 then
                            [Gaps:= ReallocMem(Gaps, Count*4);  \4 = SizeOfInt
                            Gaps(Count-2):= N - N0;
                            ];
                        N0:= N;
                        ];
                ];
            N:= N+1;
            ];
        Sort(Gaps, Count-1);
        Print("\nFound %,d primes under %,d whose neighboring pair are tetraprimes\n",
            Count, TenPower);
        Print("of which %,d have a neighboring pair, one of whose factors is 7.\n\n",
            Count7);
        Print("Minimum gap between %,d primes : %,d\n", Count, Gaps(0));
        Print("Median  gap between %,d primes : %,d\n", Count, Median(Gaps, Count-1));
        Print("Maximum gap between %,d primes : %,d\n", Count, Gaps(Count-2));
        Sign:= Sign * -1;
        ];
    TenPower:= TenPower * 10;
    ];
]
Output:

   8647  15107  20407  20771  21491  23003  23531  24767  24971  27967
  29147  33287  34847  36779  42187  42407  42667  43331  43991  46807
  46867  51431  52691  52747  53891  54167  58567  63247  63367  69379
  71711  73607  73867  74167  76507  76631  76847  80447  83591  84247
  86243  87187  87803  89387  93887  97547  97847  98347  99431
Found 49 primes under 100,000 whose neighboring pair are tetraprimes
of which 31 have a neighboring pair, one of whose factors is 7.

Minimum gap between 49 primes : 56
Median  gap between 49 primes : 1,208
Maximum gap between 49 primes : 6,460

   8293  16553  17389  18289  22153  26893  29209  33409  35509  36293
  39233  39829  40493  41809  45589  48109  58393  59629  59753  59981
  60493  60913  64013  64921  65713  66169  69221  71329  74093  75577
  75853  77689  77933  79393  79609  82913  84533  85853  87589  87701
  88681  91153  93889  96017  97381  98453
Found 46 primes under 100,000 whose neighboring pair are tetraprimes
of which 36 have a neighboring pair, one of whose factors is 7.

Minimum gap between 46 primes : 112
Median  gap between 46 primes : 1,460
Maximum gap between 46 primes : 10,284

Found 885 primes under 1,000,000 whose neighboring pair are tetraprimes
of which 503 have a neighboring pair, one of whose factors is 7.

Minimum gap between 885 primes : 4
Median  gap between 885 primes : 756
Maximum gap between 885 primes : 7,712

Found 866 primes under 1,000,000 whose neighboring pair are tetraprimes
of which 492 have a neighboring pair, one of whose factors is 7.

Minimum gap between 866 primes : 4
Median  gap between 866 primes : 832
Maximum gap between 866 primes : 10,284

Found 10,815 primes under 10,000,000 whose neighboring pair are tetraprimes
of which 5,176 have a neighboring pair, one of whose factors is 7.

Minimum gap between 10,815 primes : 4
Median  gap between 10,815 primes : 648
Maximum gap between 10,815 primes : 9,352

Found 10,551 primes under 10,000,000 whose neighboring pair are tetraprimes
of which 5,069 have a neighboring pair, one of whose factors is 7.

Minimum gap between 10,551 primes : 4
Median  gap between 10,551 primes : 660
Maximum gap between 10,551 primes : 10,284
Cookies help us deliver our services. By using our services, you agree to our use of cookies.