Sexy primes

Sexy primes is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.
 This page uses content from Wikipedia. The original article was at Sexy_prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)

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 5 is 6.

The term "sexy prime" is a pun stemming from the Latin word for six: sex.

Sexy prime pairs: Sexy prime pairs are groups of two primes that differ by 6. e.g. (5 11), (7 13), (11 17)
See sequences: OEIS:A023201 and OEIS:A046117

Sexy prime triplets: Sexy prime triplets are groups of three primes where each differs from the next by 6. e.g. (5 11 17), (7 13 19), (17 23 29)
See sequences: OEIS:A046118, OEIS:A046119 and OEIS:A046120

Sexy prime quadruplets: Sexy prime quadruplets are groups of four primes where each differs from the next by 6. e.g. (5 11 17 23), (11 17 23 29)
See sequences: OEIS:A023271, OEIS:A046122, OEIS:A046123 and OEIS:A046124

Sexy prime quintuplets: Sexy prime quintuplets are groups of five primes with a common difference of 6. One of the terms must be divisible by 5, because 5 and 6 are relatively prime. Thus, the only possible sexy prime quintuplet is (5 11 17 23 29)

• 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 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.
• 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.

 Note: the task requirements have changed for reasons found on the discussion page. Please update tasks to meet the updated requirements.

Factor

<lang factor>USING: combinators.short-circuit fry io kernel literals make math math.primes math.ranges prettyprint qw sequences ; IN: rosetta-code.sexy-primes

CONSTANT: primes \$[ 1,000,000 primes-upto ]

CONSTANT: tuplet-names qw{ pair triplet quadruplet quintuplet }

