Primes whose first and last number is 3: Difference between revisions

m
(add FreeBASIC)
m (→‎{{header|Wren}}: Minor tidy)
 
(17 intermediate revisions by 12 users not shown)
Line 10:
Find and show only the   ''number''   of these types of primes   that are   '''<   1,000,000'''.
<br><br>
 
=={{header|11l}}==
{{trans|Nim}}
 
<syntaxhighlight lang="11l">F is_prime(n)
I n == 2
R 1B
I n < 2 | n % 2 == 0
R 0B
L(i) (3 .. Int(sqrt(n))).step(2)
I n % i == 0
R 0B
R 1B
 
V lim = 1'000'000
V primes3x3 = [3]
V m = 100
V count = 1
L m * 3 < lim
L(n) (3 * m + 3 .. 4 * m - 7).step(10)
I n > lim
L.break
I is_prime(n)
count++
I n < 4000
primes3x3.append(n)
m *= 10
 
print(‘Found ’primes3x3.len‘ primes starting and ending with 3 below 4000:’)
L(n) primes3x3
print(‘#4’.format(n), end' I (L.index + 1) % 11 == 0 {"\n"} E ‘ ’)
 
print("\nFound "count‘ primes starting and ending with 3 below 1000000.’)</syntaxhighlight>
 
{{out}}
<pre>
Found 33 primes starting and ending with 3 below 4000:
3 313 353 373 383 3023 3083 3163 3203 3253 3313
3323 3343 3373 3413 3433 3463 3533 3583 3593 3613 3623
3643 3673 3733 3793 3803 3823 3833 3853 3863 3923 3943
 
Found 2251 primes starting and ending with 3 below 1000000.
</pre>
 
=={{header|Action!}}==
{{libheader|Action! Sieve of Eratosthenes}}
<syntaxhighlight lang="action!">INCLUDE "H6:SIEVE.ACT"
 
BYTE Func IsSpecialPrime(INT i BYTE ARRAY primes)
BYTE d,first
 
IF primes(i)=0 THEN
RETURN (0)
FI
first=1
WHILE i#0
DO
d=i MOD 10
IF first THEN
IF d#3 THEN
RETURN (0)
FI
first=0
FI
i==/10
OD
IF d#3 THEN
RETURN (0)
FI
RETURN (1)
 
PROC Main()
DEFINE MAX="3999"
BYTE ARRAY primes(MAX+1)
INT i,count=[0]
 
Put(125) PutE() ;clear the screen
Sieve(primes,MAX+1)
FOR i=2 TO MAX
DO
IF IsSpecialPrime(i,primes) THEN
PrintI(i) Put(32)
count==+1
FI
OD
PrintF("%E%EThere are %I primes",count)
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Primes_whose_first_and_last_number_is_3.png Screenshot from Atari 8-bit computer]
<pre>
3 313 353 373 383 3023 3083 3163 3203 3253 3313 3323 3343 3373 3413 3433 3463
3533 3583 3593 3613 3623 3643 3673 3733 3793 3803 3823 3833 3853 3863 3923 3943
 
There are 33 primes
</pre>
 
=={{header|ALGOL 68}}==
{{Trans|ALGOL W}} With added stretch goal. As with the Go and other samples, generates the candidate sequence.
{{libheader|ALGOL 68-primes}}
<langsyntaxhighlight lang="algol68">BEGIN # find some primes whose first and last digits are 3 #
INT max prime = 1 000 000; # largest number to consider #
# sieve the primes to max prime #
Line 34 ⟶ 129:
FOR i FROM 0 BY 10 TO 99 990 DO IF prime[ 300 003 + i ] THEN p3count +:= 1 FI OD;
print( ( newline, "Found ", whole( p3count, 0 ), " ""3x3"" primes below 1000000", newline ) )
END</langsyntaxhighlight>
{{out}}
<pre>
Line 45 ⟶ 140:
=={{header|ALGOL W}}==
As with the Go and oher samples, finds the numbers by generating the candidate seuence.
<langsyntaxhighlight lang="algolw">begin % find some primes whose first and last digits are 3 %
integer MAX_PRIME;
MAX_PRIME := 4000;
Line 71 ⟶ 166:
for i := 0 step 10 until 990 do p( 3003 + i );
end
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 78 ⟶ 173:
3733 3793 3803 3823 3833 3853 3863 3923 3943
</pre>
=={{header|Arturo}}==
<syntaxhighlight lang="arturo">firstAndLastIs3?: function [n][
if not? prime? n -> return false
return and? -> 3 = first digits n
-> 3 = last digits n
]
 
