Sexy primes: Difference between revisions

124,714 bytes added ,  1 month ago
Added BASIC256 and Yabasic. Moved FreeBASIC to section BASIC
(Update task requirments)
(Added BASIC256 and Yabasic. Moved FreeBASIC to section BASIC)
 
(160 intermediate revisions by 36 users not shown)
Line 1:
{{draft task|Prime Numbers}}
{{Wikipedia|Sexy_prime}}
 
Line 5:
In mathematics, '''sexy primes''' are prime numbers that differ from each other by six.
 
For example, the numbers '''5''' and '''11''' are both sexy primes, because '''11''' minus '''56''' is '''65'''.
 
The term "sexy prime" is a pun stemming from the Latin word for six: ''sex''.<br><br>
Line 23:
 
::*For each of pairs, triplets, quadruplets and quintuplets, Find and display the count of each group type of sexy primes less than one million thirty-five ('''1,000,035''').
::*Display at most the '''last''' '''5''' (or all if there are fewer), less than one million thirty-five, of each sexy prime group type.
::*Find and display the count of the unsexy primes less than one million thirty-five.
::*Find and display the '''last 10''' unsexy primes less than one million thirty-five.<br><br>
::*Note that 1000033 '''SHOULD NOT''' be counted in the pair count. It is sexy, but not in a pair within the limit. However, it also '''SHOULD NOT''' be listed in the unsexy primes since it is sexy.
<br><br>
 
=={{header|11l}}==
{{alertbox|pink|Note: the task requirements have changed for reasons found on the discussion page. Please update tasks to meet the updated requirements.}}
{{trans|Python}}
 
<syntaxhighlight lang="11l">V LIMIT = 1'000'000
F get_primes(limit)
V is_prime = [0B] * 2 [+] [1B] * (limit - 1)
L(n) 0 .< Int(limit ^ 0.5 + 1.5)
I is_prime[n]
L(i) (n * n .< limit + 1).step(n)
is_prime[i] = 0B
R enumerate(is_prime).filter((i, prime) -> prime).map((i, prime) -> i)
 
V primes = get_primes(LIMIT)
V primeset = Set(primes)
 
V s = [[[Int]]()] * 4
[Int] unsexy
L(p) primes
I p + 6 C primeset
s[0].append([p, p + 6])
E
I p - 6 !C primeset
unsexy.append(p)
L.continue
I p + 12 C primeset
s[1].append([p, p + 6, p + 12])
E
L.continue
I p + 18 C primeset
s[2].append([p, p + 6, p + 12, p + 18])
E
L.continue
I p + 24 C primeset
s[3].append([p, p + 6, p + 12, p + 18, p + 24])
 