tuplet ( m n -- seq ) dupd 1 - 6 * + 6 <range> ;
sexy-tuplets ( n -- seq ) [ primes ] dip '[
```       [ _ tuplet dup [ prime? ] all? [ , ] [ drop ] if ] each
] { } make ;
```
show-tuplets ( n -- )
```   "Number of sexy prime " write dup 2 - tuplet-names nth write
"s less than 1,000,000: " write sexy-tuplets dup length .
5 short tail* "Up to last 5: " write [ { } like pprint bl ]
each nl nl ;
```
unsexy-primes ( -- seq ) primes [
```       { [ 6 + prime? not ] [ 6 - prime? not ] } 1&&
] filter ;
```
show-unsexy ( -- )
```   "Number of unsexy primes less than 1,000,000: " write
unsexy-primes dup length . "Last 10: " write
10 tail* [ pprint bl ] each nl ;
```
main ( -- ) 2 5 [a,b] [ show-tuplets ] each show-unsexy ;

MAIN: main</lang>

Output:
```Number of sexy prime pairs less than 1,000,000: 16386
Up to last 5: { 999371 999377 } { 999431 999437 } { 999721 999727 } { 999763 999769 } { 999953 999959 }

Number of sexy prime triplets less than 1,000,000: 2900
Up to last 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,000: 325
Up to 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 less than 1,000,000: 1
Up to last 5: { 5 11 17 23 29 }

Number of unsexy primes less than 1,000,000: 48626
Last 10: 999809 999853 999863 999883 999907 999917 999931 999961 999979 999983
```

Go

<lang go>package main

import "fmt"

func sieve(limit int) []bool {

```   limit++
// True denotes composite, false denotes prime.
c := make([]bool, limit) // all false by default
c[0] = true
c[1] = true
// no need to bother with even numbers over 2 for this task
p := 3 // Start from 3.
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
}
}
}
return c
```

}

func commatize(n int) string {

```   s := fmt.Sprintf("%d", n)
if n < 0 {
s = s[1:]
}
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
if n >= 0 {
return s
}
return "-" + s
```

}

func printHelper(cat string, le, lim, max int) (int, int, string) {

```   cle, clim := commatize(le), commatize(lim)
if cat != "unsexy primes" {
cat = "sexy prime " + cat
}
fmt.Printf("Number of %s less than %s = %s\n", cat, clim, cle)
last := max
if le < last {
last = le
}
verb := "are"
if last == 1 {
verb = "is"
}
return le, last, verb
```

}

func main() {

```   lim := 1000035
sv := sieve(lim - 1)
var pairs [][2]int
var trips [][3]int
var quins [][5]int
var unsexy = []int{2, 3}
for i := 3; i < lim; i += 2 {
if i > 5 && i < lim-6 && !sv[i] && sv[i-6] && sv[i+6] {
unsexy = append(unsexy, i)
continue
}
if i < lim-6 && !sv[i] && !sv[i+6] {
pair := [2]int{i, i + 6}
pairs = append(pairs, pair)
} else {
continue
}
if i < lim-12 && !sv[i+12] {
trip := [3]int{i, i + 6, i + 12}
trips = append(trips, trip)
} else {
continue
}
if i < lim-18 && !sv[i+18] {
quad := [4]int{i, i + 6, i + 12, i + 18}
} else {
continue
}
if i < lim-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.Printf("The last %d %s:\n  %v\n\n", n, verb, pairs[le-n:])
```
```   le, n, verb = printHelper("triplets", len(trips), lim, 5)
fmt.Printf("The last %d %s:\n  %v\n\n", n, verb, trips[le-n:])
```
```   le, n, verb = printHelper("quadruplets", len(quads), lim, 5)
fmt.Printf("The last %d %s:\n  %v\n\n", n, verb, quads[le-n:])
```
```   le, n, verb = printHelper("quintuplets", len(quins), lim, 5)
fmt.Printf("The last %d %s:\n  %v\n\n", n, verb, quins[le-n:])
```
```   le, n, verb = printHelper("unsexy primes", len(unsexy), lim, 10)
fmt.Printf("The last %d %s:\n  %v\n\n", n, verb, unsexy[le-n:])
```

}</lang>

Output:
```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]
```

Perl 6

Works with: Rakudo version 2018.08

<lang perl6>use Math::Primesieve; my \$sieve = Math::Primesieve.new;

my \$max = 1_000_035; my %primes = \$sieve.primes(\$max) X=> 1;

my \$primes = %primes.keys.categorize: { .&sexy }

say "Total primes less than {comma \$max}: ", comma +%primes.keys;

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 ;
```

}

say "Number of unsexy primes less than {comma \$max}: ", comma +\$primes<unsexy>; say " Last 10 unsexy primes less than {comma \$max}: ", \$primes<unsexy>.sort(+*).tail(10);

sub sexy (\$i) {

```   (
(so all(%primes{\$i «+« (6,12,18,24)})) ?? 'quintuplet' !! Nil,
(so all(%primes{\$i «+« (6,12,18)   })) ?? 'quadruplet' !! Nil,
(so all(%primes{\$i «+« (6,12)      })) ?? 'triplet'    !! Nil,
(so     %primes{\$i  +   6          })  ?? 'pair'       !! Nil,
(((\$i >= \$max - 6)  &&  (\$i + 6).is-prime)) ||
(so any(%primes{\$i «+« (6, -6)     })) ?? 'sexy' !! 'unsexy'
).grep: *.defined
```

}

sub comma { \$^i.flip.comb(3).join(',').flip }</lang>

Output:
```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)```

Python

<lang python>LIMIT = 1_000_000 def primes2(limit=LIMIT):

```   if limit < 2: return []
if limit < 3: return [2]
lmtbf = (limit - 3) // 2
buf = [True] * (lmtbf + 1)
for i in range((int(limit ** 0.5) - 3) // 2 + 1):
if buf[i]:
p = i + i + 3
s = p * (i + 1) + i
buf[s::p] = [False] * ((lmtbf - s) // p + 1)
return [2] + [i + i + 3 for i, v in enumerate(buf) if v]
```

primes = primes2(LIMIT) primeset = set(primes)

1. %%

s = [[] for x in range(4)] unsexy = [] for p in primes:

```   if p + 6 in primeset:
s[0].append((p, p+6))
else:
if p - 6 not in primeset:
unsexy.append(p)
continue
if p + 12 in primeset:
s[1].append((p, p+6, p+12))
else:
continue
if p + 18 in primeset:
s[2].append((p, p+6, p+12, p+18))
else:
continue
if p + 24 in primeset:
s[3].append((p, p+6, p+12, p+18, p+24))
```
1. %%

print('"SEXY" PRIME GROUPINGS:') for sexy, name in zip(s, 'pairs triplets quadruplets quintuplets'.split()):

```   print(f'  {len(sexy)} {name} ending with ...')
for sx in sexy[-5:]:
print('   ',sx)
```

print(f'\nThere are {len(unsexy)} unsexy primes ending with ...') for usx in unsexy[-10:]:

```   print(' ',usx)</lang>
```
Output:
```"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)
(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```

REXX

<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= 1000000 - 1 /*Not specified? Then use the default.*/ if endU== | endU=="," then endU= 10 /* " " " " " " */ if end2== | end2=="," then end2= 5 /* " " " " " " */ if end3== | end3=="," then end3= 5 /* " " " " " " */ if end4== | end4=="," then end4= 5 /* " " " " " " */ if end5== | end5=="," then end4= 5 /* " " " " " " */ @.=.; s.=0; #=0;  !.=0 /*count of primes (so far); set prime#.*/ if N>1 then do; #=1; @.1=2;  !.2=1; end /*a count of the primes found (so far).*/

```     do j=3  by 2  to  N+6                      /*start in the cellar and work up.     */
if j<19  then if wordpos(j, '3 5 7 11 13 17')==0  then iterate
else do;  #= #+1;  @.#= j;  !.j= 1
b= j-6;   if !.b  then s.b= 1
iterate
end
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(s2, 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(s3, 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(s4, max(1,y4-end4+1)) say say 'There are ' commas(w5%5) @sexy "quintuplets less than " Nc say 'The last ' commas(end4) @sexy "quintuplets are:"; say subword(s5, max(1,y5-end4+1)) say say 'There are ' commas(s1) " sexy primes less than " Nc say 'There are ' commas(uu) " unsexy primes less than " Nc say 'The last ' commas(endU) " unsexy primes are: " subword(u, max(1,uu-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>
```
output   when using the default inputs:

(Shown at   5/6   size.)

```There are  78,498  primes less than  1,000,000

There are  16,386  sexy prime pairs less than  1,000,000
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,000
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,000
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 are  1  sexy prime quintuplets less than  1,000,000
The last  5  sexy prime quintuplets are:
5~11~17~23~29

There are  29,872    sexy primes less than  1,000,000
There are  48,626  unsexy primes less than  1,000,000
The last  10  unsexy primes are:  999809 999853 999863 999883 999907 999917 999931 999961 999979 999983
```

zkl

Using GMP (GNU Multiple Precision Arithmetic Library, probabilistic primes), because it is easy and fast to generate primes.

Extensible prime generator#zkl could be used instead. <lang zkl>var [const] BI=Import("zklBigNum"); // libGMP const N=1_000_000, M=N+25; // M allows prime group to span N, eg N=100, (97,103) ps,p := Data(M).fill(0), BI(2); while(p.nextPrime()<=M){ ps[p]=1 } // bitmap of primes

ns:=[3..N,2].filter('wrap(n){ 2==(ps[n] + ps[n+6]) }); msg(N,"pairs",ns,5,1);

ns:=[3..N-6,2].filter('wrap(n){ 3==(ps[n] + ps[n+6] + ps[n+12]) }); msg(N,"triples",ns,5,2);

ns:=[3..N-12,2].filter('wrap(n){ 4==(ps[n] + ps[n+6] + ps[n+12] + ps[n+18]) }); msg(N,"quadruplets",ns,5,3);

ns:=[3..N-18,2].filter('wrap(n){ 5==(ps[n] + ps[n+6] + ps[n+12] + ps[n+18] + ps[n+24]) }); msg(N,"quintuplets",ns,1,4);

ns:=[7..N-6,2].filter('wrap(n){ ps[n] and 0==(ps[n-6] + ps[n+6]) }); msg(N,"(opps, I meant UNsexy primes)",ns,10,0);

fcn msg(N,s,ps,n,g){

```  n=n.min(ps.len());	// if the number of primes is less than n
gs:=ps[-n,*].apply('wrap(n){ [0..g*6,6].apply('+(n)) })
.pump(String,T("concat",","),"(%s) ".fmt);
println("Number of sexy prime %s less than %,d = %,d".fmt(s,N,ps.len()));
println("The last %d are:\n  %s\n".fmt(n,gs));
```

}</lang>

Output:
```Number of sexy prime pairs less than 1,000,000 = 16,386
The last 5 are:
(999371,999377) (999431,999437) (999721,999727) (999763,999769) (999953,999959)

Number of sexy prime triples less than 1,000,000 = 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,000 = 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,000 = 1
The last 1 are:
(5,11,17,23,29)

Number of sexy prime (opps, I meant UNsexy primes) less than 1,000,000 = 48,624
The last 10 are:
(999809) (999853) (999863) (999883) (999907) (999917) (999931) (999961) (999979) (999983)
```