primesWithFirstAndLast3: select 1..4000 => firstAndLastIs3?
 
loop split.every: 11 primesWithFirstAndLast3 'x ->
print map x 's -> pad to :string s 5
 
nofPrimesBelow1M: enumerate 1..1000000 => firstAndLastIs3?
 
print ""
print ["Found" nofPrimesBelow1M "primes starting and ending with 3 below 1000000."]</syntaxhighlight>
 
{{out}}
 
<pre> 3 313 353 373 383 3023 3083 3163 3203 3253 3313
3323 3343 3373 3413 3433 3463 3533 3583 3593 3613 3623
3643 3673 3733 3793 3803 3823 3833 3853 3863 3923 3943
 
Found 2251 primes starting and ending with 3 below 1000000. </pre>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f PRIMES_WHOSE_FIRST_AND_LAST_NUMBER_IS_3.AWK
BEGIN {
Line 111 ⟶ 231:
return(1)
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 121 ⟶ 241:
Primes beginning and ending with '3' 1-999999: 2251
</pre>
 
=={{header|C}}==
{{trans|FreeBASIC}}
<syntaxhighlight lang="c">#include<stdio.h>
#include<stdlib.h>
#include<math.h>
 
int isprime( int p ) {
int i;
if(p==2) return 1;
if(!(p%2)) return 0;
for(i=3; i*i<=p; i+=2) {
if(!(p%i)) return 0;
}
return 1;
}
 
int main(void) {
int np = 1, d, i, n;
printf( "3 " );
for(d=1; d<6; d++) {
for(i=3; i<pow(10,d)-1; i+=10) {
n = i + 3*pow(10,d);
if(isprime(n)) {
++np;
if(n<4009) {
printf("%d ",n);
if(!(np%10)) printf("\n");
}
}
}
}
printf( "\n\nThere were %d primes of the form 3x3 below one million.\n", np );
return 0;
}</syntaxhighlight>
{{out}}<pre>
3 313 353 373 383 3023 3083 3163 3203 3253
3313 3323 3343 3373 3413 3433 3463 3533 3583 3593
3613 3623 3643 3673 3733 3793 3803 3823 3833 3853
3863 3923 3943
 
There were 2251 primes of the form 3x3 below one million.</pre>
 
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
 
 
<syntaxhighlight lang="Delphi">
function IsPrime(N: int64): boolean;
{Fast, optimised prime test}
var I,Stop: int64;
begin
if (N = 2) or (N=3) then Result:=true
else if (n <= 1) or ((n mod 2) = 0) or ((n mod 3) = 0) then Result:= false
else
begin
I:=5;
Stop:=Trunc(sqrt(N+0.0));
Result:=False;
while I<=Stop do
begin
if ((N mod I) = 0) or ((N mod (I + 2)) = 0) then exit;
Inc(I,6);
end;
Result:=True;
end;
end;
 
 
 
 
procedure GetDigits(N: integer; var IA: TIntegerDynArray);
{Get an array of the integers in a number}
var T: integer;
begin
SetLength(IA,0);
repeat
begin
T:=N mod 10;
N:=N div 10;
SetLength(IA,Length(IA)+1);
IA[High(IA)]:=T;
end
until N<1;
end;
 
 
 
procedure ShowFirstLast3Prime(Memo: TMemo);
var I,Cnt1,Cnt2: integer;
var IA: TIntegerDynArray;
var S: string;
 
function FirstLast3(N: integer): boolean;
var I: integer;
begin
GetDigits(N,IA);
Result:=(IA[0]=3) and (IA[High(IA)]=3);
end;
 
begin
Cnt1:=0; Cnt2:=0;
S:='';
for I:=0 to 1000000-1 do
if IsPrime(I) then
if FirstLast3(I) then
begin
Inc(Cnt1);
if I<4000 then
begin
Inc(Cnt2);
S:=S+Format('%5D',[I]);
If (Cnt2 mod 5)=0 then S:=S+CRLF;
end;
end;
Memo.Lines.Add(S);
Memo.Lines.Add('Count < 1,000 = '+IntToStr(Cnt2));
Memo.Lines.Add('Count < 1,000,000 = '+IntToStr(Cnt1));
end;
 
 
</syntaxhighlight>
{{out}}
<pre>
3 313 353 373 383
3023 3083 3163 3203 3253
3313 3323 3343 3373 3413
3433 3463 3533 3583 3593
3613 3623 3643 3673 3733
3793 3803 3823 3833 3853
3863 3923 3943
Count < 1,000 = 33
Count < 1,000,000 = 2251
Elapsed Time: 181.797 ms.
 
</pre>
 
 
=={{header|F_Sharp|F#}}==
This task uses [http://www.rosettacode.org/wiki/Extensible_prime_generator#The_functions Extensible Prime Generator (F#)]
<langsyntaxhighlight lang="fsharp">
//3 Sandwich Primes. Nigel Galloway: July 25th., 2021
primes32()|>Seq.takeWhile((>)4000)|>Seq.filter(fun n->n%10=3 && (n=3||(n>29 && n<40)||(n>299 && n<400)||n>2999))|>Seq.iter(printf "%d "); printfn ""
</syntaxhighlight>
</lang>
{{out}}
<pre>
3 313 353 373 383 3023 3083 3163 3203 3253 3313 3323 3343 3373 3413 3433 3463 3533 3583 3593 3613 3623 3643 3673 3733 3793 3803 3823 3833 3853 3863 3923 3943
</pre>
 
=={{header|Factor}}==
{{works with|Factor|0.99 2021-06-02}}
<langsyntaxhighlight lang="factor">USING: formatting grouping io kernel lists lists.lazy math
math.functions math.primes sequences ;
 
Line 155 ⟶ 414:
 
3 1,000,000 surrounded llength
"Found %d primes beginning and ending with 3 under 1,000,000.\n" printf</langsyntaxhighlight>
{{out}}
<pre>
Line 185 ⟶ 444:
 
Found 2251 primes beginning and ending with 3 under 1,000,000.
</pre>
 
=={{header|Fermat}}==
<syntaxhighlight lang="fermat">np := 1;
!(3,' ');
for d = 1 to 5 do
for i = 3 to 10^d-1 by 10 do
n:=3*10^d + i;
if Isprime(n) = 1 then
np:=np+1;
if n<4000 then
!(n,' ');
if Divides(10,np) then !! fi;
fi;
fi;
od;
od;
!!;
!!;
!!('There were ',np,' primes of the form 3...3 below 1,000,000');
</syntaxhighlight>
{{out}}<pre>
3 313 353 373 383 3023 3083 3163 3203 3253
 
3313 3323 3343 3373 3413 3433 3463 3533 3583 3593
 
3613 3623 3643 3673 3733 3793 3803 3823 3833 3853
 
3863 3923 3943
 
There were 2251 primes of the form 3...3 below 1,000,000
</pre>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">#include "isprime.bas"
 
dim as integer np = 1, d, n, i
Line 205 ⟶ 495:
next d
print : print
print "There were ";np;" 3...3 primes below 1000000"</langsyntaxhighlight>
{{out}}<pre>
3 313 353 373 383 3023 3083 3163 3203 3253
Line 217 ⟶ 507:
=={{header|Go}}==
{{libheader|Go-rcu}}
<langsyntaxhighlight lang="go">package main
 
import (
Line 259 ⟶ 549:
pcc := rcu.Commatize(pc)
fmt.Println("\nFound", pcc, "primes under 1,000,000 which begin and end with 3.")
}</langsyntaxhighlight>
 
{{out}}
Line 272 ⟶ 562:
Found 2,251 primes under 1,000,000 which begin and end with 3.
</pre>
 
=={{header|Haskell}}==
<syntaxhighlight lang="haskell">
isPrime :: Int -> Bool
isPrime n
|n == 2 = True
|n == 1 = False
|otherwise = null $ filter (\i -> mod n i == 0 ) [2 .. root]
where
root :: Int
root = floor $ sqrt $ fromIntegral n
 
condition :: Int -> Bool
condition n = isPrime n && head numstr == '3' && last numstr == '3'
where
numstr :: String
numstr = show n
 
solution :: [Int]
solution = filter condition [1..3999]
 
main :: IO ( )
main = do
print solution
putStrLn ( "There are " ++ ( show $ length $ filter condition [1..999999]
) ++ " 3 x 3 primes below 1000000!" )
</syntaxhighlight>
{{out}}
<pre>
[3,313,353,373,383,3023,3083,3163,3203,3253,3313,3323,3343,3373,3413,3433,3463,3533,3583,3593,3613,3623,3643,3673,3733,3793,3803,3823,3833,3853,3863,3923,3943]
There are 2251 3 x 3 primes below 1000000!
</pre>
 
=={{header|J}}==
<syntaxhighlight lang="j"> primes3x3=. 3 ;@; 10 <@(#~ 1&p:)@(30&* + 3 + 10 * i.)@^ i.
 
primes3x3 3
3 313 353 373 383 3023 3083 3163 3203 3253 3313 3323 3343 3373 3413 3433 3463 3533 3583 3593 3613 3623 3643 3673 3733 3793 3803 3823 3833 3853 3863 3923 3943
 
# primes3x3 5
2251</syntaxhighlight>
 
=={{header|jq}}==
Line 278 ⟶ 609:
 
See e.g. [[Erd%C5%91s-primes#jq]] for a suitable implementation of `is_prime`.
<langsyntaxhighlight lang="jq"># For the stretch goal:
def count(s): reduce s as $x (null; .+1);
 
Line 291 ⟶ 622:
 
task(2),
"\nStretch goal: \(count( task(4) ))"</langsyntaxhighlight>
{{out}}
<pre>
Line 332 ⟶ 663:
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">using Primes
 
isxbyx(n, base=10, dig=3) = n ÷ prevpow(base, n) == dig && n % base == dig
Line 343 ⟶ 674:
println("\nTotal $(d)x$d primes less than 1,000,000: ", length(p3x3(1_000_000, 10, d)), ".")
end
</langsyntaxhighlight>{{out}}
<pre>
Line 376 ⟶ 707:
9749 9769 9829 9839 9859 9929 9949
Total 9x9 primes less than 1,000,000: 2053.
</pre>
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">Cases[NestWhileList[NextPrime,
2, # < 4000 &], _?(IntegerDigits[#][[{1, -1}]] === {3, 3} &)]</syntaxhighlight>
 
{{out}}<pre>
{3,313,353,373,383,3023,3083,3163,3203,3253,3313,3323,3343,3373,3413,3433,3463,3533,3583,3593,3613,3623,3643,3673,3733,3793,3803,3823,3833,3853,3863,3923,3943}
</pre>
 
=={{header|Nim}}==
<langsyntaxhighlight Nimlang="nim">import strformat
 
func isPrime(n: Positive): bool =
Line 408 ⟶ 746:
stdout.write &"{n:4}", if (i + 1) mod 11 == 0: '\n' else: ' '
 
echo &"\nFound {count} primes starting and ending with 3 below 1_000_000."</langsyntaxhighlight>
 
{{out}}
Line 420 ⟶ 758:
=={{header|Perl}}==
{{libheader|ntheory}}
<langsyntaxhighlight lang="perl">#!/usr/bin/perl
 
use strict; # https://rosettacode.org/wiki/Primes_whose_first_and_last_number_is_3
Line 429 ⟶ 767:
my $n33 = grep /^3/ && /3$/, @{ primes( 1_000_000 ) };
print @n33 . " under 4000\n\n@n33" =~ s/.{75}\K /\n/gr,
"\n\n$n33 under 1000000\n";</langsyntaxhighlight>
{{out}}
<pre>
Line 442 ⟶ 780:
=={{header|Phix}}==
Works for any digit, partly inspired by the Wren entry.
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">primes_with_first_and_last_digit</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">d</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">p10</span><span style="color: #0000FF;">)</span>
Line 467 ⟶ 805:
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">primes_with_first_and_last_digit</span><span style="color: #0000FF;">(</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">6</span><span style="color: #0000FF;">)</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: #008000;">"There are %d primes under 1,000,000 which begin and end in 3\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">)})</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 480 ⟶ 818:
 
=={{header|Raku}}==
<syntaxhighlight lang="raku" perl6line>my $upto = 1e4;
 
for 1,3,5,7,9 -> $bracket {
Line 490 ⟶ 828:
cache $list;
$title ~ $list.batch($cols)».fmt($fmt).join: "\n"
}</langsyntaxhighlight>
{{out}}
<pre>Primes up to 10000 bracketed by 1 - 39 matching:
Line 523 ⟶ 861:
 
Also, &nbsp; if a negative &nbsp; '''cols''' &nbsp; is specified, &nbsp; only the &nbsp; ''count'' &nbsp; of primes found is shown.
<langsyntaxhighlight lang="rexx">/*REXX pgm finds and displays primes (base ten) that contain a leading and trailing 3. */
parse arg hi cols dig . /*obtain optional argument from the CL.*/
if hi=='' | hi=="," then hi= 4000 /*Not specified? Then use the default.*/
Line 567 ⟶ 905:
end /*k*/ /* [↑] only process numbers ≤ √ J */
#= #+1; @.#= j; sq.#= j*j /*bump # of Ps; assign next P; P square*/
end /*j*/; return</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
Line 586 ⟶ 924:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
load "stdlib.ring"
see "working..." + nl
Line 605 ⟶ 943:
see nl + "Found " + row + " numbers" + nl
see "done..." + nl
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 616 ⟶ 954:
Found 33 numbers
done...
</pre>
 
=={{header|RPL}}==
Uses a candidate numbers generator to speed up execution.
{{works with|HP|49}}
≪ { } 3
'''WHILE''' DUP 4000 < '''REPEAT'''
'''IF''' DUP ISPRIME? '''THEN''' SWAP OVER + SWAP '''END'''
10 +
'''IF''' DUP MANT IP 3 ≠ '''THEN''' XPON 1 + ALOG 3 * 3 + '''END'''
'''END''' DROP
≫ '<span style="color:blue">33PRIMES</span>' STO
{{out}}
<pre>
1: { 3 313 353 373 383 3023 3083 3163 3203 3253 3313 3323 3343 3373 3413 3433 3463 3533 3583 3593 3613 3623 3643 3673 3733 3793 3803 3823 3833 3853 3863 3923 3943 }
</pre>
 
=={{header|Ruby}}==
<syntaxhighlight lang="ruby">require 'prime'
 
puts "Primes below #{n=4000} which start and end with #{d=3}: "
p Prime.each(n).select{|pr| p_d = pr.digits; p_d.first == d && p_d.last == d}
 
print "\nCount of primes below #{n=1_000_000} which start and en with #{d=3}: "
puts Prime.each(n).count{|pr| p_d = pr.digits; p_d.first == d && p_d.last == d}
</syntaxhighlight>
{{out}}
<pre>Primes below 4000 which start and end with 3:
[3, 313, 353, 373, 383, 3023, 3083, 3163, 3203, 3253, 3313, 3323, 3343, 3373, 3413, 3433, 3463, 3533, 3583, 3593, 3613, 3623, 3643, 3673, 3733, 3793, 3803, 3823, 3833, 3853, 3863, 3923, 3943]
 
Count of primes below 1000000 which start and en with 3: 2251
</pre>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func numbers_with_edges(upto, base = 10, s = [3]) {
Enumerator({|callback|
callback(s.digits2num(base))
Line 646 ⟶ 1,015:
var count = numbers_with_edges(n).grep{.is_prime}.len
say "\nThere are #{count} primes <= #{n.commify} which begin and end in 3"
}</langsyntaxhighlight>
{{out}}
<pre>
Line 660 ⟶ 1,029:
=={{header|Wren}}==
{{libheader|Wren-math}}
{{libheader|Wren-traititerate}}
{{libheader|Wren-seq}}
{{libheader|Wren-fmt}}
 
===Basic task===
<langsyntaxhighlight ecmascriptlang="wren">import "./math" for Int
import "./traititerate" for Stepped
import "./seqfmt" for LstFmt
import "/fmt" for Fmt
 
var primes = []
Line 675 ⟶ 1,042:
}
System.print("Primes under 4,000 which begin and end in 3:")
for (chunk in Lst.chunks(primes, 11)) Fmt.printtprint("$,5d", chunkprimes, 11)
System.print("\nFound %(primes.count) such primes.")</langsyntaxhighlight>
 
{{out}}
Line 690 ⟶ 1,057:
===More general===
This version deals with primes (in base 10) beginning and ending with any specified digit and with up to a given number of digits.
<langsyntaxhighlight ecmascriptlang="wren">import "./math" for Int
import "./traititerate" for Stepped
import "./seqfmt" for LstFmt
import "/fmt" for Fmt
 
var getQualifyingPrimes = Fn.new { |x, d|
Line 715 ⟶ 1,081:
var len = d + ((d-1)/3).floor
Fmt.print("Primes under $,%(len)d which begin and end in $d:", 10.pow(d), x)
for (chunk in Lst.chunks(primes, 10)) Fmt.printtprint("$,%(len)d", chunkprimes, 10)
System.print("\nFound %(primes.count) such primes.\n")
}
Line 723 ⟶ 1,089:
var primes = getQualifyingPrimes.call(x, d)
Fmt.print("Found $,d primes under $,d which begin and end with $d.\n", primes.count, 10.pow(d), x)
}</langsyntaxhighlight>
 
{{out}}
Line 778 ⟶ 1,144:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">func IsPrime(N); \Return 'true' if N is a prime number
int N, I;
[if N <= 1 then return false;
Line 815 ⟶ 1,181:
Text(0, " such primes found below 1,000,000.
");
]</langsyntaxhighlight>
 
{{out}}
9,476

edits