print(‘"SEXY" PRIME GROUPINGS:’)
L(sexy, name) zip(s, ‘pairs triplets quadruplets quintuplets’.split(‘ ’))
print(‘ #. #. ending with ...’.format(sexy.len, name))
L(sx) sexy[(len)-5..]
print(‘ ’sx)
 
print("\nThere are #. unsexy primes ending with ...".format(unsexy.len))
L(usx) unsexy[(len)-10..]
print(‘ ’usx)</syntaxhighlight>
 
{{out}}
<pre>
"SEXY" PRIME GROUPINGS:
16386 pairs ending with ...
[999371, 999377]
[999431, 999437]
[999721, 999727]
[999763, 999769]
[999953, 999959]
2900 triplets ending with ...
[997427, 997433, 997439]
[997541, 997547, 997553]
[998071, 998077, 998083]
[998617, 998623, 998629]
[998737, 998743, 998749]
325 quadruplets ending with ...
[977351, 977357, 977363, 977369]
[983771, 983777, 983783, 983789]
[986131, 986137, 986143, 986149]
[990371, 990377, 990383, 990389]
[997091, 997097, 997103, 997109]
1 quintuplets ending with ...
[5, 11, 17, 23, 29]
 
There are 48626 unsexy primes ending with ...
999809
999853
999863
999883
999907
999917
999931
999961
999979
999983
</pre>
 
=={{header|ALGOL W}}==
<syntaxhighlight lang="algolw">begin
% find some sexy primes - primes that differ from another prime by 6 %
% implements the sieve of Eratosthenes %
procedure sieve( logical array s ( * ); integer value n ) ;
begin
% start with everything flagged as prime %
for i := 1 until n do s( i ) := true;
% sieve out the non-primes %
s( 1 ) := false;
for i := 2 until truncate( sqrt( n ) ) do begin
if s( i ) then for p := i * i step i until n do s( p ) := false
end for_i ;
end sieve ;
% adds a prime to list of sexy/unsexy primes %
procedure addPrime ( integer value p
; integer array list ( * )
; integer value len
) ;
begin
% increment count, shuffle down the primes and add the new one %
list( 0 ) := list( 0 ) + 1;
for i := 1 until len - 1 do list( i ) := list( i + 1 );
list( len ) := p
end addPrime ;
% counts the number of pairs of sexy primes, triplets, quadruplest and %
% quintuplets up to n %
% the counts of each kind are returned in the 0 element of the arrays %
% the last 5 ( or less if there are less than 5 ) of each type of sexy %
% prime is returned in the array elements 1 to 5 %
procedure countSexyPrimes ( logical array s ( * )
; integer value n
; integer array pairs, triplets, quadruplets, quintuplets ( * )
) ;
begin
integer pos2, pos3, pos4, pos5;
for i := 0 until 5 do pairs( i ) := triplets( i ) := quadruplets( i ) := quintuplets( i ) := 0;
% look for pairs etc. up to n %
% 2 cannot be a sexy prime as it is the only even prime, thus: %
% pairs can start at 7, triplets at 13, quadruplets at 19 and %
% quintuplets at 25 %
for p := 7 step 2 until 11 do begin
if s( p ) and s( p - 6 ) then addPrime( p, pairs, 5 )
end for_p ;
for p := 13 step 2 until 17 do begin
if s( p ) and s( p - 6 ) then addPrime( p, pairs, 5 );
if s( p ) and s( p - 6 ) and s( p - 12 ) then addPrime( p, triplets, 5 )
end for_p ;
for p := 19 step 2 until 23 do begin
if s( p ) and s( p - 6 ) then addPrime( p, pairs, 5 );
if s( p ) and s( p - 6 ) and s( p - 12 ) then addPrime( p, triplets, 5 );
if s( p ) and s( p - 6 ) and s( p - 12 ) and s( p - 18 )
then addPrime( p, quadruplets, 5 )
end for_p ;
pos5 := 1;
pos4 := pos5 + 6;
pos3 := pos4 + 6;
pos2 := pos3 + 6;
for p := pos2 + 6 step 2 until n do begin
if s( p ) then begin
if s( pos2 ) then begin % sexy pair %
addPrime( p, pairs, 5 );
if s( pos3 ) then begin % sexy triplet %
addPrime( p, triplets, 5 );
if s( pos4 ) then begin % sexy quadruplet %
addPrime( p, quadruplets, 5 );
if s( pos5 ) then begin % sexy quintuplet %
addPrime( p, quintuplets, 5 )
end if_s_pos5
end if_s_pos4
end if_s_pos3
end if_s_pos2
end if_s_p ;
pos2 := pos2 + 2;
pos3 := pos3 + 2;
pos4 := pos4 + 2;
pos5 := pos5 + 2
end for_p
end countSexyPrimes ;
% counts the number of unsexy primes up to n %
% the count is returned in the 0 element of the array %
% the last 5 ( or less if there are less than 5 ) unsexy prime is %
% returned in the array elements 1 to 10 %
procedure countUnsexyPrimes ( logical array s ( * )
; integer value n
; integer array unsexy ( * )
) ;
begin
for i := 0 until 10 do unsexy( i ) := 0;
for p := 2, 3, 5 do begin % handle primes below 7 separately %
if s( p ) and not s( p + 6 ) then addPrime( p, unsexy, 10 )
end for_p ;
for p := 7 step 2 until n do begin
if s( p ) and not s( p - 6 ) and not s( p + 6 ) then addPrime( p, unsexy, 10 )
end for_p
end countUnsexyPrimes ;
% shows sexy prime pairs %
procedure showPrimes ( integer value elements
; integer array primes ( * )
; integer value arrayMax
; string(24) value title
; integer value maxPrime
) ;
begin
write( i_w := 8, s_w := 0, "Found ", primes( 0 ), " ", title, " below ", maxPrime + 1
, i_w := 2, "; last ", ( if primes( 0 ) > arrayMax then arrayMax else primes( 0 ) ), ":"
);
write( i_w := 1, s_w := 0, " " );
for p := 1 until arrayMax do begin
if primes( p ) not = 0 then begin
integer pn;
if elements > 1 then writeon( "(" );
pn := primes( p ) - ( ( elements - 1 ) * 6 );
for i := 1 until elements do begin
writeon( i_w := 1, s_w := 0, " ", pn );
pn := pn + 6
end for_i ;
if elements > 1 then writeon( " ) " );
end if_primes_p_ne_0
end for_p
end showPrimes ;
integer MAX_SEXY, MAX_PRIME;
% for the task, we need to consider primes up to 1 000 035 %
% however we must still recognise sexy primes up that limit, so we sieve %
% up to 1 000 035 + 6 %
MAX_SEXY := 1000000 + 35;
MAX_PRIME := MAX_SEXY + 6;
begin
logical array s ( 1 :: MAX_PRIME );
integer array pairs, triplets, quadruplets, quintuplets ( 0 :: 5 );
integer array unsexy ( 0 :: 10 );
sieve( s, MAX_PRIME );
countSexyPrimes( s, MAX_SEXY, pairs, triplets, quadruplets, quintuplets );
countUnsexyPrimes( s, MAX_SEXY, unsexy );
showPrimes( 2, pairs, 5, "sexy prime pairs", MAX_SEXY );
showPrimes( 3, triplets, 5, "sexy prime triplets", MAX_SEXY );
showPrimes( 4, quadruplets, 5, "sexy prime quadruplets", MAX_SEXY );
showPrimes( 5, quintuplets, 5, "sexy prime quintuplets", MAX_SEXY );
showPrimes( 1, unsexy, 10, "unsexy primes", MAX_SEXY )
end
end.</syntaxhighlight>
{{out}}
<pre>
Found 16386 sexy prime pairs below 1000036; last 5:
( 999371 999377 ) ( 999431 999437 ) ( 999721 999727 ) ( 999763 999769 ) ( 999953 999959 )
Found 2900 sexy prime triplets below 1000036; last 5:
( 997427 997433 997439 ) ( 997541 997547 997553 ) ( 998071 998077 998083 ) ( 998617 998623 998629 ) ( 998737 998743 998749 )
Found 325 sexy prime quadruplets below 1000036; last 5:
( 977351 977357 977363 977369 ) ( 983771 983777 983783 983789 ) ( 986131 986137 986143 986149 ) ( 990371 990377 990383 990389 ) ( 997091 997097 997103 997109 )
Found 1 sexy prime quintuplets below 1000036; last 1:
( 5 11 17 23 29 )
Found 48627 unsexy primes below 1000036; last 10:
999853 999863 999883 999907 999917 999931 999961 999979 999983 1000003
</pre>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f SEXY_PRIMES.AWK
BEGIN {
cutoff = 1000034
for (i=1; i<=cutoff; i++) {
n1 = i
if (is_prime(n1)) {
total_primes++
if ((n2 = n1 + 6) > cutoff) { continue }
if (is_prime(n2)) {
save(2,5,n1 FS n2)
if ((n3 = n2 + 6) > cutoff) { continue }
if (is_prime(n3)) {
save(3,5,n1 FS n2 FS n3)
if ((n4 = n3 + 6) > cutoff) { continue }
if (is_prime(n4)) {
save(4,5,n1 FS n2 FS n3 FS n4)
if ((n5 = n4 + 6) > cutoff) { continue }
if (is_prime(n5)) {
save(5,5,n1 FS n2 FS n3 FS n4 FS n5)
}
}
}
}
if ((s[2] s[3] s[4] s[5]) !~ (n1 "")) { # check for unsexy
save(1,10,n1)
}
}
}
printf("%d primes less than %s\n\n",total_primes,cutoff+1)
printf("%d unsexy primes\n%s\n\n",c[1],s[1])
printf("%d sexy prime pairs\n%s\n\n",c[2],s[2])
printf("%d sexy prime triplets\n%s\n\n",c[3],s[3])
printf("%d sexy prime quadruplets\n%s\n\n",c[4],s[4])
printf("%d sexy prime quintuplets\n%s\n\n",c[5],s[5])
exit(0)
}
function is_prime(x, i) {
if (x <= 1) {
return(0)
}
for (i=2; i<=int(sqrt(x)); i++) {
if (x % i == 0) {
return(0)
}
}
return(1)
}
function save(key,nbr_to_keep,str) {
c[key]++
str = s[key] str ", "
if (gsub(/,/,"&",str) > nbr_to_keep) {
str = substr(str,index(str,",")+2)
}
s[key] = str
}
</syntaxhighlight>
{{out}}
<pre>
78500 primes less than 1000035
 
48627 unsexy primes
999853, 999863, 999883, 999907, 999917, 999931, 999961, 999979, 999983, 1000003,
 
16386 sexy prime pairs
999371 999377, 999431 999437, 999721 999727, 999763 999769, 999953 999959,
 
2900 sexy prime triplets
997427 997433 997439, 997541 997547 997553, 998071 998077 998083, 998617 998623 998629, 998737 998743 998749,
 
325 sexy prime quadruplets
977351 977357 977363 977369, 983771 983777 983783 983789, 986131 986137 986143 986149, 990371 990377 990383 990389, 997091 997097 997103 997109,
 
1 sexy prime quintuplets
5 11 17 23 29,
</pre>
 
=={{header|BASIC}}==
==={{header|BASIC256}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="vbnet">include "isprime.kbs"
 
maxi = 1000035
cu = 0
c2 = 0
c3 = 0
c4 = 0
c5 = 0
#, n, i,
p = 0
dim unsexy(10)
dim pairs(5)
dim trips(5)
dim quads(5)
dim quins(5)
 
for n = maxi to 2 step -1
if isPrime(n) then
p += 1
if not isPrime(n-6) and not isPrime(n+6) then
if cu < 10 then unsexy[cu] = n
cu += 1
end if
if isPrime(n-6) then
if c2 < 5 then pairs[c2] = n
c2 += 1
if isPrime(n-12) then
if c3 < 5 then trips[c3] = n
c3 += 1
if isPrime(n-18) then
if c4 < 5 then quads[c4] = n
c4 += 1
if isPrime(n-24) then
if c5 < 5 then quins[c5] = n
c5 += 1
end if
end if
end if
end if
end if
next n
 
print p; " primes less than "; maxi
 
print chr(10); c2; " pairs ending with:"
for i = 4 to 0 step -1
print " ["; pairs[i]-6; ", "; pairs[i]; "]"
next i
 
print chr(10); c3; " triplets ending with:"
for i = 4 to 0 step -1
print " ["; trips[i]-12; ", "; trips[i]-6; ", "& trips[i]; "]"
next i
 
print chr(10); c4; " quadruplets ending with:"
for i = 4 to 0 step -1
print " ["; quads[i]-18; ", "; quads[i]-12; ", "; quads[i]-6; ", "; quads[i]; "]"
next i
 
print chr(10); c5; " quintuplet(s) ending with:"
if c5 > 5 then i = 5 else i = c5
for i = i-1 to 0 step -1
print " ["; quins[i]-24; ", "& quins[i]-18; ", "& quins[i]-12; ", "& quins[i]-6; ", "& quins[i]; "]"
next i
 
print chr(10); cu; " unsexy primes ending with:"
for i = 9 to 0 step -1
print unsexy[i]; ",";
next i
end</syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
 
 
==={{header|FreeBASIC}}===
<syntaxhighlight lang="vbnet">#include "isprime.bas"
 
#define maxi 1000035
Dim As Integer CU = 0, C2 = 0, C3 = 0, C4 = 0, C5 = 0, N, I, P = 0
Dim As Integer Unsexy(10), Pairs(5), Trips(5), Quads(5), Quins(5)
 
For N = maxi To 2 Step -1
If isPrime(N) Then
P += 1
If Not isPrime(N-6) And Not isPrime(N+6) Then
If CU < 10 Then Unsexy(CU) = N
CU += 1
End If
If isPrime(N-6) Then
If C2 < 5 Then Pairs(C2) = N
C2 += 1
If isPrime(N-12) Then
If C3 < 5 Then Trips(C3) = N
C3 += 1
If isPrime(N-18) Then
If C4 < 5 Then Quads(C4) = N
C4 += 1
If isPrime(N-24) Then
If C5 < 5 Then Quins(C5) = N
C5 += 1
End If
End If
End If
End If
End If
Next N
 
Print P; " primes less than"; maxi
 
Print Chr(10); C2; " pairs ending with:"
For I = 4 To 0 Step -1
Print " [" & Pairs(I)-6 & ", "& Pairs(I) & "]"
Next I
 
Print Chr(10); C3; " triplets ending with:"
For I = 4 To 0 Step -1
Print " [" & Trips(I)-12 & ", "& Trips(I)-6 & ", "& Trips(I) & "]"
Next I
 
Print Chr(10); C4; " quadruplets ending with:"
For I = 4 To 0 Step -1
Print " [" & Quads(I)-18 & ", "& Quads(I)-12 & ", "& Quads(I)-6 & ", "& Quads(I) & "]"
Next I
 
Print Chr(10); C5; " quintuplet(s) ending with:"
I = Iif(C5 > 5, 5, C5)
For I = I-1 To 0 Step -1
Print " [" & Quins(I)-24 & ", "& Quins(I)-18 & ", "& Quins(I)-12 & ", "& Quins(I)-6 & ", "& Quins(I) & "]"
Next I
 
Print Chr(10); CU; " unsexy primes ending with:"
For I = 9 To 0 Step -1
Print Unsexy(I); ",";
Next I
Print Chr(8); " "
Sleep</syntaxhighlight>
{{out}}
<pre> 78500 primes less than 1000035
 
16386 pairs ending with:
[999371, 999377]
[999431, 999437]
[999721, 999727]
[999763, 999769]
[999953, 999959]
 
2900 triplets ending with:
[997427, 997433, 997439]
[997541, 997547, 997553]
[998071, 998077, 998083]
[998617, 998623, 998629]
[998737, 998743, 998749]
 
325 quadruplets ending with:
[977351, 977357, 977363, 977369]
[983771, 983777, 983783, 983789]
[986131, 986137, 986143, 986149]
[990371, 990377, 990383, 990389]
[997091, 997097, 997103, 997109]
 
1 quintuplet(s) ending with:
[5, 11, 17, 23, 29]
 
48627 unsexy primes ending with:
999853, 999863, 999883, 999907, 999917, 999931, 999961, 999979, 999983, 1000003</pre>
 
==={{header|Yabasic}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="vbnet">import isprime
 
maxi = 1000035
cu = 0
c2 = 0
c3 = 0
c4 = 0
c5 = 0
p = 0
dim unsexy(10), pairs(5), trips(5), quads(5), quins(5)
 
for n = maxi to 2 step -1
if isPrime(n) then
p = p + 1
if not isPrime(n - 6) and not isPrime(n + 6) then
if cu < 10 unsexy(cu) = n
cu = cu + 1
fi
if isPrime(n - 6) then
if c2 < 5 pairs(c2) = n
c2 = c2 + 1
if isPrime(n - 12) then
if c3 < 5 trips(c3) = n
c3 = c3 + 1
if isPrime(n - 18) then
if c4 < 5 quads(c4) = n
c4 = c4 + 1
if isPrime(n - 24) then
if c5 < 5 quins(c5) = n
c5 = c5 + 1
fi
fi
fi
fi
fi
next n
 
print p, " primes less than ", maxi
 
print chr$(10), c2, " pairs ending with:"
for i = 4 to 0 step -1
print " [", pairs(i)-6, ", ", pairs(i), "]"
next i
 
print chr$(10), c3, " triplets ending with:"
for i = 4 to 0 step -1
print " [", trips(i)-12, ", ", trips(i)-6, ", ", trips(i), "]"
next i
 
print chr$(10), c4, " quadruplets ending with:"
for i = 4 to 0 step -1
print " [", quads(i)-18, ", ", quads(i)-12, ", ", quads(i)-6, ", ", quads(i), "]"
next i
 
print chr$(10), c5, " quintuplet(s) ending with:"
if c5 > 5 then i = 5 else i = c5 : fi
for i = i-1 to 0 step -1
print " [", quins(i)-24, ", ", quins(i)-18, ", ", quins(i)-12, ", ", quins(i)-6, ", ", quins(i), "]"
next i
 
print chr$(10), cu, " unsexy primes ending with:"
for i = 9 to 0 step -1
print unsexy(i), ",";
next i
print chr$(8)," "
end</syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
 
=={{header|C}}==
Similar approach to the Go entry but only stores the arrays that need to be printed out.
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <locale.h>
 
#define TRUE 1
#define FALSE 0
 
typedef unsigned char bool;
 
void sieve(bool *c, int limit) {
int i, p = 3, p2;
// TRUE denotes composite, FALSE denotes prime.
c[0] = TRUE;
c[1] = TRUE;
// no need to bother with even numbers over 2 for this task
for (;;) {
p2 = p * p;
if (p2 >= limit) {
break;
}
for (i = p2; i < limit; i += 2*p) {
c[i] = TRUE;
}
for (;;) {
p += 2;
if (!c[p]) {
break;
}
}
}
}
 
void printHelper(const char *cat, int len, int lim, int n) {
const char *sp = strcmp(cat, "unsexy primes") ? "sexy prime " : "";
const char *verb = (len == 1) ? "is" : "are";
printf("Number of %s%s less than %'d = %'d\n", sp, cat, lim, len);
printf("The last %d %s:\n", n, verb);
}
 
void printArray(int *a, int len) {
int i;
printf("[");
for (i = 0; i < len; ++i) printf("%d ", a[i]);
printf("\b]");
}
 
int main() {
int i, ix, n, lim = 1000035;
int pairs = 0, trips = 0, quads = 0, quins = 0, unsexy = 2;
int pr = 0, tr = 0, qd = 0, qn = 0, un = 2;
int lpr = 5, ltr = 5, lqd = 5, lqn = 5, lun = 10;
int last_pr[5][2], last_tr[5][3], last_qd[5][4], last_qn[5][5];
int last_un[10];
bool *sv = calloc(lim - 1, sizeof(bool)); // all FALSE by default
setlocale(LC_NUMERIC, "");
sieve(sv, lim);
 
// get the counts first
for (i = 3; i < lim; i += 2) {
if (i > 5 && i < lim-6 && !sv[i] && sv[i-6] && sv[i+6]) {
unsexy++;
continue;
}
if (i < lim-6 && !sv[i] && !sv[i+6]) {
pairs++;
} else continue;
 
if (i < lim-12 && !sv[i+12]) {
trips++;
} else continue;
 
if (i < lim-18 && !sv[i+18]) {
quads++;
} else continue;
 
if (i < lim-24 && !sv[i+24]) {
quins++;
}
}
if (pairs < lpr) lpr = pairs;
if (trips < ltr) ltr = trips;
if (quads < lqd) lqd = quads;
if (quins < lqn) lqn = quins;
if (unsexy < lun) lun = unsexy;
 
// now get the last 'x' for each category
for (i = 3; i < lim; i += 2) {
if (i > 5 && i < lim-6 && !sv[i] && sv[i-6] && sv[i+6]) {
un++;
if (un > unsexy - lun) {
last_un[un + lun - 1 - unsexy] = i;
}
continue;
}
if (i < lim-6 && !sv[i] && !sv[i+6]) {
pr++;
if (pr > pairs - lpr) {
ix = pr + lpr - 1 - pairs;
last_pr[ix][0] = i; last_pr[ix][1] = i + 6;
}
} else continue;
 
if (i < lim-12 && !sv[i+12]) {
tr++;
if (tr > trips - ltr) {
ix = tr + ltr - 1 - trips;
last_tr[ix][0] = i; last_tr[ix][1] = i + 6;
last_tr[ix][2] = i + 12;
}
} else continue;
 
if (i < lim-18 && !sv[i+18]) {
qd++;
if (qd > quads - lqd) {
ix = qd + lqd - 1 - quads;
last_qd[ix][0] = i; last_qd[ix][1] = i + 6;
last_qd[ix][2] = i + 12; last_qd[ix][3] = i + 18;
}
} else continue;
 
if (i < lim-24 && !sv[i+24]) {
qn++;
if (qn > quins - lqn) {
ix = qn + lqn - 1 - quins;
last_qn[ix][0] = i; last_qn[ix][1] = i + 6;
last_qn[ix][2] = i + 12; last_qn[ix][3] = i + 18;
last_qn[ix][4] = i + 24;
}
}
}
 
printHelper("pairs", pairs, lim, lpr);
printf(" [");
for (i = 0; i < lpr; ++i) {
printArray(last_pr[i], 2);
printf("\b] ");
}
printf("\b]\n\n");
 
printHelper("triplets", trips, lim, ltr);
printf(" [");
for (i = 0; i < ltr; ++i) {
printArray(last_tr[i], 3);
printf("\b] ");
}
printf("\b]\n\n");
 
printHelper("quadruplets", quads, lim, lqd);
printf(" [");
for (i = 0; i < lqd; ++i) {
printArray(last_qd[i], 4);
printf("\b] ");
}
printf("\b]\n\n");
 
printHelper("quintuplets", quins, lim, lqn);
printf(" [");
for (i = 0; i < lqn; ++i) {
printArray(last_qn[i], 5);
printf("\b] ");
}
printf("\b]\n\n");
 
printHelper("unsexy primes", unsexy, lim, lun);
printf(" [");
printArray(last_un, lun);
printf("\b]\n");
free(sv);
return 0;
}</syntaxhighlight>
 
{{out}}
<pre>
Number of sexy prime pairs less than 1,000,035 = 16,386
The last 5 are:
[[999371 999377] [999431 999437] [999721 999727] [999763 999769] [999953 999959]]
 
Number of sexy prime triplets less than 1,000,035 = 2,900
The last 5 are:
[[997427 997433 997439] [997541 997547 997553] [998071 998077 998083] [998617 998623 998629] [998737 998743 998749]]
 
Number of sexy prime quadruplets less than 1,000,035 = 325
The last 5 are:
[[977351 977357 977363 977369] [983771 983777 983783 983789] [986131 986137 986143 986149] [990371 990377 990383 990389] [997091 997097 997103 997109]]
 
Number of sexy prime quintuplets less than 1,000,035 = 1
The last 1 is:
[[5 11 17 23 29]]
 
Number of unsexy primes less than 1,000,035 = 48,627
The last 10 are:
[[999853 999863 999883 999907 999917 999931 999961 999979 999983 1000003]
</pre>
 
=={{header|C++}}==
{{libheader|Boost}}
<syntaxhighlight lang="cpp">#include <array>
#include <iostream>
#include <vector>
#include <boost/circular_buffer.hpp>
#include "prime_sieve.hpp"
 
int main() {
using std::cout;
using std::vector;
using boost::circular_buffer;
using group_buffer = circular_buffer<vector<int>>;
 
const int max = 1000035;
const int max_group_size = 5;
const int diff = 6;
const int array_size = max + diff;
const int max_groups = 5;
const int max_unsexy = 10;
 
// Use Sieve of Eratosthenes to find prime numbers up to max
prime_sieve sieve(array_size);
 
std::array<int, max_group_size> group_count{0};
vector<group_buffer> groups(max_group_size, group_buffer(max_groups));
int unsexy_count = 0;
circular_buffer<int> unsexy_primes(max_unsexy);
vector<int> group;
 
for (int p = 2; p < max; ++p) {
if (!sieve.is_prime(p))
continue;
if (!sieve.is_prime(p + diff) && (p - diff < 2 || !sieve.is_prime(p - diff))) {
// if p + diff and p - diff aren't prime then p can't be sexy
++unsexy_count;
unsexy_primes.push_back(p);
} else {
// find the groups of sexy primes that begin with p
group.clear();
group.push_back(p);
for (int group_size = 1; group_size < max_group_size; group_size++) {
int next_p = p + group_size * diff;
if (next_p >= max || !sieve.is_prime(next_p))
break;
group.push_back(next_p);
++group_count[group_size];
groups[group_size].push_back(group);
}
}
}
 
for (int size = 1; size < max_group_size; ++size) {
cout << "number of groups of size " << size + 1 << " is " << group_count[size] << '\n';
cout << "last " << groups[size].size() << " groups of size " << size + 1 << ":";
for (const vector<int>& group : groups[size]) {
cout << " (";
for (size_t i = 0; i < group.size(); ++i) {
if (i > 0)
cout << ' ';
cout << group[i];
}
cout << ")";
}
cout << "\n\n";
}
cout << "number of unsexy primes is " << unsexy_count << '\n';
cout << "last " << unsexy_primes.size() << " unsexy primes:";
for (int prime : unsexy_primes)
cout << ' ' << prime;
cout << '\n';
return 0;
}</syntaxhighlight>
 
Contents of prime_sieve.hpp:
<syntaxhighlight lang="cpp">#ifndef PRIME_SIEVE_HPP
#define PRIME_SIEVE_HPP
 
#include <algorithm>
#include <vector>
 
/**
* A simple implementation of the Sieve of Eratosthenes.
* See https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes.
*/
class prime_sieve {
public:
explicit prime_sieve(size_t);
bool is_prime(size_t) const;
private:
std::vector<bool> is_prime_;
};
 
/**
* Constructs a sieve with the given limit.
*
* @param limit the maximum integer that can be tested for primality
*/
inline prime_sieve::prime_sieve(size_t limit) {
limit = std::max(size_t(3), limit);
is_prime_.resize(limit/2, true);
for (size_t p = 3; p * p <= limit; p += 2) {
if (is_prime_[p/2 - 1]) {
size_t inc = 2 * p;
for (size_t q = p * p; q <= limit; q += inc)
is_prime_[q/2 - 1] = false;
}
}
}
 
/**
* Returns true if the given integer is a prime number. The integer
* must be less than or equal to the limit passed to the constructor.
*
* @param n an integer less than or equal to the limit passed to the
* constructor
* @return true if the integer is prime
*/
inline bool prime_sieve::is_prime(size_t n) const {
if (n == 2)
return true;
if (n < 2 || n % 2 == 0)
return false;
return is_prime_.at(n/2 - 1);
}
 
#endif</syntaxhighlight>
 
{{out}}
<pre>
number of groups of size 2 is 16386
last 5 groups of size 2: (999371 999377) (999431 999437) (999721 999727) (999763 999769) (999953 999959)
 
number of groups of size 3 is 2900
last 5 groups of size 3: (997427 997433 997439) (997541 997547 997553) (998071 998077 998083) (998617 998623 998629) (998737 998743 998749)
 
number of groups of size 4 is 325
last 5 groups of size 4: (977351 977357 977363 977369) (983771 983777 983783 983789) (986131 986137 986143 986149) (990371 990377 990383 990389) (997091 997097 997103 997109)
 
number of groups of size 5 is 1
last 1 groups of size 5: (5 11 17 23 29)
 
number of unsexy primes is 48627
last 10 unsexy primes: 999853 999863 999883 999907 999917 999931 999961 999979 999983 1000003
</pre>
 
=={{header|Delphi}}==
See [https://rosettacode.org/wiki/Sexy_primes#Pascal Pascal].
 
=={{header|EasyLang}}==
<syntaxhighlight>
len isdiv[] 1000035
proc sieve . .
max = sqrt len isdiv[]
for d = 2 to max
if isdiv[d] = 0
for i = d * d step d to len isdiv[]
isdiv[i] = 1
.
.
.
.
sieve
#
proc showsx nr . .
for i = len isdiv[] - 6 * nr downto 3
if isdiv[i] = 0
h = 0
for j to nr
h += isdiv[i + j * 6]
.
if h = 0
cnt += 1
if cnt <= 5
s[] &= i
.
.
.
.
print cnt & " sexy primes of " & nr + 1
if cnt > 5
write "... "
.
for i = lower 5 len s[] downto 1
write "(" & s[i]
for j to nr
write " " & s[i] + j * 6
.
write ") "
.
print ""
.
proc showunsx . .
for i = len isdiv[] - 6 downto 2
if isdiv[i] = 0 and isdiv[i + 6] = 1 and (i <= 6 or isdiv[i - 6] = 1)
cnt += 1
if cnt <= 10
s[] &= i
.
.
.
print cnt & " unsexy primes"
write "... "
for i = 10 downto 1
write s[i] & " "
.
print ""
.
showsx 1
showsx 2
showsx 3
showsx 4
showunsx
</syntaxhighlight>
 
{{out}}
<pre>
16386 sexy primes of 2
... (999371 999377) (999431 999437) (999721 999727) (999763 999769) (999953 999959)
2900 sexy primes of 3
... (997427 997433 997439) (997541 997547 997553) (998071 998077 998083) (998617 998623 998629) (998737 998743 998749)
325 sexy primes of 4
... (977351 977357 977363 977369) (983771 983777 983783 983789) (986131 986137 986143 986149) (990371 990377 990383 990389) (997091 997097 997103 997109)
1 sexy primes of 5
(5 11 17 23 29)
48627 unsexy primes
... 999853 999863 999883 999907 999917 999931 999961 999979 999983 1000003
</pre>
 
=={{header|F_Sharp|F#}}==
This task uses [http://www.rosettacode.org/wiki/Extensible_prime_generator#The_function Extensible Prime Generator (F#)]
<syntaxhighlight lang="fsharp">
// Sexy primes. Nigel Galloway: October 2nd., 2018
let n=pCache |> Seq.takeWhile(fun n->n<1000035) |> Seq.filter(fun n->(not (isPrime(n+6)) && (not isPrime(n-6))))) |> Array.ofSeq
printfn "There are %d unsexy primes less than 1,000,035. The last 10 are:" n.Length
Array.skip (n.Length-10) n |> Array.iter(fun n->printf "%d " n); printfn ""
let ni=pCache |> Seq.takeWhile(fun n->n<1000035) |> Seq.filter(fun n->isPrime(n-6)) |> Array.ofSeq
printfn "There are %d sexy prime pairs all components of which are less than 1,000,035. The last 5 are:" ni.Length
Array.skip (ni.Length-5) ni |> Array.iter(fun n->printf "(%d,%d) " (n-6) n); printfn ""
let nig=ni |> Array.filter(fun n->isPrime(n-12))
printfn "There are %d sexy prime triplets all components of which are less than 1,000,035. The last 5 are:" nig.Length
Array.skip (nig.Length-5) nig |> Array.iter(fun n->printf "(%d,%d,%d) " (n-12) (n-6) n); printfn ""
let nige=nig |> Array.filter(fun n->isPrime(n-18))
printfn "There are %d sexy prime quadruplets all components of which are less than 1,000,035. The last 5 are:" nige.Length
Array.skip (nige.Length-5) nige |> Array.iter(fun n->printf "(%d,%d,%d,%d) " (n-18) (n-12) (n-6) n); printfn ""
let nigel=nige |> Array.filter(fun n->isPrime(n-24))
printfn "There are %d sexy prime quintuplets all components of which are less than 1,000,035. The last 5 are:" nigel.Length
Array.skip (nigel.Length-5) nigel |> Array.iter(fun n->printf "(%d,%d,%d,%d,%d) " (n-24) (n-18) (n-12) (n-6) n); printfn ""
</syntaxhighlight>
{{out}}
<pre>
There are 48627 unsexy primes less than 1,000,035. The last 10 are:
999853 999863 999883 999907 999917 999931 999961 999979 999983 1000003
There are 16386 sexy prime pairs all components of which are less than 1,000,035. The last 5 are:
(999371,999377) (999431,999437) (999721,999727) (999763,999769) (999953,999959)
There are 2900 sexy prime triplets all components of which are less than 1,000,035. The last 5 are:
(997427,997433,997439) (997541,997547,997553) (998071,998077,998083) (998617,998623,998629) (998737,998743,998749)
There are 325 sexy prime quadruplets all components of which are less than 1,000,035. The last 5 are:
(977351,977357,977363,977369) (983771,983777,983783,983789) (986131.986137,986143,986149) (990371,990377,990383,990389) (997091,997097,997103,997109)
There are 1 sexy prime quintuplets all components of which are less than 1,000,035. The last 5 are:
(5,11,17,23,29)
</pre>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: combinators.short-circuit fry interpolate io kernel literals make
literals locals make math math.primes math.ranges prettyprint qw sequences ;
sequences tools.memory.private ;
IN: rosetta-code.sexy-primes
 
CONSTANT: primes $[limit 1,000,000 primes-upto ]035
CONSTANT: primes $[ limit primes-upto ]
 
CONSTANT: tuplet-names qw{ pair triplet quadruplet quintuplet }
 
: tuplet ( m n -- seq ) dupd 1 - 6 * + 6 <range> ;
 
: viable-tuplet? ( seq -- ? )
[ [ prime? ] [ limit < ] bi and ] all? ;
 
: sexy-tuplets ( n -- seq ) [ primes ] dip '[
[ _ tuplet dup [ prime? ] allviable-tuplet? [ , ] [ drop ] if ] each
] { } make ;
 
: ?last5 ( seq -- seq' ) 5 short tail* ;
 
: last5 ( seq -- str )
?last5 [ { } like unparse ] map " " join ;
 
:: tuplet-info ( n -- last5 l5-len num-tup limit tuplet-name )
n sexy-tuplets :> tup tup last5 tup ?last5 length tup length
commas limit commas n 2 - tuplet-names nth ;
 
: show-tuplets ( n -- )
tuplet-info
"Number of sexy prime " write dup 2 - tuplet-names nth write
[I Number of sexy prime ${0}s < ${1}: ${2}I] nl
"s less than 1,000,000: " write sexy-tuplets dup length .
[I Last ${0}: ${1}I] nl nl ;
5 short tail* "Up to last 5: " write [ { } like pprint bl ]
each nl nl ;
 
: unsexy-primes ( -- seq ) primes [
Line 56 ⟶ 1,082:
 
: show-unsexy ( -- )
"Number of unsexy -primes lessdup thanlength 1,000,000:commas "limit writecommas
[I Number of unsexy primes < ${0}: ${1}I] nl
unsexy-primes dup length . "Last 10: " write
"Last 10: " write 10 short tail* [ pprint bl ] each nl ;
 
: main ( -- ) 2 5 [a,b] [ show-tuplets ] each show-unsexy ;
 
MAIN: main</langsyntaxhighlight>
{{out}}
<pre>
Number of sexy prime pairs less than< 1,000,000035: 1638616,386
Up to lastLast 5: { 999371 999377 } { 999431 999437 } { 999721 999727 } { 999763 999769 } { 999953 999959 }
 
Number of sexy prime triplets less than< 1,000,000035: 29002,900
Up to lastLast 5: { 997427 997433 997439 } { 997541 997547 997553 } { 998071 998077 998083 } { 998617 998623 998629 } { 998737 998743 998749 }
 
Number of sexy prime quadruplets less than< 1,000,000035: 325
Up to lastLast 5: { 977351 977357 977363 977369 } { 983771 983777 983783 983789 } { 986131 986137 986143 986149 } { 990371 990377 990383 990389 } { 997091 997097 997103 997109 }
 
Number of sexy prime quintuplets less than< 1,000,000035: 1
UpLast to last 51: { 5 11 17 23 29 }
 
Number of unsexy primes less than< 1,000,000035: 4862648,627
Last 10: 999809 999853 999863 999883 999907 999917 999931 999961 999979 999983 1000003
</pre>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
 
func sieve(limit uint64int) []bool {
limit++
// True denotes composite, false denotes prime.
Line 93 ⟶ 1,119:
c[1] = true
// no need to bother with even numbers over 2 for this task
p := uint64(3) // Start from 3.
for {
p2 := p * p
Line 127 ⟶ 1,153:
}
 
func minOfprintHelper(acat string, ble, lim, max int) (int, int, string) {
cle, clim := commatize(le), commatize(lim)
if a < b {
if cat != "unsexy returnprimes" a{
cat = "sexy prime " + cat
}
fmt.Printf("Number of %s less than %s = %s\n", cat, clim, cle)
return b
last := max
if le < last {
last = le
}
verb := "are"
if last == 1 {
verb = "is"
}
return le, last, verb
}
 
func main() {
//lim sieve:= up to 1 million1000035
sv := sieve(1e6lim - 1)
var pairs [][2]int
var trips [][3]int
Line 142 ⟶ 1,178:
var quins [][5]int
var unsexy = []int{2, 3}
for i := 3; i < 1e6lim; i += 2 {
if i > 5 && i < 999994lim-6 && !sv[i] && sv[i-6] && sv[i+6] {
unsexy = append(unsexy, i)
continue
}
if i < 999994lim-6 && !sv[i] && !sv[i+6] {
pair := [2]int{i, i + 6}
pairs = append(pairs, pair)
Line 153 ⟶ 1,189:
continue
}
if i < 999988lim-12 && !sv[i+12] {
trip := [3]int{i, i + 6, i + 12}
trips = append(trips, trip)
Line 159 ⟶ 1,195:
continue
}
if i < 999982lim-18 && !sv[i+18] {
quad := [4]int{i, i + 6, i + 12, i + 18}
quads = append(quads, quad)
Line 165 ⟶ 1,201:
continue
}
if i < 999976lim-24 && !sv[i+24] {
quin := [5]int{i, i + 6, i + 12, i + 18, i + 24}
quins = append(quins, quin)
}
}
le, n, verb := printHelper("pairs", len(pairs), lim, 5)
fmt.PrintlnPrintf("NumberThe oflast sexy%d prime%s:\n pairs less%v\n\n", than 1n,000,000 ="verb, commatize(pairs[le)-n:])
n := minOf(le, 5)
fmt.Println("The last", n, "is/are:\n ", pairs[le-n:], "\n")
 
le, n, verb = printHelper("triplets", len(trips), lim, 5)
fmt.PrintlnPrintf("NumberThe oflast sexy%d prime%s:\n triplets less%v\n\n", than 1n,000,000 ="verb, commatize(trips[le)-n:])
n = minOf(le, 5)
fmt.Println("The last", n, "is/are:\n ", trips[le-n:], "\n")
 
le, n, verb = printHelper("quadruplets", len(quads), lim, 5)
fmt.PrintlnPrintf("NumberThe oflast sexy%d prime%s:\n quadruplets less%v\n\n", than 1n,000,000 ="verb, commatize(quads[le)-n:])
n = minOf(le, 5)
fmt.Println("The last", n, "is/are:\n ", quads[le-n:], "\n")
 
le, n, verb = printHelper("quintuplets", len(quins), lim, 5)
fmt.PrintlnPrintf("NumberThe oflast sexy%d prime%s:\n quintuplets less%v\n\n", than 1n,000,000 ="verb, commatize(quins[le)-n:])
n = minOf(le, 5)
fmt.Println("The last", n, "is/are:\n ", quins[le-n:], "\n")
 
le, n, verb = printHelper("unsexy primes", len(unsexy), lim, 10)
fmt.PrintlnPrintf("NumberThe oflast unsexy%d primes%s:\n less than%v\n\n", 1n,000,000 ="verb, commatize(unsexy[le)-n:])
}</syntaxhighlight>
n = minOf(le, 10)
fmt.Println("The last", n, "is/are:\n ", unsexy[le-n:])
}</lang>
 
{{out}}
<pre>
Number of sexy prime pairs less than 1,000,000035 = 16,386
The last 5 is/are:
[[999371 999377] [999431 999437] [999721 999727] [999763 999769] [999953 999959]]
 
Number of sexy prime triplets less than 1,000,000035 = 2,900
The last 5 is/are:
[[997427 997433 997439] [997541 997547 997553] [998071 998077 998083] [998617 998623 998629] [998737 998743 998749]]
 
Number of sexy prime quadruplets less than 1,000,000035 = 325
The last 5 is/are:
[[977351 977357 977363 977369] [983771 983777 983783 983789] [986131 986137 986143 986149] [990371 990377 990383 990389] [997091 997097 997103 997109]]
 
Number of sexy prime quintuplets less than 1,000,000035 = 1
The last 1 is/are:
[[5 11 17 23 29]]
 
Number of unsexy primes less than 1,000,000035 = 48,626627
The last 10 is/are:
[999809 999853 999863 999883 999907 999917 999931 999961 999979 999983 1000003]
</pre>
=={{header|Haskell}}==
Uses Library primes. https://hackage.haskell.org/package/primes (wheel sieve).
<syntaxhighlight lang="haskell">import Text.Printf (printf)
import Data.Numbers.Primes (isPrime, primes)
 
type Pair = (Int, Int)
=={{header|Perl 6}}==
type Triplet = (Int, Int, Int)
{{works with|Rakudo|2018.08}}
type Quad = (Int, Int, Int, Int)
type Quin = (Int, Int, Int, Int, Int)
 
type Result = ([Pair], [Triplet], [Quad], [Quin], [Int])
<lang perl6>use Math::Primesieve;
my $sieve = Math::Primesieve.new;
 
groups :: Int -> Result -> Result
my $max = 1_000_000;
groups n r@(p, t, q, qn, u)
my %primes = $sieve.primes($max) X=> 1;
| isPrime n4 && isPrime n3 && isPrime n2 && isPrime n1 = (addPair, addTriplet, addQuad, addQuin, u)
| isPrime n3 && isPrime n2 && isPrime n1 = (addPair, addTriplet, addQuad, qn, u)
| isPrime n2 && isPrime n1 = (addPair, addTriplet, q, qn, u)
| isPrime n1 = (addPair, t, q, qn, u)
| not (isPrime (n+6)) && not (isPrime n1) = (p, t, q, qn, n : u)
| otherwise = r
where addPair = (n1, n) : p
addTriplet = (n2, n1, n) : t
addQuad = (n3, n2, n1, n) : q
addQuin = (n4, n3, n2, n1, n) : qn
n1 = n - 6
n2 = n - 12
n3 = n - 18
n4 = n - 24
 
main :: IO ()
my $primes = %primes.keys.categorize: { .&sexy }
main = do
printf ("Number of sexy prime pairs: %d\n" <> lastFiveText) (length pairs) (lastFive pairs)
printf ("Number of sexy prime triplets: %d\n" <> lastFiveText) (length triplets) (lastFive triplets)
printf ("Number of sexy prime quadruplets: %d\n" <> lastFiveText) (length quads) (lastFive quads)
printf "Number of sexy prime quintuplets: %d\n Last 1 : %s\n\n" (length quins) (show $ last quins)
printf "Number of unsexy primes: %d\n Last 10: %s\n\n" (length unsexy) (show $ drop (length unsexy - 10) unsexy)
where (pairs, triplets, quads, quins, unsexy) = foldr groups ([], [], [], [], []) $ takeWhile (< 1000035) primes
lastFive xs = show $ drop (length xs - 5) xs
lastFiveText = " Last 5 : %s\n\n"</syntaxhighlight>
{{out}}
<pre>
Number of sexy prime pairs: 16386
Last 5 : [(999371,999377),(999431,999437),(999721,999727),(999763,999769),(999953,999959)]
 
Number of sexy prime triplets: 2900
say "Total primes less than {comma $max}: ", comma +%primes.keys;
Last 5 : [(997427,997433,997439),(997541,997547,997553),(998071,998077,998083),(998617,998623,998629),(998737,998743,998749)]
 
Number of sexy prime quadruplets: 325
Last 5 : [(977351,977357,977363,977369),(983771,983777,983783,983789),(986131,986137,986143,986149),(990371,990377,990383,990389),(997091,997097,997103,997109)]
 
Number of sexy prime quintuplets: 1
Last 1 : [(5,11,17,23,29)]
 
Number of unsexy primes: 48627
Last 10: [999853,999863,999883,999907,999917,999931,999961,999979,999983,1000003]
</pre>
Slight variation which only holds on to the display results. Does not perform any better than above though. Both run ~ 250ms.
<syntaxhighlight lang="haskell">{-# LANGUAGE TemplateHaskell #-}
import Control.Lens (makeLenses, over, (^.), to, view)
import Data.Numbers.Primes (isPrime, primes)
import Text.Printf (printf)
 
data Group a = Group { _count :: Int, _results :: [a] } deriving (Show)
makeLenses ''Group
 
type Groups = ( Group (Int, Int)
, Group (Int, Int, Int)
, Group (Int, Int, Int, Int)
, Group (Int, Int, Int, Int, Int)
, Group Int )
 
initialGroups :: Groups
initialGroups = let newGroup = Group 0 []
in (newGroup, newGroup, newGroup, newGroup, newGroup)
 
collect :: Groups -> Int -> Groups
collect r@(pr, tt, qd, qn, un) n
| isPrime n4 && isPrime n3 && isPrime n2 && isPrime n1 = (addPair pr, addTriplet tt, addQuad qd, addQuin qn, un)
| isPrime n3 && isPrime n2 && isPrime n1 = (addPair pr, addTriplet tt, addQuad qd, qn, un)
| isPrime n2 && isPrime n1 = (addPair pr, addTriplet tt, qd, qn, un)
| isPrime n1 = (addPair pr, tt, qd, qn, un)
| not (isPrime (n+6)) && not (isPrime n1) = (pr, tt, qd, qn, addUnSexy un)
| otherwise = r
where
n1 = n-6
n2 = n-12
n3 = n-18
n4 = n-24
 
addPair = over count succ . over results (take 5 . (:) (n1, n))
addTriplet = over count succ . over results (take 5 . (:) (n2, n1, n))
addQuad = over count succ . over results (take 5 . (:) (n3, n2, n1, n))
addQuin = over count succ . over results (take 1 . (:) (n4, n3, n2, n1, n))
addUnSexy = over count succ . over results (take 10 . (:) n)
 
main :: IO ()
main = do
let (pr, tt, qd, qn, un) = collectGroups primes
printf "Number of sexy prime pairs: %d\n Last 5 : %s\n\n" (pr ^. count) (pr ^. results . to display)
printf "Number of sexy prime triplets: %d\n Last 5 : %s\n\n" (tt ^. count) (tt ^. results . to display)
printf "Number of sexy prime quadruplets: %d\n Last 5 : %s\n\n" (qd ^. count) (qd ^. results . to display)
printf "Number of sexy prime quintuplets: %d\n Last 1 : %s\n\n" (qn ^. count) (qn ^. results . to display)
printf "Number of unsexy primes: %d\n Last 10: %s\n\n" (un ^. count) (un ^. results . to display)
where
collectGroups = foldl collect initialGroups . takeWhile (< 1000035)
display :: Show a => [a] -> String
display = show . reverse</syntaxhighlight>
 
=={{header|J}}==
A brute force approach finds primes in the task range which are preceded by primes with appropriate offsets:
<syntaxhighlight lang=J> #sp2=: (#~ 1 p: _6+]) p1=:i.&.(p:inv) 1000035 NB. pairs
16386
(_6*i.-2)+/_5{.sp2
999371 999431 999721 999763 999953
999377 999437 999727 999769 999959
#sp3=: (#~ 1 p: _12+]) sp2 NB. triplets
2900
(_6*i.-3)+/_5{.sp3
997427 997541 998071 998617 998737
997433 997547 998077 998623 998743
997439 997553 998083 998629 998749
#sp4=: (#~ 1 p: _18+]) sp3 NB. quads
325
(_6*i.-5)+/_5{.sp4
977345 983765 986125 990365 997085
977351 983771 986131 990371 997091
977357 983777 986137 990377 997097
977363 983783 986143 990383 997103
977369 983789 986149 990389 997109
#sp5=: (#~ 1 p: _24+]) sp4 NB. quint
1
(_6*i.5)+/sp5
29
23
17
11
5
#unp=: p1-. 0 6+/(#~ 1 p: 6+]) p1
48627
_10{.unp
999853 999863 999883 999907 999917 999931 999961 999979 999983 1000003
</syntaxhighlight>
 
And here's a different approach:
<syntaxhighlight lang="j">NB. Primes Not Greater Than (the input)
NB. The 1 _1 p: ... logic here allows the input value to
NB. be included in the list in the case it itself is prime
pngt =: p:@:i.@:([: +/ 1 _1 p:"0 ])
 
NB. Add 6 and see which sums appear in input list
sexy =: ] #~ + e. ]
 
NB. Iterate "sexy" logic up to orgy size
orgy =: sexy&.>^:( ({.@:[) ` (<@:{:@:[) ` (<@:]) )
 
sp =: dyad define
'pd os' =. x NB. x is prime distance (6), orgy size (5)
p =. pngt y
o =. x orgy p
g =. o +/&.> <\ +/\ _1 |.!.0 os # pd NB. Groups
 
's g' =. split g NB. Split singles from groups
l =. (({.~ -) 5 <. #)&.> g NB. Last (max) 5 groups
 
NB. I'm sure there's something clever with p-.s or similar,
NB. but (a) I don't want to think through it, and (b)
NB. it causes the kind of edge-case issues the spec warns
NB. about with 1000033
us =. p (] #~ 1 +:/@:p: +/)~ (+,-) pd NB. Unsexy numbers
( (# ; _10&{.) us ) , (#&.> g) ,. l
)</syntaxhighlight>
 
{{out}}
<syntaxhighlight lang="j"> r =: 6 5 sp 1000035 NB. 6=sex=prime distance, 5=max orgy size
(;:'Group Count Examples') , (;:'Unsexy Pairs Triplets Quadruplets Quintuplets') ,. r
+-----------+-----+----------------------------------------------------------------------+
|Group |Count|Examples |
+-----------+-----+----------------------------------------------------------------------+
|Unsexy |48627|999853 999863 999883 999907 999917 999931 999961 999979 999983 1000003|
+-----------+-----+----------------------------------------------------------------------+
|Pairs |16386|999371 999377 |
| | |999431 999437 |
| | |999721 999727 |
| | |999763 999769 |
| | |999953 999959 |
+-----------+-----+----------------------------------------------------------------------+
|Triplets |2900 |997427 997433 997439 |
| | |997541 997547 997553 |
| | |998071 998077 998083 |
| | |998617 998623 998629 |
| | |998737 998743 998749 |
+-----------+-----+----------------------------------------------------------------------+
|Quadruplets|325 |977351 977357 977363 977369 |
| | |983771 983777 983783 983789 |
| | |986131 986137 986143 986149 |
| | |990371 990377 990383 990389 |
| | |997091 997097 997103 997109 |
+-----------+-----+----------------------------------------------------------------------+
|Quintuplets|1 |5 11 17 23 29 |
+-----------+-----+----------------------------------------------------------------------+</syntaxhighlight>
 
=={{header|Java}}==
<syntaxhighlight lang="java">
import java.util.ArrayList;
import java.util.List;
 
public class SexyPrimes {
 
public static void main(String[] args) {
sieve();
int pairs = 0;
List<String> pairList = new ArrayList<>();
int triples = 0;
List<String> tripleList = new ArrayList<>();
int quadruplets = 0;
List<String> quadrupletList = new ArrayList<>();
int unsexyCount = 1; // 2 (the even prime) not found in tests below.
List<String> unsexyList = new ArrayList<>();
for ( int i = 3 ; i < MAX ; i++ ) {
if ( i-6 >= 3 && primes[i-6] && primes[i] ) {
pairs++;
pairList.add((i-6) + " " + i);
if ( pairList.size() > 5 ) {
pairList.remove(0);
}
}
else if ( i < MAX-2 && primes[i] && ! (i+6<MAX && primes[i] && primes[i+6])) {
unsexyCount++;
unsexyList.add("" + i);
if ( unsexyList.size() > 10 ) {
unsexyList.remove(0);
}
}
if ( i-12 >= 3 && primes[i-12] && primes[i-6] && primes[i] ) {
triples++;
tripleList.add((i-12) + " " + (i-6) + " " + i);
if ( tripleList.size() > 5 ) {
tripleList.remove(0);
}
}
if ( i-16 >= 3 && primes[i-18] && primes[i-12] && primes[i-6] && primes[i] ) {
quadruplets++;
quadrupletList.add((i-18) + " " + (i-12) + " " + (i-6) + " " + i);
if ( quadrupletList.size() > 5 ) {
quadrupletList.remove(0);
}
}
}
System.out.printf("Count of sexy triples less than %,d = %,d%n", MAX, pairs);
System.out.printf("The last 5 sexy pairs:%n %s%n%n", pairList.toString().replaceAll(", ", "], ["));
System.out.printf("Count of sexy triples less than %,d = %,d%n", MAX, triples);
System.out.printf("The last 5 sexy triples:%n %s%n%n", tripleList.toString().replaceAll(", ", "], ["));
System.out.printf("Count of sexy quadruplets less than %,d = %,d%n", MAX, quadruplets);
System.out.printf("The last 5 sexy quadruplets:%n %s%n%n", quadrupletList.toString().replaceAll(", ", "], ["));
System.out.printf("Count of unsexy primes less than %,d = %,d%n", MAX, unsexyCount);
System.out.printf("The last 10 unsexy primes:%n %s%n%n", unsexyList.toString().replaceAll(", ", "], ["));
}
 
private static int MAX = 1_000_035;
private static boolean[] primes = new boolean[MAX];
 
private static final void sieve() {
// primes
for ( int i = 2 ; i < MAX ; i++ ) {
primes[i] = true;
}
for ( int i = 2 ; i < MAX ; i++ ) {
if ( primes[i] ) {
for ( int j = 2*i ; j < MAX ; j += i ) {
primes[j] = false;
}
}
}
}
 
for <pair 2 triplet 3 quadruplet 4 quintuplet 5> -> $sexy, $cnt {
say "Number of sexy prime {$sexy}s less than {comma $max}: ", comma +$primes{$sexy};
say " Last 5 sexy prime {$sexy}s less than {comma $max}: ",
join ' ', $primes{$sexy}.sort(+*).tail(5).grep(*.defined).map:
{ "({ $_ «+« (0,6 … 24)[^$cnt] })" }
say '';
}
</syntaxhighlight>
 
{{out}}
say "Number of unsexy primes less than {comma $max}: ", comma +$primes<unsexy>;
<pre>
say " Last 10 unsexy primes less than {comma $max}: ", $primes<unsexy>.sort(+*).tail(10);
Count of sexy triples less than 1,000,035 = 16,386
The last 5 sexy pairs:
[999371 999377], [999431 999437], [999721 999727], [999763 999769], [999953 999959]
 
Count of sexy triples less than 1,000,035 = 2,900
sub sexy ($i) {
The last 5 sexy triples:
(
[997427 997433 997439], [997541 997547 997553], [998071 998077 998083], [998617 998623 998629], [998737 998743 998749]
(so all(%primes{$i «+« (6,12,18,24)})) ?? 'quintuplet' !! Nil,
 
(so all(%primes{$i «+« (6,12,18) })) ?? 'quadruplet' !! Nil,
Count of sexy quadruplets less than 1,000,035 = 325
(so all(%primes{$i «+« (6,12) })) ?? 'triplet' !! Nil,
The last 5 sexy quadruplets:
(so %primes{$i + 6 }) ?? 'pair' !! Nil,
[977351 977357 977363 977369], [983771 983777 983783 983789], [986131 986137 986143 986149], [990371 990377 990383 990389], [997091 997097 997103 997109]
(so any(%primes{$i «+« (6,-6) })) ?? 'sexy' !! 'unsexy'
 
).grep: *.defined
Count of unsexy primes less than 1,000,035 = 48,627
The last 10 unsexy primes:
[999853], [999863], [999883], [999907], [999917], [999931], [999961], [999979], [999983], [1000003]
</pre>
 
=={{header|jq}}==
'''Adapted from [[#Wren|Wren]]'''
{{works with|jq}}
''Also works with gojq and fq''
 
See e.g. [[Anaprimes#jq]] for a suitable jq def of `primeSieve`.
<syntaxhighlight lang=jq>
include "primeSieve"; # or copy-and-paste its def
 
def when(filter; action): if filter // null then action else . end;
 
def results($cat; $lim; $max; $array):
($array|length) as $len
| (if $cat != "unsexy primes" then "sexy prime " + $cat else $cat end) as $cat
| (if $len < $max then $len else $max end) as $last
| (if $last == 1 then "is" else "are" end) as $verb
| "Number of \($cat) less than \($lim) = \($len)",
"The last \($max) \($verb):\n \($array[ - $last :])\n";
 
def task($lim):
(($lim-1) | primeSieve) as $sieve # $sieve[i] iff i is prime
| { pairs:[], trips:[], quads:[], quins:[], unsexy:[2, 3], i: 3 }
| until (.i >= $lim;
if .i > 5 and .i < $lim-6 and $sieve[.i] and ($sieve[.i-6]|not) and ($sieve[.i+6]|not)
then .unsexy += [.i]
else when(.i < $lim-6 and $sieve[.i] and $sieve[.i+6];
.pairs += [[.i, .i+6]]
| when(.i < $lim-12 and $sieve[.i+12];
.trips += [[.i, .i+6, .i+12]]
| when(.i < $lim-18 and $sieve[.i+18];
.quads += [[.i, .i+6, .i+12, .i+18]]
| when(.i < $lim-24 and $sieve[.i+24];
.quins += [[.i, .i+6, .i+12, .i+18, .i+24]]))))
end
| .i += 2 )
| results("pairs"; $lim; 5; .pairs),
results("triplets"; $lim; 5; .trips),
results("quadruplets"; $lim; 5; .quads),
results("quintuplets"; $lim; 5; .quins),
results("unsexy primes"; $lim; 10; .unsexy)
;
 
task(1000035)
</syntaxhighlight>
{{output}}
<pre>
Number of sexy prime pairs less than 1000035 = 16386
The last 5 are:
[[999371,999377],[999431,999437],[999721,999727],[999763,999769],[999953,999959]]
 
Number of sexy prime triplets less than 1000035 = 2900
The last 5 are:
[[997427,997433,997439],[997541,997547,997553],[998071,998077,998083],[998617,998623,998629],[998737,998743,998749]]
 
Number of sexy prime quadruplets less than 1000035 = 325
The last 5 are:
[[977351,977357,977363,977369],[983771,983777,983783,983789],[986131,986137,986143,986149],[990371,990377,990383,990389],[997091,997097,997103,997109]]
 
Number of sexy prime quintuplets less than 1000035 = 1
The last 5 is:
[[5,11,17,23,29]]
 
Number of unsexy primes less than 1000035 = 48627
The last 10 are:
[999853,999863,999883,999907,999917,999931,999961,999979,999983,1000003]
</pre>
 
=={{header|Julia}}==
<syntaxhighlight lang="julia">
using Primes
 
function nextby6(n, a)
top = length(a)
i = n + 1
j = n + 2
k = n + 3
if n >= top
return n
end
possiblenext = a[n] + 6
if i <= top && possiblenext == a[i]
return i
elseif j <= top && possiblenext == a[j]
return j
elseif k <= top && possiblenext == a[k]
return k
end
return n
end
 
function lastones(dict, n)
arr = sort(collect(keys(dict)))
beginidx = max(1, length(arr) - n + 1)
arr[beginidx: end]
end
 
function lastoneslessthan(dict, n, ceiling)
arr = filter(y -> y < ceiling, lastones(dict, n+3))
beginidx = max(1, length(arr) - n + 1)
arr[beginidx: end]
end
 
function primesbysexiness(x)
twins = Dict{Int64, Array{Int64,1}}()
triplets = Dict{Int64, Array{Int64,1}}()
quadruplets = Dict{Int64, Array{Int64,1}}()
quintuplets = Dict{Int64, Array{Int64,1}}()
possibles = primes(x + 30)
singles = filter(y -> y <= x - 6, possibles)
unsexy = Dict(p => true for p in singles)
for (i, p) in enumerate(singles)
twinidx = nextby6(i, possibles)
if twinidx > i
delete!(unsexy, p)
delete!(unsexy, p + 6)
twins[p] = [i, twinidx]
tripidx = nextby6(twinidx, possibles)
if tripidx > twinidx
triplets[p] = [i, twinidx, tripidx]
quadidx = nextby6(tripidx, possibles)
if quadidx > tripidx
quadruplets[p] = [i, twinidx, tripidx, quadidx]
quintidx = nextby6(quadidx, possibles)
if quintidx > quadidx
quintuplets[p] = [i, twinidx, tripidx, quadidx, quintidx]
end
end
end
end
end
# Find and display the count of each group
println("There are:\n$(length(twins)) twins,\n",
"$(length(triplets)) triplets,\n",
"$(length(quadruplets)) quadruplets, and\n",
"$(length(quintuplets)) quintuplets less than $x.")
println("The last 5 twin primes start with ", lastoneslessthan(twins, 5, x - 6))
println("The last 5 triplet primes start with ", lastones(triplets, 5))
println("The last 5 quadruplet primes start with ", lastones(quadruplets, 5))
println("The quintuplet primes start with ", lastones(quintuplets, 5))
println("There are $(length(unsexy)) unsexy primes less than $x.")
lastunsexy = sort(collect(keys(unsexy)))[length(unsexy) - 9: end]
println("The last 10 unsexy primes are: $lastunsexy")
end
 
primesbysexiness(1000035) </syntaxhighlight> {{output}} <pre>
There are:
16386 twins,
2900 triplets,
325 quadruplets, and
1 quintuplets less than 1000035.
The last 5 twin primes start with [999371, 999431, 999721, 999763, 999953]
The last 5 triplet primes start with [997427, 997541, 998071, 998617, 998737]
The last 5 quadruplet primes start with [977351, 983771, 986131, 990371, 997091]
The quintuplet primes start with [5]
There are 48627 unsexy primes less than 1000035.
The last 10 unsexy primes are: [999853, 999863, 999883, 999907, 999917, 999931, 999961, 999979, 999983, 1000003]
</pre>
 
=={{header|Kotlin}}==
{{trans|Go}}
<syntaxhighlight lang="scala">// Version 1.2.71
 
fun sieve(lim: Int): BooleanArray {
var limit = lim + 1
// True denotes composite, false denotes prime.
val c = BooleanArray(limit) // all false by default
c[0] = true
c[1] = true
// No need to bother with even numbers over 2 for this task.
var p = 3 // Start from 3.
while (true) {
val p2 = p * p
if (p2 >= limit) break
for (i in p2 until limit step 2 * p) c[i] = true
while (true) {
p += 2
if (!c[p]) break
}
}
return c
}
 
fun printHelper(cat: String, len: Int, lim: Int, max: Int): Pair<Int, String> {
sub comma { $^i.flip.comb(3).join(',').flip }</lang>
val cat2 = if (cat != "unsexy primes") "sexy prime " + cat else cat
System.out.printf("Number of %s less than %d = %,d\n", cat2, lim, len)
val last = if (len < max) len else max
val verb = if (last == 1) "is" else "are"
return last to verb
}
 
fun main(args: Array<String>) {
val lim = 1_000_035
val sv = sieve(lim - 1)
val pairs = mutableListOf<List<Int>>()
val trips = mutableListOf<List<Int>>()
val quads = mutableListOf<List<Int>>()
val quins = mutableListOf<List<Int>>()
val unsexy = mutableListOf(2, 3)
for (i in 3 until lim step 2) {
if (i > 5 && i < lim - 6 && !sv[i] && sv[i - 6] && sv[i + 6]) {
unsexy.add(i)
continue
}
 
if (i < lim - 6 && !sv[i] && !sv[i + 6]) {
val pair = listOf(i, i + 6)
pairs.add(pair)
} else continue
 
if (i < lim - 12 && !sv[i + 12]) {
val trip = listOf(i, i + 6, i + 12)
trips.add(trip)
} else continue
 
if (i < lim - 18 && !sv[i + 18]) {
val quad = listOf(i, i + 6, i + 12, i + 18)
quads.add(quad)
} else continue
 
if (i < lim - 24 && !sv[i + 24]) {
val quin = listOf(i, i + 6, i + 12, i + 18, i + 24)
quins.add(quin)
}
}
 
var (n2, verb2) = printHelper("pairs", pairs.size, lim, 5)
System.out.printf("The last %d %s:\n %s\n\n", n2, verb2, pairs.takeLast(n2))
 
var (n3, verb3) = printHelper("triplets", trips.size, lim, 5)
System.out.printf("The last %d %s:\n %s\n\n", n3, verb3, trips.takeLast(n3))
 
var (n4, verb4) = printHelper("quadruplets", quads.size, lim, 5)
System.out.printf("The last %d %s:\n %s\n\n", n4, verb4, quads.takeLast(n4))
 
var (n5, verb5) = printHelper("quintuplets", quins.size, lim, 5)
System.out.printf("The last %d %s:\n %s\n\n", n5, verb5, quins.takeLast(n5))
 
var (nu, verbu) = printHelper("unsexy primes", unsexy.size, lim, 10)
System.out.printf("The last %d %s:\n %s\n\n", nu, verbu, unsexy.takeLast(nu))
}</syntaxhighlight>
 
{{output}}
<pre>
Number of sexy prime pairs less than 1000035 = 16,386
The last 5 are:
[[999371, 999377], [999431, 999437], [999721, 999727], [999763, 999769], [999953, 999959]]
 
Number of sexy prime triplets less than 1000035 = 2,900
The last 5 are:
[[997427, 997433, 997439], [997541, 997547, 997553], [998071, 998077, 998083], [998617, 998623, 998629], [998737, 998743, 998749]]
 
Number of sexy prime quadruplets less than 1000035 = 325
The last 5 are:
[[977351, 977357, 977363, 977369], [983771, 983777, 983783, 983789], [986131, 986137, 986143, 986149], [990371, 990377, 990383, 990389], [997091, 997097, 997103, 997109]]
 
Number of sexy prime quintuplets less than 1000035 = 1
The last 1 is:
[[5, 11, 17, 23, 29]]
 
Number of unsexy primes less than 1000035 = 48,627
The last 10 are:
[999853, 999863, 999883, 999907, 999917, 999931, 999961, 999979, 999983, 1000003]
</pre>
 
 
=={{header|Lua}}==
<syntaxhighlight lang="lua">local N = 1000035
 
-- FUNCS:
local function T(t) return setmetatable(t, {__index=table}) end
table.filter = function(t,f) local s=T{} for _,v in ipairs(t) do if f(v) then s[#s+1]=v end end return s end
table.map = function(t,f,...) local s=T{} for _,v in ipairs(t) do s[#s+1]=f(v,...) end return s end
table.lastn = function(t,n) local s=T{} n=n>#t and #t or n for i = 1,n do s[i]=t[#t-n+i] end return s end
table.each = function(t,f,...) for _,v in ipairs(t) do f(v,...) end end
 
-- PRIMES:
local sieve, primes = {false}, T{}
for i = 2,N+6 do sieve[i]=true end
for i = 2,N+6 do if sieve[i] then for j=i*i,N+6,i do sieve[j]=nil end end end
for i = 2,N+6 do if sieve[i] then primes[#primes+1]=i end end
 
-- TASKS:
local sexy, name = { primes }, { "primes", "pairs", "triplets", "quadruplets", "quintuplets" }
local function sexy2str(v,n) local s=T{} for i=1,n do s[i]=v+(i-1)*6 end return "("..s:concat(" ")..")" end
for i = 2, 5 do
sexy[i] = sexy[i-1]:filter(function(v) return v+(i-1)*6<N and sieve[v+(i-1)*6] end)
print(#sexy[i] .. " " .. name[i] .. ", ending with: " .. sexy[i]:lastn(5):map(sexy2str,i):concat(" "))
end
local unsexy = primes:filter(function(v) return not (v>=N or sieve[v-6] or sieve[v+6]) end)
print(#unsexy .. " unsexy, ending with: " ..unsexy:lastn(10):concat(" "))</syntaxhighlight>
{{out}}
<pre>16386 pairs, ending with: (999371 999377) (999431 999437) (999721 999727) (999763 999769) (999953 999959)
<pre>Total primes less than 1,000,000: 78,498
2900 triplets, ending with: (997427 997433 997439) (997541 997547 997553) (998071 998077 998083) (998617 998623 998629) (998737 998743 998749)
Number of sexy prime pairs less than 1,000,000: 16,386
325 quadruplets, ending with: (977351 977357 977363 977369) (983771 983777 983783 983789) (986131 986137 986143 986149) (990371 990377 990383 990389) (997091 997097 997103 997109)
Last 5 sexy prime pairs less than 1,000,000: (999371 999377) (999431 999437) (999721 999727) (999763 999769) (999953 999959)
1 quintuplets, ending with: (5 11 17 23 29)
48627 unsexy, ending with: 999853 999863 999883 999907 999917 999931 999961 999979 999983 1000003</pre>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Number of sexy prime triplets less than 1,000,000: 2,900
<syntaxhighlight lang="mathematica">ClearAll[AllSublengths]
Last 5 sexy prime triplets less than 1,000,000: (997427 997433 997439) (997541 997547 997553) (998071 998077 998083) (998617 998623 998629) (998737 998743 998749)
AllSublengths[l_List] := If[Length[l] > 2,
Catenate[Partition[l, #, 1] & /@ Range[2, Length[l]]]
,
{l}
]
primes = Prime[Range[PrimePi[1000035]]];
ps = Union[Intersection[primes + 6, primes] - 6, Intersection[primes - 6, primes] + 6];
a = Intersection[ps + 6, ps] - 6;
b = Intersection[ps - 6, ps] + 6;
g = Graph[DeleteDuplicates[Thread[a \[UndirectedEdge] (a + 6)]~Join~Thread[(b - 6) \[UndirectedEdge] b]]];
sp = Sort /@ ConnectedComponents[g];
sp //= SortBy[First];
sp //= Map[AllSublengths];
sp //= Catenate;
sp //= SortBy[First];
sp //= DeleteDuplicates;
sel = Select[sp, Length /* EqualTo[2]];
Length[sel]
sel[[-5 ;;]] // Column
sel = Select[sp, Length /* EqualTo[3]];
Length[sel]
sel[[-5 ;;]] // Column
sel = Select[sp, Length /* EqualTo[4]];
Length[sel]
sel[[-5 ;;]] // Column
sel = Select[sp, Length /* EqualTo[5]];
Length[sel]
sel // Column
 
Select[Complement[primes, DeleteDuplicates[Catenate@sp]][[-20 ;;]], ! (PrimeQ[# + 6] \[Or] PrimeQ[# - 6]) &][[-10 ;;]] // Column</syntaxhighlight>
Number of sexy prime quadruplets less than 1,000,000: 325
{{out}}
Last 5 sexy prime quadruplets less than 1,000,000: (977351 977357 977363 977369) (983771 983777 983783 983789) (986131 986137 986143 986149) (990371 990377 990383 990389) (997091 997097 997103 997109)
<pre>16386
{999371,999377}
{999431,999437}
{999721,999727}
{999763,999769}
{999953,999959}
2900
{997427,997433,997439}
{997541,997547,997553}
{998071,998077,998083}
{998617,998623,998629}
{998737,998743,998749}
325
{977351,977357,977363,977369}
{983771,983777,983783,983789}
{986131,986137,986143,986149}
{990371,990377,990383,990389}
{997091,997097,997103,997109}
1
{5,11,17,23,29}
999853
999863
999883
999907
999917
999931
999961
999979
999983
1000003</pre>
 
=={{header|Nim}}==
Number of sexy prime quintuplets less than 1,000,000: 1
{{trans|Kotlin}}
Last 5 sexy prime quintuplets less than 1,000,000: (5 11 17 23 29)
This Nim version uses Kotlin algorithm with several differences. In particular, we have chosen to store only the first term of groups as others can be retrieved by computation. But it complicates somewhat the printing of results.
 
<syntaxhighlight lang="nim">import math, strformat, strutils
Number of unsexy primes less than 1,000,000: 48,626
 
Last 10 unsexy primes less than 1,000,000: (999809 999853 999863 999883 999907 999917 999931 999961 999979 999983)</pre>
const Lim = 1_000_035
 
type Group {.pure.} = enum # "ord" gives the number of terms.
Unsexy = (1, "unsexy primes")
Pairs = (2, "sexy prime pairs")
Triplets = (3, "sexy prime triplets")
Quadruplets = (4, "sexy prime quadruplets")
Quintuplets = (5, "sexy prime quintuplets")
 
 
# Sieve of Erathosthenes.
var composite: array[1..Lim, bool] # Default is false.
composite[1] = true
for p in countup(3, sqrt(Lim.toFloat).int, 2): # Ignore even numbers.
if not composite[p]:
for k in countup(p * p, Lim, 2 * p):
composite[k] = true
 
template isPrime(n: int): bool = not composite[n]
 
 
proc expandGroup(n: int; group: Group): string =
## Given the first term of a group, return the full group
## representation as a string.
var n = n
for _ in 1..ord(group):
result.addSep(", ")
result.add $n
inc n, 6
if group != Unsexy: result = '(' & result & ')'
 
 
proc printResult(group: Group; values: seq[int]; count: int) =
## Print a result.
 
echo &"\nNumber of {group} less than {Lim}: {values.len}"
let last = min(values.len, count)
let verb = if last == 1: "is" else: "are"
echo &"The last {last} {verb}:"
 
var line = ""
for i in countdown(last, 1):
line.addSep(", ")
line.add expandGroup(values[^i], group)
echo " ", line
 
 
var
pairs, trips, quads, quints: seq[int] # Keep only the first prime of the group.
unsexy = @[2, 3]
 
for n in countup(3, Lim, 2):
if composite[n]: continue
 
if n in 7..(Lim - 8) and composite[n - 6] and composite[n + 6]:
unsexy.add n
continue
 
if n < Lim - 6 and isPrime(n + 6):
pairs.add n
else: continue
 
if n < Lim - 12 and isPrime(n + 12):
trips.add n
else: continue
 
if n < Lim - 18 and isPrime(n + 18):
quads.add n
else: continue
 
if n < Lim - 24 and isPrime(n + 24):
quints.add n
 
printResult(Pairs, pairs, 5)
printResult(Triplets, trips, 5)
printResult(Quadruplets, quads, 5)
printResult(Quintuplets, quints, 5)
printResult(Unsexy, unsexy, 10)</syntaxhighlight>
 
{{out}}
<pre>Number of sexy prime pairs less than 1000035: 16386
The last 5 are:
(999371, 999377), (999431, 999437), (999721, 999727), (999763, 999769), (999953, 999959)
 
Number of sexy prime triplets less than 1000035: 2900
The last 5 are:
(997427, 997433, 997439), (997541, 997547, 997553), (998071, 998077, 998083), (998617, 998623, 998629), (998737, 998743, 998749)
 
Number of sexy prime quadruplets less than 1000035: 325
The last 5 are:
(977351, 977357, 977363, 977369), (983771, 983777, 983783, 983789), (986131, 986137, 986143, 986149), (990371, 990377, 990383, 990389), (997091, 997097, 997103, 997109)
 
Number of sexy prime quintuplets less than 1000035: 1
The last 1 is:
(5, 11, 17, 23, 29)
 
Number of unsexy primes less than 1000035: 48627
The last 10 are:
999853, 999863, 999883, 999907, 999917, 999931, 999961, 999979, 999983, 1000003</pre>
 
=={{header|Pascal}}==
{{works with|Free Pascal}}
Is the count of unsexy primes = primes-2* SexyPrimesPairs +SexyPrimesTriplets-SexyPrimesQuintuplet?
 
48627 unsexy primes // = 78500-2*16386+2900-1
 
37907606 unsexy primes // = 50847538-2*6849047+758163-1
It seems so, not a proove.
<syntaxhighlight lang="pascal">program SexyPrimes;
 
uses
SysUtils
{$IFNDEF FPC}
,windows // GettickCount64
{$ENDIF}
 
const
ctext: array[0..5] of string = ('Primes',
'sexy prime pairs',
'sexy prime triplets',
'sexy prime quadruplets',
'sexy prime quintuplet',
'sexy prime sextuplet');
 
primeLmt = 1000 * 1000 + 35;
type
sxPrtpl = record
spCnt,
splast5Idx: nativeInt;
splast5: array[0..6] of NativeInt;
end;
 
var
sieve: array[0..primeLmt] of byte;
sexyPrimesTpl: array[0..5] of sxPrtpl;
unsexyprimes: NativeUint;
 
procedure dosieve;
var
p, delPos, fact: NativeInt;
begin
p := 2;
repeat
if sieve[p] = 0 then
begin
delPos := primeLmt div p;
if delPos < p then
BREAK;
fact := delPos * p;
while delPos >= p do
begin
if sieve[delPos] = 0 then
sieve[fact] := 1;
Dec(delPos);
Dec(fact, p);
end;
end;
Inc(p);
until False;
end;
procedure CheckforSexy;
var
i, idx, sieveMask, tstMask: NativeInt;
begin
sieveMask := -1;
for i := 2 to primelmt do
begin
tstMask := 1;
sieveMask := sieveMask + sieveMask + sieve[i];
idx := 0;
repeat
if (tstMask and sieveMask) = 0 then
with sexyPrimesTpl[idx] do
begin
Inc(spCnt);
//memorize the last entry
Inc(splast5idx);
if splast5idx > 5 then
splast5idx := 1;
splast5[splast5idx] := i;
tstMask := tstMask shl 6 + 1;
end
else
begin
BREAK;
end;
Inc(idx);
until idx > 5;
end;
end;
 
procedure CheckforUnsexy;
var
i: NativeInt;
begin
for i := 2 to 6 do
begin
if (Sieve[i] = 0) and (Sieve[i + 6] = 1) then
Inc(unsexyprimes);
end;
for i := 2 + 6 to primelmt - 6 do
begin
if (Sieve[i] = 0) and (Sieve[i - 6] = 1) and (Sieve[i + 6] = 1) then
Inc(unsexyprimes);
end;
end;
 
procedure OutLast5(idx: NativeInt);
var
i, j, k: nativeInt;
begin
with sexyPrimesTpl[idx] do
begin
writeln(cText[idx], ' ', spCnt);
i := splast5idx + 1;
for j := 1 to 5 do
begin
if i > 5 then
i := 1;
if splast5[i] <> 0 then
begin
Write('[');
for k := idx downto 1 do
Write(splast5[i] - k * 6, ' ');
Write(splast5[i], ']');
end;
Inc(i);
end;
end;
writeln;
end;
 
procedure OutLastUnsexy(cnt:NativeInt);
var
i: NativeInt;
erg: array of NativeUint;
begin
if cnt < 1 then
EXIT;
setlength(erg,cnt);
dec(cnt);
if cnt < 0 then
EXIT;
for i := primelmt downto 2 + 6 do
begin
if (Sieve[i] = 0) and (Sieve[i - 6] = 1) and (Sieve[i + 6] = 1) then
Begin
erg[cnt] := i;
dec(cnt);
If cnt < 0 then
BREAK;
end;
end;
write('the last ',High(Erg)+1,' unsexy primes ');
For i := 0 to High(erg)-1 do
write(erg[i],',');
write(erg[High(erg)]);
end;
var
T1, T0: int64;
i: nativeInt;
 
begin
 
T0 := GettickCount64;
dosieve;
T1 := GettickCount64;
writeln('Sieving is done in ', T1 - T0, ' ms');
T0 := GettickCount64;
CheckforSexy;
T1 := GettickCount64;
writeln('Checking is done in ', T1 - T0, ' ms');
 
unsexyprimes := 0;
T0 := GettickCount64;
CheckforUnsexy;
T1 := GettickCount64;
writeln('Checking unsexy is done in ', T1 - T0, ' ms');
 
writeln('Limit : ', primelmt);
for i := 0 to 4 do
begin
OutLast5(i);
end;
writeln;
writeln(unsexyprimes,' unsexy primes');
OutLastUnsexy(10);
end.</syntaxhighlight>
{{Output}}
<pre>
Sieving is done in 361 ms
Checking is done in 2 ms
Checking unsexy is done in 1 ms
Limit : 1000035
Primes 78500
[999961][999979][999983][1000003][1000033]
sexy prime pairs 16386
[999371 999377][999431 999437][999721 999727][999763 999769][999953 999959]
sexy prime triplets 2900
[997427 997433 997439][997541 997547 997553][998071 998077 998083][998617 998623 998629][998737 998743 998749]
sexy prime quadruplets 325
[977351 977357 977363 977369][983771 983777 983783 983789][986131 986137 986143 986149][990371 990377 990383 990389][997091 997097 997103 997109]
sexy prime quintuplet 1
[5 11 17 23 29]
 
48627 unsexy primes
the last 10 unsexy primes 999853,999863,999883,999907,999917,999931,999961,999979,999983,1000003
---
Sieving is done in 5248 ms
Checking is done in 1462 ms
Checking unsexy is done in 1062 ms
Limit : 1000000035
Primes 50847538
[999999937][1000000007][1000000009][1000000021][1000000033]
sexy prime pairs 6849047
[999999191 999999197][999999223 999999229][999999607 999999613][999999733 999999739][999999751 999999757]
sexy prime triplets 758163
[999990347 999990353 999990359][999993811 999993817 999993823][999994427 999994433 999994439][999994741 999994747 999994753][999996031 999996037 999996043]
sexy prime quadruplets 56643
[999835261 999835267 999835273 999835279][999864611 999864617 999864623 999864629][999874021 999874027 999874033 999874039][999890981 999890987 999890993 999890999][999956921 999956927 999956933 999956939]
sexy prime quintuplet 1
[5 11 17 23 29]
 
37907606 unsexy primes // = 50847538-2*6849047+758163-1
the last 10 unsexy primes 999999677,999999761,999999797,999999883,999999893,999999929,999999937,1000000007,1000000009,1000000021
</pre>
 
=={{header|Perl}}==
{{libheader|ntheory}}
We will use the prime iterator and primality test from the <code>ntheory</code> module.
<syntaxhighlight lang="perl">use ntheory qw/prime_iterator is_prime/;
 
sub tuple_tail {
my($n,$cnt,@array) = @_;
$n = @array if $n > @array;
my @tail;
for (1..$n) {
my $p = $array[-$n+$_-1];
push @tail, "(" . join(" ", map { $p+6*$_ } 0..$cnt-1) . ")";
}
return @tail;
}
 
sub comma {
(my $s = reverse shift) =~ s/(.{3})/$1,/g;
($s = reverse $s) =~ s/^,//;
return $s;
}
 
sub sexy_string { my $p = shift; is_prime($p+6) || is_prime($p-6) ? 'sexy' : 'unsexy' }
 
my $max = 1_000_035;
my $cmax = comma $max;
 
my $iter = prime_iterator;
my $p = $iter->();
my %primes;
push @{$primes{sexy_string($p)}}, $p;
while ( ($p = $iter->()) < $max) {
push @{$primes{sexy_string($p)}}, $p;
$p+ 6 < $max && is_prime($p+ 6) ? push @{$primes{'pair'}}, $p : next;
$p+12 < $max && is_prime($p+12) ? push @{$primes{'triplet'}}, $p : next;
$p+18 < $max && is_prime($p+18) ? push @{$primes{'quadruplet'}}, $p : next;
$p+24 < $max && is_prime($p+24) ? push @{$primes{'quintuplet'}}, $p : next;
}
 
print "Total primes less than $cmax: " . comma(@{$primes{'sexy'}} + @{$primes{'unsexy'}}) . "\n\n";
 
for (['pair', 2], ['triplet', 3], ['quadruplet', 4], ['quintuplet', 5]) {
my($sexy,$cnt) = @$_;
print "Number of sexy prime ${sexy}s less than $cmax: " . comma(scalar @{$primes{$sexy}}) . "\n";
print " Last 5 sexy prime ${sexy}s less than $cmax: " . join(' ', tuple_tail(5,$cnt,@{$primes{$sexy}})) . "\n";
print "\n";
}
 
print "Number of unsexy primes less than $cmax: ". comma(scalar @{$primes{unsexy}}) . "\n";
print " Last 10 unsexy primes less than $cmax: ". join(' ', @{$primes{unsexy}}[-10..-1]) . "\n";</syntaxhighlight>
{{out}}
<pre>Total primes less than 1,000,035: 78,500
 
Number of sexy prime pairs less than 1,000,035: 16,386
Last 5 sexy prime pairs less than 1,000,035: (999371 999377) (999431 999437) (999721 999727) (999763 999769) (999953 999959)
 
Number of sexy prime triplets less than 1,000,035: 2,900
Last 5 sexy prime triplets less than 1,000,035: (997427 997433 997439) (997541 997547 997553) (998071 998077 998083) (998617 998623 998629) (998737 998743 998749)
 
Number of sexy prime quadruplets less than 1,000,035: 325
Last 5 sexy prime quadruplets less than 1,000,035: (977351 977357 977363 977369) (983771 983777 983783 983789) (986131 986137 986143 986149) (990371 990377 990383 990389) (997091 997097 997103 997109)
 
Number of sexy prime quintuplets less than 1,000,035: 1
Last 5 sexy prime quintuplets less than 1,000,035: (5 11 17 23 29)
 
Number of unsexy primes less than 1,000,035: 48,627
Last 10 unsexy primes less than 1,000,035: 999853 999863 999883 999907 999917 999931 999961 999979 999983 1000003</pre>
 
===Using cluster sieve===
The <code>ntheory</code> module includes a function to do very efficient sieving for prime clusters. Even though we are doing repeated work for this task, it is still faster than the previous code. The helper subroutines and output code remain identical, as does the generated output.
 
The cluster sieve becomes more efficient as the number of terms increases. See for example [[oeis:a213646|OEIS Prime 11-tuplets]].
 
<syntaxhighlight lang="perl">use ntheory qw/sieve_prime_cluster forprimes is_prime/;
 
# ... identical helper functions
 
my %primes = (
sexy => [],
unsexy => [],
pair => [ sieve_prime_cluster(1, $max-1- 6, 6) ],
triplet => [ sieve_prime_cluster(1, $max-1-12, 6, 12) ],
quadruplet => [ sieve_prime_cluster(1, $max-1-18, 6, 12, 18) ],
quintuplet => [ sieve_prime_cluster(1, $max-1-24, 6, 12, 18, 24) ],
);
 
forprimes {
push @{$primes{sexy_string($_)}}, $_;
} $max-1;
 
# ... identical output code</syntaxhighlight>
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">function</span> <span style="color: #000000;">create_sieve</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">limit</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">sieve</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #004600;">true</span><span style="color: #0000FF;">,</span><span style="color: #000000;">limit</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">sieve</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #004600;">false</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">4</span> <span style="color: #008080;">to</span> <span style="color: #000000;">limit</span> <span style="color: #008080;">by</span> <span style="color: #000000;">2</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">sieve</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #004600;">false</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">p</span><span style="color: #0000FF;">=</span><span style="color: #000000;">3</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">sqrt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">limit</span><span style="color: #0000FF;">))</span> <span style="color: #008080;">by</span> <span style="color: #000000;">2</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">p2</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">p</span><span style="color: #0000FF;">*</span><span style="color: #000000;">p</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">sieve</span><span style="color: #0000FF;">[</span><span style="color: #000000;">p2</span><span style="color: #0000FF;">]</span> <span style="color: #008080;">then</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">k</span><span style="color: #0000FF;">=</span><span style="color: #000000;">p2</span> <span style="color: #008080;">to</span> <span style="color: #000000;">limit</span> <span style="color: #008080;">by</span> <span style="color: #000000;">p</span><span style="color: #0000FF;">*</span><span style="color: #000000;">2</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">sieve</span><span style="color: #0000FF;">[</span><span style="color: #000000;">k</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #004600;">false</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">sieve</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">lim</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1000035</span><span style="color: #0000FF;">,</span>
<span style="color: #000080;font-style:italic;">--constant lim = 100, -- (this works too)</span>
<span style="color: #000000;">limit</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">lim</span><span style="color: #0000FF;">-(</span><span style="color: #7060A8;">and_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">lim</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">),</span> <span style="color: #000080;font-style:italic;">-- (limit must be odd)</span>
<span style="color: #000000;">sieve</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">create_sieve</span><span style="color: #0000FF;">(</span><span style="color: #000000;">limit</span><span style="color: #0000FF;">+</span><span style="color: #000000;">6</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- (+6 to check for sexiness)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">sets</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">({},</span><span style="color: #000000;">5</span><span style="color: #0000FF;">),</span> <span style="color: #000080;font-style:italic;">-- (unsexy,pairs,trips,quads,quins)</span>
<span style="color: #000000;">limits</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">10</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">},</span>
<span style="color: #000000;">counts</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">&</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- (2 is an unsexy prime)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">total</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span> <span style="color: #000080;font-style:italic;">-- ""</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">limit</span> <span style="color: #008080;">to</span> <span style="color: #000000;">3</span> <span style="color: #008080;">by</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">2</span> <span style="color: #008080;">do</span> <span style="color: #000080;font-style:italic;">-- (this loop skips 2)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">sieve</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">total</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">sieve</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">+</span><span style="color: #000000;">6</span><span style="color: #0000FF;">]=</span><span style="color: #004600;">false</span> <span style="color: #008080;">and</span> <span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">-</span><span style="color: #000000;">6</span><span style="color: #0000FF;"><</span><span style="color: #000000;">0</span> <span style="color: #008080;">or</span> <span style="color: #000000;">sieve</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">-</span><span style="color: #000000;">6</span><span style="color: #0000FF;">]=</span><span style="color: #004600;">false</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">counts</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span> <span style="color: #000080;font-style:italic;">-- unsexy</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sets</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">])<</span><span style="color: #000000;">limits</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">sets</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">prepend</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sets</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">],</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">else</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">set</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">i</span><span style="color: #0000FF;">}</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</span><span style="color: #000000;">i</span><span style="color: #0000FF;">-</span><span style="color: #000000;">6</span> <span style="color: #008080;">to</span> <span style="color: #000000;">3</span> <span style="color: #008080;">by</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">6</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">j</span><span style="color: #0000FF;"><=</span><span style="color: #000000;">0</span> <span style="color: #008080;">or</span> <span style="color: #000000;">sieve</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]=</span><span style="color: #004600;">false</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">set</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">prepend</span><span style="color: #0000FF;">(</span><span style="color: #000000;">set</span><span style="color: #0000FF;">,</span><span style="color: #000000;">j</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">l</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">set</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sets</span><span style="color: #0000FF;">[</span><span style="color: #000000;">l</span><span style="color: #0000FF;">])<</span><span style="color: #000000;">limits</span><span style="color: #0000FF;">[</span><span style="color: #000000;">l</span><span style="color: #0000FF;">]</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">sets</span><span style="color: #0000FF;">[</span><span style="color: #000000;">l</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">prepend</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sets</span><span style="color: #0000FF;">[</span><span style="color: #000000;">l</span><span style="color: #0000FF;">],</span><span style="color: #000000;">set</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">counts</span><span style="color: #0000FF;">[</span><span style="color: #000000;">l</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sets</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">])<</span><span style="color: #000000;">limits</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">sets</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">prepend</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sets</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">],</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- (as 2 skipped above)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">fmt</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"""
Of %,d primes less than %,d there are:
%,d unsexy primes, the last %d being %s
%,d pairs, the last %d being %s
%,d triplets, the last %d being %s
%,d quadruplets, the last %d being %s
%,d quintuplet, the last %d being %s
"""</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">results</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">total</span><span style="color: #0000FF;">,</span><span style="color: #000000;">lim</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #008000;">""</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #008000;">""</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #008000;">""</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #008000;">""</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #008000;">""</span><span style="color: #0000FF;">}</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">5</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">results</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">*</span><span style="color: #000000;">3</span><span style="color: #0000FF;">..</span><span style="color: #000000;">i</span><span style="color: #0000FF;">*</span><span style="color: #000000;">3</span><span style="color: #0000FF;">+</span><span style="color: #000000;">2</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">counts</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sets</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]),</span><span style="color: #7060A8;">sprint</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sets</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])}</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">fmt</span><span style="color: #0000FF;">,</span><span style="color: #000000;">results</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Of 78,500 primes less than 1,000,035 there are:
48,627 unsexy primes, the last 10 being {999853,999863,999883,999907,999917,999931,999961,999979,999983,1000003}
16,386 pairs, the last 5 being {{999371,999377},{999431,999437},{999721,999727},{999763,999769},{999953,999959}}
2,900 triplets, the last 4 being {{997541,997547,997553},{998071,998077,998083},{998617,998623,998629},{998737,998743,998749}}
325 quadruplets, the last 3 being {{986131,986137,986143,986149},{990371,990377,990383,990389},{997091,997097,997103,997109}}
1 quintuplet, the last 1 being {{5,11,17,23,29}}
</pre>
 
=={{header|Prolog}}==
{{works with|SWI Prolog}}
<syntaxhighlight lang="prolog">sexy_prime_group(1, N, _, [N]):-
is_prime(N),
!.
sexy_prime_group(Size, N, Limit, [N|Group]):-
is_prime(N),
N1 is N + 6,
N1 =< Limit,
S1 is Size - 1,
sexy_prime_group(S1, N1, Limit, Group).
 
print_sexy_prime_groups(Size, Limit):-
findall(G, (is_prime(P), P =< Limit, sexy_prime_group(Size, P, Limit, G)), Groups),
length(Groups, Len),
writef('Number of groups of size %t is %t\n', [Size, Len]),
last_n(Groups, 5, Len, Last, Last_len),
writef('Last %t groups of size %t: %t\n\n', [Last_len, Size, Last]).
 
last_n([], _, L, [], L):-!.
last_n([_|List], Max, Length, Last, Last_len):-
Max < Length,
!,
Len1 is Length - 1,
last_n(List, Max, Len1, Last, Last_len).
last_n([E|List], Max, Length, [E|Last], Last_len):-
last_n(List, Max, Length, Last, Last_len).
 
unsexy(P):-
P1 is P + 6,
\+is_prime(P1),
P2 is P - 6,
\+is_prime(P2).
 
main(Limit):-
Max is Limit + 6,
find_prime_numbers(Max),
print_sexy_prime_groups(2, Limit),
print_sexy_prime_groups(3, Limit),
print_sexy_prime_groups(4, Limit),
print_sexy_prime_groups(5, Limit),
findall(P, (is_prime(P), P =< Limit, unsexy(P)), Unsexy),
length(Unsexy, Count),
writef('Number of unsexy primes is %t\n', [Count]),
last_n(Unsexy, 10, Count, Last10, _),
writef('Last 10 unsexy primes: %t', [Last10]).
 
main:-
main(1000035).</syntaxhighlight>
 
Module for finding prime numbers up to some limit:
<syntaxhighlight lang="prolog">:- module(prime_numbers, [find_prime_numbers/1, is_prime/1]).
:- dynamic is_prime/1.
 
find_prime_numbers(N):-
retractall(is_prime(_)),
assertz(is_prime(2)),
init_sieve(N, 3),
sieve(N, 3).
 
init_sieve(N, P):-
P > N,
!.
init_sieve(N, P):-
assertz(is_prime(P)),
Q is P + 2,
init_sieve(N, Q).
 
sieve(N, P):-
P * P > N,
!.
sieve(N, P):-
is_prime(P),
!,
S is P * P,
cross_out(S, N, P),
Q is P + 2,
sieve(N, Q).
sieve(N, P):-
Q is P + 2,
sieve(N, Q).
 
cross_out(S, N, _):-
S > N,
!.
cross_out(S, N, P):-
retract(is_prime(S)),
!,
Q is S + 2 * P,
cross_out(Q, N, P).
cross_out(S, N, P):-
Q is S + 2 * P,
cross_out(Q, N, P).</syntaxhighlight>
 
{{out}}
<pre>
Number of groups of size 2 is 16386
Last 5 groups of size 2: [[999371,999377],[999431,999437],[999721,999727],[999763,999769],[999953,999959]]
 
Number of groups of size 3 is 2900
Last 5 groups of size 3: [[997427,997433,997439],[997541,997547,997553],[998071,998077,998083],[998617,998623,998629],[998737,998743,998749]]
 
Number of groups of size 4 is 325
Last 5 groups of size 4: [[977351,977357,977363,977369],[983771,983777,983783,983789],[986131,986137,986143,986149],[990371,990377,990383,990389],[997091,997097,997103,997109]]
 
Number of groups of size 5 is 1
Last 1 groups of size 5: [[5,11,17,23,29]]
 
Number of unsexy primes is 48627
Last 10 unsexy primes: [999853,999863,999883,999907,999917,999931,999961,999979,999983,1000003]
</pre>
 
=={{header|PureBasic}}==
<syntaxhighlight lang="purebasic">DisableDebugger
EnableExplicit
 
#LIM=1000035
 
Macro six(mul)
6*mul
EndMacro
 
Macro form(n)
RSet(Str(n),8)
EndMacro
 
Macro put(m,g,n)
PrintN(Str(m)+" "+g)
PrintN(n)
EndMacro
 
Define c1.i=2,c2.i,c3.i,c4.i,c5.i,t1$,t2$,t3$,t4$,t5$,i.i,j.i
 
Global Dim soe.b(#LIM)
FillMemory(@soe(0),#LIM,#True,#PB_Byte)
If Not OpenConsole("")
End 1
EndIf
 
For i=2 To Sqr(#LIM)
If soe(i)=#True
j=i*i
While j<=#LIM
soe(j)=#False
j+i
Wend
EndIf
Next
 
Procedure.s formtab(t$,l.i)
If CountString(t$,~"\n")>l
t$=Mid(t$,FindString(t$,~"\n")+1)
EndIf
ProcedureReturn t$
EndProcedure
 
For i=3 To #LIM Step 2
If i>5 And i<#LIM-6 And soe(i)&~(soe(i-six(1))|soe(i+six(1)))
c1+1
t1$+form(i)+~"\n"
t1$=formtab(t1$,10)
Continue
EndIf
If i<#LIM-six(1) And soe(i)&soe(i+six(1))
c2+1
t2$+form(i)+form(i+six(1))+~"\n"
t2$=formtab(t2$,5)
EndIf
If i<#LIM-six(2) And soe(i)&soe(i+six(1))&soe(i+six(2))
c3+1
t3$+form(i)+form(i+six(1))+form(i+six(2))+~"\n"
t3$=formtab(t3$,5)
EndIf
If i<#LIM-six(3) And soe(i)&soe(i+six(1))&soe(i+six(2))&soe(i+six(3))
c4+1
t4$+form(i)+form(i+six(1))+form(i+six(2))+form(i+six(3))+~"\n"
t4$=formtab(t4$,5)
EndIf
If i<#LIM-six(4) And soe(i)&soe(i+six(1))&soe(i+six(2))&soe(i+six(3))&soe(i+six(4))
c5+1
t5$+form(i)+form(i+six(1))+form(i+six(2))+form(i+six(3))+form(i+six(4))+~"\n"
t5$=formtab(t5$,5)
EndIf
Next
 
put(c2,"pairs ending with ...",t2$)
put(c3,"triplets ending with ...",t3$)
put(c4,"quadruplets ending with ...",t4$)
put(c5,"quintuplets ending with ...",t5$)
put(c1,"unsexy primes ending with ...",t1$)
 
Input()</syntaxhighlight>
{{out}}
<pre>16386 pairs ending with ...
999371 999377
999431 999437
999721 999727
999763 999769
999953 999959
 
2900 triplets ending with ...
997427 997433 997439
997541 997547 997553
998071 998077 998083
998617 998623 998629
998737 998743 998749
 
325 quadruplets ending with ...
977351 977357 977363 977369
983771 983777 983783 983789
986131 986137 986143 986149
990371 990377 990383 990389
997091 997097 997103 997109
 
1 quintuplets ending with ...
5 11 17 23 29
 
48627 unsexy primes ending with ...
999853
999863
999883
999907
999917
999931
999961
999979
999983
1000003
</pre>
 
=={{header|Python}}==
===Imperative Style===
<lang python>LIMIT = 1_000_000
<syntaxhighlight lang="python">LIMIT = 1_000_035
def primes2(limit=LIMIT):
if limit < 2: return []
Line 285 ⟶ 2,656:
return [2] + [i + i + 3 for i, v in enumerate(buf) if v]
 
primes = primes2(LIMIT +6)
primeset = set(primes)
primearray = [n in primeset for n in range(LIMIT)]
 
#%%
s = [[] for x in range(4)]
unsexy = []
 
for p in primes:
if p +> 6 in primesetLIMIT:
break
if p + 6 in primeset and p + 6 < LIMIT:
s[0].append((p, p+6))
elif p + 6 in primeset:
break
else:
if p - 6 not in primeset:
unsexy.append(p)
continue
if p + 12 in primeset and p + 12 < LIMIT:
s[1].append((p, p+6, p+12))
else:
continue
if p + 18 in primeset and p + 18 < LIMIT:
s[2].append((p, p+6, p+12, p+18))
else:
continue
if p + 24 in primeset and p + 24 < LIMIT:
s[3].append((p, p+6, p+12, p+18, p+24))
 
#%%
print('"SEXY" PRIME GROUPINGS:')
for sexy, name in zip(s, 'pairs triplets quadruplets quintuplets'.split()):
print(f' {len(sexy)} {name}na ending(not withisPrime(n-6))))) |> Array...')ofSeq
printfn "There are %d unsexy primes less than 1,000,035. The last 10 are:" n.Length
Array.skip (n.Length-10) n |> Array.iter(fun n->printf "%d " n); printfn ""
let ni=pCache |> Seq.takeWhile(fun n->nme} ending with ...')
for sx in sexy[-5:]:
print(' ',sx)
Line 316 ⟶ 2,698:
print(f'\nThere are {len(unsexy)} unsexy primes ending with ...')
for usx in unsexy[-10:]:
print(' ',usx)</langsyntaxhighlight>
 
{{out}}
Line 341 ⟶ 2,723:
(5, 11, 17, 23, 29)
 
There are 4862648627 unsexy primes ending with ...
999809
999853
999863
Line 351 ⟶ 2,732:
999961
999979
999983</pre>
1000003</pre>
 
===Functional style===
{{trans|FSharp}}
This task uses [[Extensible_prime_generator#210-wheel_postponed_incremental_sieve]]
<syntaxhighlight lang="python">
#Functional Sexy Primes. Nigel Galloway: October 5th., 2018
from itertools import *
z=primes()
n=frozenset(takewhile(lambda x: x<1000035,z))
ni=sorted(list(filter(lambda g: n.__contains__(g+6) ,n)))
print ("There are",len(ni),"sexy prime pairs all components of which are less than 1,000,035. The last 5 are:")
for g in islice(ni,max(len(ni)-5,0),len(ni)): print(format("(%d,%d) " % (g,g+6)))
nig=list(filter(lambda g: n.__contains__(g+12) ,ni))
print ("There are",len(nig),"sexy prime triplets all components of which are less than 1,000,035. The last 5 are:")
for g in islice(nig,max(len(nig)-5,0),len(nig)): print(format("(%d,%d,%d) " % (g,g+6,g+12)))
nige=list(filter(lambda g: n.__contains__(g+18) ,nig))
print ("There are",len(nige),"sexy prime quadruplets all components of which are less than 1,000,035. The last 5 are:")
for g in islice(nige,max(len(nige)-5,0),len(nige)): print(format("(%d,%d,%d,%d) " % (g,g+6,g+12,g+18)))
nigel=list(filter(lambda g: n.__contains__(g+24) ,nige))
print ("There are",len(nigel),"sexy prime quintuplets all components of which are less than 1,000,035. The last 5 are:")
for g in islice(nigel,max(len(nigel)-5,0),len(nigel)): print(format("(%d,%d,%d,%d,%d) " % (g,g+6,g+12,g+18,g+24)))
un=frozenset(takewhile(lambda x: x<1000050,z)).union(n)
unsexy=sorted(list(filter(lambda g: not un.__contains__(g+6) and not un.__contains__(g-6),n)))
print ("There are",len(unsexy),"unsexy primes less than 1,000,035. The last 10 are:")
for g in islice(unsexy,max(len(unsexy)-10,0),len(unsexy)): print(g)
</syntaxhighlight>
{{out}}
<pre>
There are 16386 sexy prime pairs all components of which are less than 1,000,035. The last 5 are:
(999371,999377)
(999431,999437)
(999721,999727)
(999763,999769)
(999953,999959)
There are 2900 sexy prime triplets all components of which are less than 1,000,035. The last 5 are:
(997427,997433,997439)
(997541,997547,997553)
(998071,998077,998083)
(998617,998623,998629)
(998737,998743,998749)
There are 325 sexy prime quadruplets all components of which are less than 1,000,035. The last 5 are:
(977351,977357,977363,977369)
(983771,983777,983783,983789)
(986131,986137,986143,986149)
(990371,990377,990383,990389)
(997091,997097,997103,997109)
There are 1 sexy prime quintuplets all components of which are less than 1,000,035. The last 5 are:
(5,11,17,23,29)
There are 48627 unsexy primes less than 1,000,035. The last 10 are:
999853
999863
999883
999907
999917
999931
999961
999979
999983
1000003
</pre>
 
=={{header|Quackery}}==
 
<code>eratosthenes</code> and <code>primes</code> are defined at [[Sieve of Eratosthenes#Quackery]].
 
<syntaxhighlight lang="Quackery"> 1000035 eratosthenes
 
[ stack ] is pairs ( --> s )
[ stack ] is trips ( --> s )
[ stack ] is quads ( --> s )
[ stack ] is quins ( --> s )
[ stack ] is unsexy ( --> s )
 
[ share swap bit & 0 != ] is in ( s n --> b )
 
primes share dup
' [ pairs trips quads quins ]
witheach
[ dip [ dip dup 6 >> & dup ] put ]
2drop
 
pairs share
dup 6 << | ~
primes share &
unsexy put
 
' [ pairs trips quads quins ]
witheach
[ temp put
[] 1000035 times
[ i^ temp share in if
[ i^ join ] ]
dup size echo sp
-5 split echo drop cr
temp release ]
cr
[] 1000035 6 - times
[ i^ unsexy in if
[ i^ join ] ]
dup size echo sp
-10 split echo drop cr</syntaxhighlight>
 
{{out}}
 
<pre>16386 [ 999371 999431 999721 999763 999953 ]
2900 [ 997427 997541 998071 998617 998737 ]
325 [ 977351 983771 986131 990371 997091 ]
1 [ 5 ]
 
48627 [ 999853 999863 999883 999907 999917 999931 999961 999979 999983 1000003 ]
</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2018.08}}
 
<syntaxhighlight lang="raku" line>use Math::Primesieve;
my $sieve = Math::Primesieve.new;
 
my $max = 1_000_035;
my @primes = $sieve.primes($max);
 
my $filter = @primes.Set;
my $primes = @primes.categorize: &sexy;
 
say "Total primes less than {comma $max}: ", comma +@primes;
 
for <pair 2 triplet 3 quadruplet 4 quintuplet 5> -> $sexy, $cnt {
say "Number of sexy prime {$sexy}s less than {comma $max}: ", comma +$primes{$sexy};
say " Last 5 sexy prime {$sexy}s less than {comma $max}: ",
join ' ', $primes{$sexy}.tail(5).grep(*.defined).map:
{ "({ $_ «+« (0,6 … 24)[^$cnt] })" }
say '';
}
 
say "Number of unsexy primes less than {comma $max}: ", comma +$primes<unsexy>;
say " Last 10 unsexy primes less than {comma $max}: ", $primes<unsexy>.tail(10);
 
sub sexy ($i) {
gather {
take 'quintuplet' if all($filter{$i «+« (6,12,18,24)});
take 'quadruplet' if all($filter{$i «+« (6,12,18)});
take 'triplet' if all($filter{$i «+« (6,12)});
take 'pair' if $filter{$i + 6};
take (($i >= $max - 6) && ($i + 6).is-prime) ||
(so any($filter{$i «+« (6, -6)})) ?? 'sexy' !! 'unsexy';
}
}
 
sub comma { $^i.flip.comb(3).join(',').flip }</syntaxhighlight>
{{out}}
<pre>Total primes less than 1,000,035: 78,500
Number of sexy prime pairs less than 1,000,035: 16,386
Last 5 sexy prime pairs less than 1,000,035: (999371 999377) (999431 999437) (999721 999727) (999763 999769) (999953 999959)
 
Number of sexy prime triplets less than 1,000,035: 2,900
Last 5 sexy prime triplets less than 1,000,035: (997427 997433 997439) (997541 997547 997553) (998071 998077 998083) (998617 998623 998629) (998737 998743 998749)
 
Number of sexy prime quadruplets less than 1,000,035: 325
Last 5 sexy prime quadruplets less than 1,000,035: (977351 977357 977363 977369) (983771 983777 983783 983789) (986131 986137 986143 986149) (990371 990377 990383 990389) (997091 997097 997103 997109)
 
Number of sexy prime quintuplets less than 1,000,035: 1
Last 5 sexy prime quintuplets less than 1,000,035: (5 11 17 23 29)
 
Number of unsexy primes less than 1,000,035: 48,627
Last 10 unsexy primes less than 1,000,035: (999853 999863 999883 999907 999917 999931 999961 999979 999983 1000003)</pre>
 
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">/*REXX program finds and displays various kinds of sexy and unsexy primes less than N.*/
parse arg N endU end2 end3 end4 end5 . /*obtain optional argument from the CL.*/
if N=='' | N=="," then N= 10000001000035 - 1 /*Not specified? Then use the default.*/
if endU=='' | endU=="," then endU= 10 /* " " " " " " */
if end2=='' | end2=="," then end2= 5 /* " " " " " " */
Line 362 ⟶ 2,910:
if end4=='' | end4=="," then end4= 5 /* " " " " " " */
if end5=='' | end5=="," then end4= 5 /* " " " " " " */
@.=.;call genSq s.=0; #=0; !.=0 /*countgen ofsome primessquares (sofor far);the setDO k=7 prime#.UNTIL*/
ifcall genPx N>1 then do; #=1; @.1=2; !.2=1; end /*a count" ofprime the(@.) primes& foundsexy (soprime far)(X.) array*/
call genXU /*gen lists, types of sexy Ps, unsexy P*/
 
call getXs do j=3 by 2 to N+6 /*start in the cellar and/*gen lists, worklast up.# of types of sexy Ps*/
@sexy= ' sexy prime' /*a handy literal for some of the SAYs.*/
if j<19 then if wordpos(j, '3 5 7 11 13 17')==0 then iterate
w2= words( translate(x2,, '~') ); y2= words(x2) /*count #primes in the sexy pairs. */
else do; #= #+1; @.#= j; !.j= 1
w3= words( translate(x3,, '~') ); y3= words(x3) /* " " " " " " b= j-6; if !triplets.b then s.b= 1*/
w4= words( translate(x4,, '~') ); y4= words(x4) /* " " " " " " iteratequadruplets*/
w5= words( translate(x5,, '~') ); y5= words(x5) /* " " " " " " endquintuplets*/
if j// 3 ==0 then iterate /* ··· and eliminate the triples. */
parse var j '' -1 _ /* obtain the rightmost digit.*/
if _ ==5 then iterate /* ··· and eliminate the nickels. */
if j// 7 ==0 then iterate /* ··· and eliminate the luckies. */
do k=11 by 6 while k*k<=j /*this skips odd multiples of three. */
if j//k ==0 then iterate j /*perform a divide (modulus), */
if j//(k+2)==0 then iterate j /* ··· and the next also. ___ */
end /*k*/ /*divide up through the √ J */
if j<=N then do; #= #+1; @.#= j; !.j= 1 /*bump prime counter; assign prime to @*/
end /* [+] also, assign prime# to unity. */
!.j= 1 /*assign Jth number as being prime. */
b= j - 6 /*B: is the lower part of a sexy prime*/
if !.b then do; s.b=1; if j<=N then s.j=1 /*assign (maybe both) sexy primes. */
end /* [↑] is this part of a sexy prime ? */
end /*j*/
u= 2 /*the first unsafe sexy prime. */
Nc= commas(N+1)
say 'There are ' commas(#) " primes less than " Nc
s=
do k=2 for #-1; p= @.k
if s.p then s= s p
else u= u p
end /*k*/
say
uu= words(u)
s1= words(s)
s2= /* [↓] build sexy prime pairs. */
do k=2 for #-1; p= @.k; if \s.p then iterate
b= p - 6; if \s.b then iterate
s2= s2 b'~'p
end /*k*/
s3= /* [↓] build sexy prime triplets. */
do k=2 for #-1; p= @.k; if \s.p then iterate
b= p - 6; if \s.b then iterate
t= p - 12; if \s.t then iterate
s3= s3 t'~' || b"~"p
end /*k*/
s4= /* [↓] build sexy prime quadruplets. */
do k=2 for #-1; p= @.k; if \s.p then iterate
b= p - 6; if \s.b then iterate
t= p - 12; if \s.t then iterate
q= p - 18; if \s.q then iterate
s4= s4 q'~'t"~" || b'~'p
end /*k*/
s5= /* [↓] build sexy prime quintuplets. */
do k=2 for #-1; p= @.k; if \s.p then iterate
b= p - 6; if \s.b then iterate
t= p - 12; if \s.t then iterate
q= p - 18; if \s.q then iterate
v= p - 24; if \s.v then iterate
s5= s5 v'~'q"~"t'~' || b"~"p
end /*k*/
@sexy= ' sexy prime' /*handy literal for SAYs.*/
w2= words( translate(s2,, '~') ); y2= words(s2) /*count # primes in the sexy pairs. */
w3= words( translate(s3,, '~') ); y3= words(s3) /* " " " " " " triplets. */
w4= words( translate(s4,, '~') ); y4= words(s4) /* " " " " " " quads. */
w5= words( translate(s5,, '~') ); y5= words(s5) /* " " " " " " quints. */
say 'There are ' commas(w2%2) @sexy "pairs less than " Nc
say 'The last ' commas(end2) @sexy "pairs are:"; say subword(s2x2, max(1,y2-end2+1))
say
say 'There are ' commas(w3%3) @sexy "triplets less than " Nc
say 'The last ' commas(end3) @sexy "triplets are:"; say subword(s3x3, max(1,y3-end3+1))
say
say 'There are ' commas(w4%4) @sexy "quadruplets less than " Nc
say 'The last ' commas(end4) @sexy "quadruplets are:"; say subword(s4x4, max(1,y4-end4+1))
say
say 'There areis ' commas(w5%5) @sexy "quintupletsquintuplet less than " Nc
say 'The last ' commas(end4) @sexy "quintupletsquintuplet are:"; say subword(s5x5, max(1,y5-end4+1))
say
say 'There are ' commas(s1) " sexy primes less than " sexy primes less than " Nc
say 'There are ' commas(uuu1) " unsexy primes less than " unsexy primes less than " Nc
say 'The last ' commas(endU) " unsexy primes are: " " unsexy primes are: " subword(u, max(1,uuu1-endU+1))
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
commas: procedure; parse arg _; n= _'.9'; #= 123456789; b= verify(n, #, "M")
e= verify(n, #'0', , verify(n, #"0.", 'M') ) - 4
do j=e to b by -3; _= insert(',', _, j); end /*j*/; return _</lang>
/*──────────────────────────────────────────────────────────────────────────────────────*/
genSQ: do i=17 by 2 until i**2 > N+7; s.i= i**2; end; return /*S used for square roots*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
genPx: @.=; #= 0; !.= 0. /*P array; P count; sexy P array*/
if N>1 then do; #= 1; @.1= 2; !.2= 1; end /*count of primes found (so far)*/
x.=!.; LPs=3 5 7 11 13 17 /*sexy prime array; low P list.*/
do j=3 by 2 to N+6 /*start in the cellar & work up.*/
if j<19 then if wordpos(j, LPs)==0 then iterate
else do; #= #+1; @.#= j; !.j= 1; b= j - 6
if !.b then x.b= 1; iterate
end
if j// 3 ==0 then iterate /* ··· and eliminate multiples of 3.*/
parse var j '' -1 _ /* get the rightmost digit of J. */
if _ ==5 then iterate /* ··· and eliminate multiples of 5.*/
if j// 7 ==0 then iterate /* ··· " " " " 7.*/
if j//11 ==0 then iterate /* ··· " " " " 11.*/
if j//13 ==0 then iterate /* ··· " " " " 13.*/
do k=7 until s._ > j; _= @.k /*÷ by primes starting at 7th prime. */
if j // _ == 0 then iterate j /*get the remainder of j÷@.k ___ */
end /*k*/ /*divide up through & including √ J */
if j<=N then do; #= #+1; @.#= j; end /*bump P counter; assign prime to @.*/
!.j= 1 /*define Jth number as being prime.*/
b= j - 6 /*B: lower part of a sexy prime pair?*/
if !.b then do; x.b=1; if j<=N then x.j=1; end /*assign (both parts ?) sexy Ps.*/
end /*j*/; return
/*──────────────────────────────────────────────────────────────────────────────────────*/
genXU: u= 2; Nc=commas(N+1); s= /*1st unsexy prime; add commas to N+1*/
say 'There are ' commas(#) " primes less than " Nc; say
do k=2 for #-1; p= @.k; if x.p then s=s p /*if sexy prime, add it to list*/
else u= u p /* " unsexy " " " " " */
end /*k*/ /* [↑] traispe through odd Ps. */
s1= words(s); u1= words(u); return /*# of sexy primes; # unsexy primes.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
getXs: x2=; do k=2 for #-1; p=@.k; if \x.p then iterate /*build sexy prime list. */
b=p- 6; if \x.b then iterate; x2=x2 b'~'p
end /*k*/
x3=; do k=2 for #-1; p=@.k; if \x.p then iterate /*build sexy P triplets. */
b=p- 6; if \x.b then iterate
t=p-12; if \x.t then iterate; x3=x3 t'~' || b"~"p
end /*k*/
x4=; do k=2 for #-1; p=@.k; if \x.p then iterate /*build sexy P quads. */
b=p- 6; if \x.b then iterate
t=p-12; if \x.t then iterate
q=p-18; if \x.q then iterate; x4=x4 q'~'t"~" || b'~'p
end /*k*/
x5=; do k=2 for #-1; p=@.k; if \x.p then iterate /*build sexy P quints. */
b=p- 6; if \x.b then iterate
t=p-12; if \x.t then iterate
q=p-18; if \x.q then iterate
v=p-24; if \x.v then iterate; x5=x5 v'~'q"~"t'~' || b"~"p
end /*k*/; return</syntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
 
(Shown at &nbsp; <big>'''<sup>5</sup>/<sub>6</sub>'''</big> &nbsp; size.)
<pre style="font-size:83%">
There are 78,498500 primes less than 1,000,000035
 
There are 16,386 sexy prime pairs less than 1,000,000035
The last 5 sexy prime pairs are:
999371~999377 999431~999437 999721~999727 999763~999769 999953~999959
 
There are 2,900 sexy prime triplets less than 1,000,000035
The last 5 sexy prime triplets are:
997427~997433~997439 997541~997547~997553 998071~998077~998083 998617~998623~998629 998737~998743~998749
 
There are 325 sexy prime quadruplets less than 1,000,000035
The last 5 sexy prime quadruplets are:
977351~977357~977363~977369 983771~983777~983783~983789 986131~986137~986143~986149 990371~990377~990383~990389 997091~997097~997103~997109
 
There areis 1 sexy prime quintupletsquintuplet less than 1,000,000035
The last 5 sexy prime quintupletsquintuplet are:
5~11~17~23~29
 
There are 29,872873 sexy primes less than 1,000,000035
There are 48,626627 unsexy primes less than 1,000,000035
The last 10 unsexy primes are: 999809 999853 999863 999883 999907 999917 999931 999961 999979 999983 1000003
</pre>
 
=={{header|Ring}}==
{{Improve|Ring|Does not even ''attempt'' to fulfil the task requirements and has no explanation as to why not}}
<syntaxhighlight lang="ring">
load "stdlib.ring"
 
primes = []
for n = 1 to 100
if isprime(n)
add(primes,n)
ok
next
 
see "Sexy prime pairs under 100:" + nl + nl
for n = 1 to len(primes)-1
for m = n + 1 to len(primes)
if primes[m] - primes[n] = 6
see "(" + primes[n] + " " + primes[m] + ")" + nl
ok
next
next
see nl
 
see "Sexy prime triplets under 100:" + nl +nl
for n = 1 to len(primes)-2
for m = n + 1 to len(primes)-1
for x = m + 1 to len(primes)
bool1 = (primes[m] - primes[n] = 6)
bool2 = (primes[x] - primes[m] = 6)
bool = bool1 and bool2
if bool
see "(" + primes[n] + " " + primes[m] + " " + primes[x] + ")" + nl
ok
next
next
next
see nl
 
see "Sexy prime quadruplets under 100:" + nl + nl
for n = 1 to len(primes)-3
for m = n + 1 to len(primes)-2
for x = m + 1 to len(primes)-1
for y = m + 1 to len(primes)
bool1 = (primes[m] - primes[n] = 6)
bool2 = (primes[x] - primes[m] = 6)
bool3 = (primes[y] - primes[x] = 6)
bool = bool1 and bool2 and bool3
if bool
see "(" + primes[n] + " " + primes[m] + " " + primes[x] + " " + primes[y] + ")" + nl
ok
next
next
next
next
see nl
 
see "Sexy prime quintuplets under 100:" + nl + nl
for n = 1 to len(primes)-4
for m = n + 1 to len(primes)-3
for x = m + 1 to len(primes)-2
for y = m + 1 to len(primes)-1
for z = y + 1 to len(primes)
bool1 = (primes[m] - primes[n] = 6)
bool2 = (primes[x] - primes[m] = 6)
bool3 = (primes[y] - primes[x] = 6)
bool4 = (primes[z] - primes[y] = 6)
bool = bool1 and bool2 and bool3 and bool4
if bool
see "(" + primes[n] + " " + primes[m] + " " + primes[x] + " " +
primes[y] + " " + primes[z] + ")" + nl
ok
next
next
next
next
next
</syntaxhighlight>
Output:
<pre>
Sexy prime pairs under 100:
 
(5 11)
(7 13)
(11 17)
(13 19)
(17 23)
(23 29)
(31 37)
(37 43)
(41 47)
(47 53)
(53 59)
(61 67)
(67 73)
(73 79)
(83 89)
 
Sexy prime triplets under 100:
 
(5 11 17)
(7 13 19)
(11 17 23)
(17 23 29)
(31 37 43)
(41 47 53)
(47 53 59)
(61 67 73)
(67 73 79)
 
Sexy prime quadruplets under 100:
 
(5 11 17 23)
(11 17 23 29)
(41 47 53 59)
(61 67 73 79)
 
Sexy prime quintuplets under 100:
 
(5 11 17 23 29)
</pre>
 
=={{header|Ruby}}==
<syntaxhighlight lang="ruby">
require 'prime'
 
prime_array, sppair2, sppair3, sppair4, sppair5 = Array.new(5) {Array.new()} # arrays for prime numbers and index number to array for each pair.
unsexy, i, start = [2], 0, Time.now
Prime.each(1_000_100) {|prime| prime_array.push prime}
 
while prime_array[i] < 1_000_035
i+=1
unsexy.push(i) if prime_array[(i+1)..(i+2)].include?(prime_array[i]+6) == false && prime_array[(i-2)..(i-1)].include?(prime_array[i]-6) == false && prime_array[i]+6 < 1_000_035
prime_array[(i+1)..(i+4)].include?(prime_array[i]+6) && prime_array[i]+6 < 1_000_035 ? sppair2.push(i) : next
prime_array[(i+2)..(i+5)].include?(prime_array[i]+12) && prime_array[i]+12 < 1_000_035 ? sppair3.push(i) : next
prime_array[(i+3)..(i+6)].include?(prime_array[i]+18) && prime_array[i]+18 < 1_000_035 ? sppair4.push(i) : next
prime_array[(i+4)..(i+7)].include?(prime_array[i]+24) && prime_array[i]+24 < 1_000_035 ? sppair5.push(i) : next
end
 
puts "\nSexy prime pairs: #{sppair2.size} found:"
sppair2.last(5).each {|prime| print [prime_array[prime], prime_array[prime]+6].join(" - "), "\n"}
puts "\nSexy prime triplets: #{sppair3.size} found:"
sppair3.last(5).each {|prime| print [prime_array[prime], prime_array[prime]+6, prime_array[prime]+12].join(" - "), "\n"}
puts "\nSexy prime quadruplets: #{sppair4.size} found:"
sppair4.last(5).each {|prime| print [prime_array[prime], prime_array[prime]+6, prime_array[prime]+12, prime_array[prime]+18].join(" - "), "\n"}
puts "\nSexy prime quintuplets: #{sppair5.size} found:"
sppair5.last(5).each {|prime| print [prime_array[prime], prime_array[prime]+6, prime_array[prime]+12, prime_array[prime]+18, prime_array[prime]+24].join(" - "), "\n"}
 
puts "\nUnSexy prime: #{unsexy.size} found. Last 10 are:"
unsexy.last(10).each {|item| print prime_array[item], " "}
print "\n\n", Time.now - start, " seconds"
</syntaxhighlight>
 
Output:
<pre>
ruby 2.5.3p105 (2018-10-18 revision 65156) [x64-mingw32]
 
 
Sexy prime pairs: 16386 found:
999371 - 999377
999431 - 999437
999721 - 999727
999763 - 999769
999953 - 999959
 
Sexy prime triplets: 2900 found:
997427 - 997433 - 997439
997541 - 997547 - 997553
998071 - 998077 - 998083
998617 - 998623 - 998629
998737 - 998743 - 998749
 
Sexy prime quadruplets: 325 found:
977351 - 977357 - 977363 - 977369
983771 - 983777 - 983783 - 983789
986131 - 986137 - 986143 - 986149
990371 - 990377 - 990383 - 990389
997091 - 997097 - 997103 - 997109
 
Sexy prime quintuplets: 1 found:
5 - 11 - 17 - 23 - 29
 
UnSexy prime: 48627 found. Last 10 are:
999853 999863 999883 999907 999917 999931 999961 999979 999983 1000003
 
0.176955 seconds
</pre>
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">// [dependencies]
// primal = "0.2"
// circular-queue = "0.2.5"
 
use circular_queue::CircularQueue;
 
fn main() {
let max = 1000035;
let max_group_size = 5;
let diff = 6;
let max_groups = 5;
let max_unsexy = 10;
 
let sieve = primal::Sieve::new(max + diff);
let mut group_count = vec![0; max_group_size];
let mut unsexy_count = 0;
let mut groups = Vec::new();
let mut unsexy_primes = CircularQueue::with_capacity(max_unsexy);
 
for _ in 0..max_group_size {
groups.push(CircularQueue::with_capacity(max_groups));
}
 
for p in sieve.primes_from(2).take_while(|x| *x < max) {
if !sieve.is_prime(p + diff) && (p < diff + 2 || !sieve.is_prime(p - diff)) {
unsexy_count += 1;
unsexy_primes.push(p);
} else {
let mut group = Vec::new();
group.push(p);
for group_size in 1..max_group_size {
let next = p + group_size * diff;
if next >= max || !sieve.is_prime(next) {
break;
}
group.push(next);
group_count[group_size] += 1;
groups[group_size].push(group.clone());
}
}
}
 
for size in 1..max_group_size {
println!(
"Number of groups of size {} is {}",
size + 1,
group_count[size]
);
println!("Last {} groups of size {}:", groups[size].len(), size + 1);
println!(
"{}\n",
groups[size]
.asc_iter()
.map(|g| format!("({})", to_string(&mut g.iter())))
.collect::<Vec<String>>()
.join(", ")
);
}
println!("Number of unsexy primes is {}", unsexy_count);
println!("Last {} unsexy primes:", unsexy_primes.len());
println!("{}", to_string(&mut unsexy_primes.asc_iter()));
}
 
fn to_string<T: ToString>(iter: &mut dyn std::iter::Iterator<Item = T>) -> String {
iter.map(|n| n.to_string())
.collect::<Vec<String>>()
.join(", ")
}</syntaxhighlight>
 
{{out}}
<pre>
Number of groups of size 2 is 16386
Last 5 groups of size 2:
(999371, 999377), (999431, 999437), (999721, 999727), (999763, 999769), (999953, 999959)
 
Number of groups of size 3 is 2900
Last 5 groups of size 3:
(997427, 997433, 997439), (997541, 997547, 997553), (998071, 998077, 998083), (998617, 998623, 998629), (998737, 998743, 998749)
 
Number of groups of size 4 is 325
Last 5 groups of size 4:
(977351, 977357, 977363, 977369), (983771, 983777, 983783, 983789), (986131, 986137, 986143, 986149), (990371, 990377, 990383, 990389), (997091, 997097, 997103, 997109)
 
Number of groups of size 5 is 1
Last 1 groups of size 5:
(5, 11, 17, 23, 29)
 
Number of unsexy primes is 48627
Last 10 unsexy primes:
999853, 999863, 999883, 999907, 999917, 999931, 999961, 999979, 999983, 1000003
</pre>
 
=={{header|Scala}}==
<syntaxhighlight lang="scala">/* We could reduce the number of functions through a polymorphism since we're trying to retrieve sexy N-tuples (pairs, triplets etc...)
but one practical solution would be to use the Shapeless library for this purpose; here we only use built-in Scala packages. */
 
object SexyPrimes {
 
/** Check if an input number is prime or not*/
def isPrime(n: Int): Boolean = ! ((2 until n-1) exists (n % _ == 0)) && n > 1
 
/** Retrieve pairs of sexy primes given a list of Integers*/
def getSexyPrimesPairs (primes : List[Int]) = {
primes
.map(n => if(primes.contains(n+6)) (n, n+6))
.filter(p => p != ())
.map{ case (a,b) => (a.toString.toInt, b.toString.toInt)}
}
 
/** Retrieve triplets of sexy primes given a list of Integers*/
def getSexyPrimesTriplets (primes : List[Int]) = {
primes
.map(n => if(
primes.contains(n+6) && primes.contains(n+12))
(n, n+6, n+12)
)
.filter(p => p != ())
.map{ case (a,b,c) => (a.toString.toInt, b.toString.toInt, c.toString.toInt)}
}
 
/** Retrieve quadruplets of sexy primes given a list of Integers*/
def getSexyPrimesQuadruplets (primes : List[Int]) = {
primes
.map(n => if(
primes.contains(n+6) && primes.contains(n+12) && primes.contains(n+18))
(n, n+6, n+12, n+18)
)
.filter(p => p != ())
.map{ case (a,b,c,d) => (a.toString.toInt, b.toString.toInt, c.toString.toInt, d.toString.toInt)}
}
 
/** Retrieve quintuplets of sexy primes given a list of Integers*/
def getSexyPrimesQuintuplets (primes : List[Int]) = {
primes
.map(n => if (
primes.contains(n+6) && primes.contains(n+12) && primes.contains(n+18) && primes.contains(n + 24))
(n, n + 6, n + 12, n + 18, n + 24)
)
.filter(p => p != ())
.map { case (a, b, c, d, e) => (a.toString.toInt, b.toString.toInt, c.toString.toInt, d.toString.toInt, e.toString.toInt) }
 
}
 
/** Retrieve all unsexy primes between 1 and a given limit from an input list of Integers*/
def removeOutsideSexyPrimes( l : List[Int], limit : Int) : List[Int] = {
l.filter(n => !isPrime(n+6) && n+6 < limit)
}
 
def main(args: Array[String]): Unit = {
val limit = 1000035
val l = List.range(1,limit)
val primes = l.filter( n => isPrime(n))
 
val sexyPairs = getSexyPrimesPairs(primes)
println("Number of sexy pairs : " + sexyPairs.size)
println("5 last sexy pairs : " + sexyPairs.takeRight(5))
 
val primes2 = sexyPairs.flatMap(t => List(t._1, t._2)).distinct.sorted
val sexyTriplets = getSexyPrimesTriplets(primes2)
println("Number of sexy triplets : " + sexyTriplets.size)
println("5 last sexy triplets : " + sexyTriplets.takeRight(5))
 
val primes3 = sexyTriplets.flatMap(t => List(t._1, t._2, t._3)).distinct.sorted
val sexyQuadruplets = getSexyPrimesQuadruplets(primes3)
println("Number of sexy quadruplets : " + sexyQuadruplets.size)
println("5 last sexy quadruplets : " + sexyQuadruplets.takeRight(5))
 
val primes4 = sexyQuadruplets.flatMap(t => List(t._1, t._2, t._3, t._4)).distinct.sorted
val sexyQuintuplets = getSexyPrimesQuintuplets(primes4)
println("Number of sexy quintuplets : " + sexyQuintuplets.size)
println("The last sexy quintuplet : " + sexyQuintuplets.takeRight(10))
 
val sexyPrimes = primes2.toSet
val unsexyPrimes = removeOutsideSexyPrimes( primes.toSet.diff((sexyPrimes)).toList.sorted, limit)
println("Number of unsexy primes : " + unsexyPrimes.size)
println("10 last unsexy primes : " + unsexyPrimes.takeRight(10))
 
}
 
}
</syntaxhighlight>
{{out}}
<pre>
Number of sexy pairs : 16386
5 last sexy pairs : List((999371,999377), (999431,999437), (999721,999727), (999763,999769), (999953,999959))
Number of sexy triplets : 2900
5 last sexy triplets : List((997427,997433,997439), (997541,997547,997553), (998071,998077,998083), (998617,998623,998629), (998737,998743,998749))
Number of sexy quadruplets : 325
5 last sexy quadruplets : List((977351,977357,977363,977369), (983771,983777,983783,983789), (986131,986137,986143,986149), (990371,990377,990383,990389), (997091,997097,997103,997109))
Number of sexy quintuplets : 1
The last sexy quintuplet : List((5,11,17,23,29))
Number of unsexy primes : 48627
10 last unsexy primes : List(999853, 999863, 999883, 999907, 999917, 999931, 999961, 999979, 999983, 1000003)
</pre>
 
=={{header|Sidef}}==
<syntaxhighlight lang="ruby">var limit = 1e6+35
var primes = limit.primes
 
say "Total number of primes <= #{limit.commify} is #{primes.len.commify}."
say "Sexy k-tuple primes <= #{limit.commify}:\n"
 
(2..5).each {|k|
var groups = []
primes.each {|p|
var group = (1..^k -> map {|j| 6*j + p })
if (group.all{.is_prime} && (group[-1] <= limit)) {
groups << [p, group...]
}
}
 
say "...total number of sexy #{k}-tuple primes = #{groups.len.commify}"
say "...where last 5 tuples are: #{groups.last(5).map{'('+.join(' ')+')'}.join(' ')}\n"
}
 
var unsexy_primes = primes.grep {|p| is_prime(p+6) || is_prime(p-6) -> not }
say "...total number of unsexy primes = #{unsexy_primes.len.commify}"
say "...where last 10 unsexy primes are: #{unsexy_primes.last(10)}"</syntaxhighlight>
{{out}}
<pre>
Total number of primes <= 1,000,035 is 78,500.
Sexy k-tuple primes <= 1,000,035:
 
...total number of sexy 2-tuple primes = 16,386
...where last 5 tuples are: (999371 999377) (999431 999437) (999721 999727) (999763 999769) (999953 999959)
 
...total number of sexy 3-tuple primes = 2,900
...where last 5 tuples are: (997427 997433 997439) (997541 997547 997553) (998071 998077 998083) (998617 998623 998629) (998737 998743 998749)
 
...total number of sexy 4-tuple primes = 325
...where last 5 tuples are: (977351 977357 977363 977369) (983771 983777 983783 983789) (986131 986137 986143 986149) (990371 990377 990383 990389) (997091 997097 997103 997109)
 
...total number of sexy 5-tuple primes = 1
...where last 5 tuples are: (5 11 17 23 29)
 
...total number of unsexy primes = 48,627
...where last 10 unsexy primes are: [999853, 999863, 999883, 999907, 999917, 999931, 999961, 999979, 999983, 1000003]
</pre>
 
=={{header|Wren}}==
{{trans|Go}}
{{libheader|Wren-fmt}}
{{libheader|Wren-math}}
<syntaxhighlight lang="wren">import "./fmt" for Fmt
import "./math" for Int
var printHelper = Fn.new { |cat, le, lim, max|
var cle = Fmt.commatize(le)
var clim = Fmt.commatize(lim)
if (cat != "unsexy primes") cat = "sexy prime " + cat
System.print("Number of %(cat) less than %(clim) = %(cle)")
var last = (le < max) ? le : max
var verb = (last == 1) ? "is" : "are"
return [le, last, verb]
}
var lim = 1000035
var sv = Int.primeSieve(lim-1, false)
var pairs = []
var trips = []
var quads = []
var quins = []
var unsexy = [2, 3]
var i = 3
while (i < lim) {
if (i > 5 && i < lim-6 && !sv[i] && sv[i-6] && sv[i+6]) {
unsexy.add(i)
} else {
if (i < lim-6 && !sv[i] && !sv[i+6]) {
pairs.add([i, i+6])
if (i < lim-12 && !sv[i+12]) {
trips.add([i, i+6, i+12])
if (i < lim-18 && !sv[i+18]) {
quads.add([i, i+6, i+12, i+18])
if (i < lim-24 && !sv[i+24]) {
quins.add([i, i+6, i+12, i+18, i+24])
}
}
}
}
}
i = i + 2
}
var le
var n
var verb
var unwrap = Fn.new { |t|
le = t[0]
n = t[1]
verb = t[2]
}
unwrap.call(printHelper.call("pairs", pairs.count, lim, 5))
System.print("The last %(n) %(verb):\n %(pairs[le-n..-1])\n")
unwrap.call(printHelper.call("triplets", trips.count, lim, 5))
System.print("The last %(n) %(verb):\n %(trips[le-n..-1])\n")
unwrap.call(printHelper.call("quadruplets", quads.count, lim, 5))
System.print("The last %(n) %(verb):\n %(quads[le-n..-1])\n")
unwrap.call(printHelper.call("quintuplets", quins.count, lim, 5))
System.print("The last %(n) %(verb):\n %(quins[le-n..-1])\n")
unwrap.call(printHelper.call("unsexy primes", unsexy.count, lim, 10))
System.print("The last %(n) %(verb):\n %(unsexy[le-n..-1])\n")</syntaxhighlight>
 
{{out}}
<pre>
Number of sexy prime pairs less than 1,000,035 = 16,386
The last 5 are:
[[999371, 999377], [999431, 999437], [999721, 999727], [999763, 999769], [999953, 999959]]
 
Number of sexy prime triplets less than 1,000,035 = 2,900
The last 5 are:
[[997427, 997433, 997439], [997541, 997547, 997553], [998071, 998077, 998083], [998617, 998623, 998629], [998737, 998743, 998749]]
 
Number of sexy prime quadruplets less than 1,000,035 = 325
The last 5 are:
[[977351, 977357, 977363, 977369], [983771, 983777, 983783, 983789], [986131, 986137, 986143, 986149], [990371, 990377, 990383, 990389], [997091, 997097, 997103, 997109]]
 
Number of sexy prime quintuplets less than 1,000,035 = 1
The last 1 is:
[[5, 11, 17, 23, 29]]
 
Number of unsexy primes less than 1,000,035 = 48,627
The last 10 are:
[999853, 999863, 999883, 999907, 999917, 999931, 999961, 999979, 999983, 1000003]
</pre>
 
=={{header|XPL0}}==
<syntaxhighlight lang="xpl0">func IsPrime(N); \Return 'true' if N is prime
int N, I;
[if N <= 2 then return N = 2;
if (N&1) = 0 then \even >2\ return false;
for I:= 3 to sqrt(N) do
[if rem(N/I) = 0 then return false;
I:= I+1;
];
return true;
];
 
int CU, C2, C3, C4, C5, N, I;
int Unsexy(10), Pairs(5), Trips(5), Quads(5), Quins(5);
[CU:= 0; C2:= 0; C3:= 0; C4:= 0; C5:= 0;
for N:= 1000035 downto 2 do
[if IsPrime(N) then
[if IsPrime(N-6) then
[if C2 < 5 then Pairs(C2):= N;
C2:= C2+1;
if IsPrime(N-12) then
[if C3 < 5 then Trips(C3):= N;
C3:= C3+1;
if IsPrime(N-18) then
[if C4 < 5 then Quads(C4):= N;
C4:= C4+1;
if IsPrime(N-24) then
[if C5 < 5 then Quins(C5):= N;
C5:= C5+1;
];
];
];
]
else if not IsPrime(N+6) then
[if CU < 10 then Unsexy(CU):= N;
CU:= CU+1;
];
];
];
IntOut(0, C2); Text(0, " pairs ending with:^m^j");
for I:= 4 downto 0 do
[Text(0, " [");
IntOut(0, Pairs(I)-6); Text(0, ", ");
IntOut(0, Pairs(I)); Text(0, "]^m^j");
];
IntOut(0, C3); Text(0, " triplets ending with:^m^j");
for I:= 4 downto 0 do
[Text(0, " [");
IntOut(0, Trips(I)-12); Text(0, ", ");
IntOut(0, Trips(I)-6); Text(0, ", ");
IntOut(0, Trips(I)); Text(0, "]^m^j");
];
IntOut(0, C4); Text(0, " quadruplets ending with:^m^j");
for I:= 4 downto 0 do
[Text(0, " [");
IntOut(0, Quads(I)-18); Text(0, ", ");
IntOut(0, Quads(I)-12); Text(0, ", ");
IntOut(0, Quads(I)-6); Text(0, ", ");
IntOut(0, Quads(I)); Text(0, "]^m^j");
];
IntOut(0, C5); Text(0, " quintuplet(s) ending with:^m^j");
I:= if C5 > 5 then 5 else C5;
for I:= I-1 downto 0 do
[Text(0, " [");
IntOut(0, Quins(I)-24); Text(0, ", ");
IntOut(0, Quins(I)-18); Text(0, ", ");
IntOut(0, Quins(I)-12); Text(0, ", ");
IntOut(0, Quins(I)-6); Text(0, ", ");
IntOut(0, Quins(I)); Text(0, "]^m^j");
];
IntOut(0, CU); Text(0, " unsexy primes ending with:^m^j");
for I:= 9 downto 0 do
[IntOut(0, Unsexy(I)); if I then Text(0, ", ")];
CrLf(0);
]</syntaxhighlight>
 
{{out}}
<pre>
16386 pairs ending with:
[999371, 999377]
[999431, 999437]
[999721, 999727]
[999763, 999769]
[999953, 999959]
2900 triplets ending with:
[997427, 997433, 997439]
[997541, 997547, 997553]
[998071, 998077, 998083]
[998617, 998623, 998629]
[998737, 998743, 998749]
325 quadruplets ending with:
[977351, 977357, 977363, 977369]
[983771, 983777, 983783, 983789]
[986131, 986137, 986143, 986149]
[990371, 990377, 990383, 990389]
[997091, 997097, 997103, 997109]
1 quintuplet(s) ending with:
[5, 11, 17, 23, 29]
48627 unsexy primes ending with:
999853, 999863, 999883, 999907, 999917, 999931, 999961, 999979, 999983, 1000003
</pre>
 
Line 480 ⟶ 3,641:
 
[[Extensible prime generator#zkl]] could be used instead.
<langsyntaxhighlight lang="zkl">var [const] BI=Import("zklBigNum"); // libGMP
const N=1_000_035, M=N+24; // M allows prime group to span N, eg N=100, (97,103)
const N=1_000_000, M=N+25;
const OVR=6; // 6 if prime group can NOT span N, else 0
ps,p := Data(M).fill(0), BI(2);
ps,p := Data(M+50).fill(0), BI(1); // slop at the end (for reverse wrap around)
while(p.nextPrime()<=M){ ps[p]=1 } // bitmap of primes
 
ns:=[3..(N,2]-OVR).filter('wrap(n){ 2==(ps[n] + ps[n+6]) }); # know 2 isn't, check anyway
msg(N,"sexy prime pairs",ns,5,1);
 
ns:=[3..N-(6+OVR),2].filter('wrap(n){ 3==(ps[n] + ps[n+6] + ps[n+12]) }); # can't be even
msg(N,"triplessexy triplet primes",ns,5,2);
 
ns:=[3..N-(12+OVR),2].filter('wrap(n){ 4==(ps[n] + ps[n+6] + ps[n+12] + ps[n+18]) }); # no evens
msg(N,"quadrupletssexy quadruplet primes",ns,5,3);
 
ns:=[3..N-(18+OVR),2].filter('wrap(n){ 5==(ps[n] + ps[n+6] + ps[n+12] + ps[n+18] + ps[n+24]) });
msg(N,"quintupletssexy quintuplet primes",ns,1,4);
 
ns:=[7..(N-6,2]OVR).filter('wrap(n){ ps[n] and 0==(ps[n-6] + ps[n+6]) }); // include 2
msg(N,"(opps, I meant UNsexyunsexy primes)",ns,10,0);
 
fcn msg(N,s,nsps,n,g){
n=n.min(ps.len()); // if the number of primes is less than n
gs:=ns[-n,*].apply('wrap(n){ [0..g*6,6].apply('+(n)) })
gs:=ps[-n,*].apply('wrap(n){ [0..g*6,6].apply('+(n)) })
.pump(String,T("concat",","),"(%s) ".fmt);
.pump(String,T("concat", ","),"(%s) ".fmt);
println("Number of sexy prime %s less than %,d = %,d".fmt(s,N,ns.len()));
println("TheNumber lastof %ds are:\nless than %s\n,d is %,d".fmt(ns,gsN,ps.len()));
println("The last %d %s:\n %s\n".fmt(n, (n>1 and "are" or "is"), gs));
}</lang>
}</syntaxhighlight>
{{out}}
<pre style="font-size:80%">
<pre>
Number of sexy prime pairs less than 1,000,000035 =is 16,386
The last 5 are:
(999371,999377) (999431,999437) (999721,999727) (999763,999769) (999953,999959)
 
Number of sexy primetriplet triplesprimes less than 1,000,000035 =is 2,900
The last 5 are:
(997427,997433,997439) (997541,997547,997553) (998071,998077,998083) (998617,998623,998629) (998737,998743,998749)
 
Number of sexy primequadruplet quadrupletsprimes less than 1,000,000035 =is 325
The last 5 are:
(977351,977357,977363,977369) (983771,983777,983783,983789) (986131,986137,986143,986149) (990371,990377,990383,990389) (997091,997097,997103,997109)
 
Number of sexy primequintuplet quintupletsprimes less than 1,000,000035 =is 1
The last 1 areis:
(5,11,17,23,29)
 
Number of sexy prime (opps, I meant UNsexyunsexy primes) less than 1,000,000035 =is 48,624627
The last 10 are:
(999809) (999853) (999863) (999883) (999907) (999917) (999931) (999961) (999979) (999983) (1000003)
</pre>
2,169

edits