Semiprime: Difference between revisions

54,742 bytes added ,  2 months ago
m
 
(126 intermediate revisions by 52 users not shown)
Line 1:
{{task|Prime Numbers}}
{{task|Prime Numbers}} Semiprime numbers are natural numbers that are products of exactly two (possibly equal) [[prime_number|prime numbers]]. Example: 1679 = 23 × 73 (This particular number was chosen as the length of the [http://en.wikipedia.org/wiki/Arecibo_message Arecibo message]).
 
Semiprime numbers are natural numbers that are products of exactly two (possibly equal) [[prime_number|prime numbers]].
 
 
'''Semiprimes'''   are also known as:
:::*   '''semi-primes'''
:::*   '''biprimes'''
:::*   '''bi-primes'''
:::*   ''' ''2-almost'' '''   primes
:::* &nbsp; or simply: &nbsp; ''' ''P<sub>2</sub> '' '''
 
 
 
;Example:
<big> 1679 = 23 &times; 73 </big>
 
(This particular number was chosen as the length of the [http://en.wikipedia.org/wiki/Arecibo_message Arecibo message]).
 
 
;Task:
Write a function determining whether a given number is semiprime.
 
 
;See also:
* The Wikipedia article: &nbsp;[[wp:Semiprime|semiprime]].
* The Wikipedia article: &nbsp;[[wp:Almost_prime|almost prime]].
* The OEIS sequence: &nbsp;[[oeis:A001358|A001358: semiprimes]]&nbsp; which has a shorter definition: ''the product of two primes''.
<br><br>
 
=={{header|11l}}==
{{trans|C++}}
 
<syntaxhighlight lang="11l">F is_semiprime(=c)
V a = 2
V b = 0
L b < 3 & c != 1
I c % a == 0
c /= a
b++
E
a++
R b == 2
 
print((1..100).filter(n -> is_semiprime(n)))</syntaxhighlight>
 
{{out}}
<pre>
[4, 6, 9, 10, 14, 15, 21, 22, 25, 26, 33, 34, 35, 38, 39, 46, 49, 51, 55, 57, 58, 62, 65, 69, 74, 77, 82, 85, 86, 87, 91, 93, 94, 95]
</pre>
 
=={{header|360 Assembly}}==
{{trans|C}}
<syntaxhighlight lang="360asm">* Semiprime 14/03/2017
SEMIPRIM CSECT
USING SEMIPRIM,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
STM R14,R12,12(R13) save previous context
ST R13,4(R15) link backward
ST R15,8(R13) link forward
LR R13,R15 set addressability
LA R10,PG pgi=0
LA R8,0 m=0
L R6,=F'2' i=2
DO WHILE=(C,R6,LE,=F'100') do i=2 to 100
ST R6,N n=i
LA R9,0 f=0
LA R7,2 j=2
LOOPJ EQU * do j=2 while f<2 and j*j<=n
C R9,=F'2' if f<2
BNL EXITJ then exit do j
LR R5,R7 j
MR R4,R7 *j
C R5,N if j*j<=n
BH EXITJ then exit do j
LOOPK EQU * do while n mod j=0
L R4,N n
SRDA R4,32 ~
DR R4,R7 /j
LTR R4,R4 if n mod <>0
BNZ EXITK then exit do j
ST R5,N n=n/j
LA R9,1(R9) f=f+1
B LOOPK enddo k
EXITK LA R7,1(R7) j++
B LOOPJ enddo j
EXITJ L R4,N n
IF C,R4,GT,=F'1' THEN if n>1 then
LA R2,1 g=1
ELSE , else
LA R2,0 g=0
ENDIF , endif
AR R2,R9 +f
IF C,R2,EQ,=F'2' THEN if f+(n>1)=2 then
XDECO R6,XDEC edit i
MVC 0(5,R10),XDEC+7 output i
LA R10,5(R10) pgi=pgi+10
LA R8,1(R8) m=m+1
LR R4,R8 m
SRDA R4,32 ~
D R4,=F'16' m/16
IF LTR,R4,Z,R4 THEN if m mod 16=0 then
XPRNT PG,L'PG print buffer
MVC PG,=CL80' ' clear buffer
LA R10,PG pgi=0
ENDIF , endif
ENDIF , endif
LA R6,1(R6) i++
ENDDO , enddo i
XPRNT PG,L'PG print buffer
MVC PG,=CL80'..... semiprimes' init buffer
XDECO R8,XDEC edit m
MVC PG(5),XDEC+7 output m
XPRNT PG,L'PG print buffer
L R13,4(0,R13) restore previous savearea pointer
LM R14,R12,12(R13) restore previous context
XR R15,R15 rc=0
BR R14 exit
N DS F n
PG DC CL80' ' buffer
XDEC DS CL12 temp
YREGS
END SEMIPRIM</syntaxhighlight>
{{out}}
<pre>
4 6 9 10 14 15 21 22 25 26 33 34 35 38 39 46
49 51 55 57 58 62 65 69 74 77 82 85 86 87 91 93
94 95
34 semiprimes
</pre>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">BYTE FUNC IsSemiPrime(INT n)
INT a,b
 
a=2 b=0
WHILE b<3 AND n#1
DO
IF n MOD a=0 THEN
n==/a b==+1
ELSE
a==+1
FI
OD
IF b=2 THEN
RETURN(1)
FI
RETURN(0)
 
PROC Main()
INT i
 
PrintE("Semiprimes:")
FOR i=1 TO 500
DO
IF IsSemiPrime(i) THEN
PrintI(i) Put(32)
FI
OD
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Semiprime.png Screenshot from Atari 8-bit computer]
<pre>
Semiprimes:
4 6 9 10 14 15 21 22 25 26 33 34 35 38 39 46 49 51 55 57 58 62 65 69 74 77 82 85 86 87 91 93 94 95 106 111 115 118
119 121 122 123 129 133 134 141 142 143 145 146 155 158 159 161 166 169 177 178 183 185 187 194 201 202 203 205 206
209 213 214 215 217 218 219 221 226 235 237 247 249 253 254 259 262 265 267 274 278 287 289 291 295 298 299 301 302
303 305 309 314 319 321 323 326 327 329 334 335 339 341 346 355 358 361 362 365 371 377 381 382 386 391 393 394 395
398 403 407 411 413 415 417 422 427 437 445 446 447 451 453 454 458 466 469 471 473 478 481 482 485 489 493 497
</pre>
 
=={{header|Ada}}==
Line 7 ⟶ 175:
This imports the package '''Prime_Numbers''' from [[Prime decomposition#Ada]].
 
<langsyntaxhighlight lang="ada">with Prime_Numbers, Ada.Text_IO;
procedure Test_Semiprime is
Line 27 ⟶ 195:
end if;
end loop;
end Test_Semiprime;</langsyntaxhighlight>
 
It outputs all semiprimes below 100 and all semiprimes between 1675 and 1680:
Line 42 ⟶ 210:
1680 = 2 * 2 * 2 * 2 * 3 * 5 * 7,
so the result printed is actually correct.
 
=={{header|ALGOL 68}}==
<syntaxhighlight lang="algol68"># returns TRUE if n is semi-prime, FALSE otherwise #
# n is semi prime if it has exactly two prime factors #
PROC is semiprime = ( INT n )BOOL:
BEGIN
# We only need to consider factors between 2 and #
# sqrt( n ) inclusive. If there is only one of these #
# then it must be a prime factor and so the number #
# is semi prime #
INT factor count := 0;
FOR factor FROM 2 TO ENTIER sqrt( ABS n )
WHILE IF n MOD factor = 0 THEN
factor count +:= 1;
# check the factor isn't a repeated factor #
IF n /= factor * factor THEN
# the factor isn't the square root #
INT other factor = n OVER factor;
IF other factor MOD factor = 0 THEN
# have a repeated factor #
factor count +:= 1
FI
FI
FI;
factor count < 2
DO SKIP OD;
factor count = 1
END # is semiprime # ;
 
# determine the first few semi primes #
print( ( "semi primes below 100: " ) );
FOR i TO 99 DO
IF is semi prime( i ) THEN print( ( whole( i, 0 ), " " ) ) FI
OD;
print( ( newline ) );
print( ( "semi primes below between 1670 and 1690: " ) );
FOR i FROM 1670 TO 1690 DO
IF is semi prime( i ) THEN print( ( whole( i, 0 ), " " ) ) FI
OD;
print( ( newline ) )
</syntaxhighlight>
{{out}}
<pre>
semi primes below 100: 4 6 9 10 14 15 21 22 25 26 33 34 35 38 39 46 49 51 55 57 58 62 65 69 74 77 82 85 86 87 91 93 94 95
semi primes below between 1670 and 1690: 1671 1673 1678 1679 1681 1685 1687 1689
</pre>
 
=={{header|ALGOL W}}==
{{Trans|C++}}
<syntaxhighlight lang="algolw">
begin % find some semi-primes - numbers with exactly 2 prime factors %
logical procedure isSemiPrime( integer value v ) ;
begin
integer a, b, c;
a := 2; b := 0; c := v;
while b < 3 and c > 1 do begin
if c rem a = 0 then begin
c := c div a;
b := b + 1
end
else a := a + 1;
end while_b_lt_3_and_c_ne_1 ;
b = 2
end isSemiPrime ;
 
for x := 2 until 99 do begin
if isSemiPrime( x ) then writeon( i_w := 1, s_w := 0, x, " " )
end for_x
end.
</syntaxhighlight>
{{out}}
<pre>
4 6 9 10 14 15 21 22 25 26 33 34 35 38 39 46 49 51 55 57 58 62 65 69 74 77 82 85 86 87 91 93 94 95
</pre>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">semiPrime?: function [x][
2 = size factors.prime x
]
 
print select 1..100 => semiPrime?</syntaxhighlight>
 
{{out}}
 
<pre>4 6 9 10 14 15 21 22 25 26 33 34 35 38 39 46 49 51 55 57 58 62 65 69 74 77 82 85 86 87 91 93 94 95</pre>
 
=={{header|AutoHotkey}}==
{{works with|AutoHotkey_L}}
<langsyntaxhighlight AutoHotkeylang="autohotkey">SetBatchLines -1
k := 1
loop, 100
Line 99 ⟶ 353:
}
;=================================================================================================================================================
esc::Exitapp</langsyntaxhighlight>
{{output}}
<Pre>
Line 108 ⟶ 362:
yes- 1678 - 2*839
yes- 1679 - 23*73</Pre>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f SEMIPRIME.AWK
BEGIN {
main(0,100)
main(1675,1680)
exit(0)
}
function main(lo,hi, i) {
printf("%d-%d:",lo,hi)
for (i=lo; i<=hi; i++) {
if (is_semiprime(i)) {
printf(" %d",i)
}
}
printf("\n")
}
function is_semiprime(n, i,nf) {
nf = 0
for (i=2; i<=n; i++) {
while (n % i == 0) {
if (nf == 2) {
return(0)
}
nf++
n /= i
}
}
return(nf == 2)
}
</syntaxhighlight>
{{out}}
<pre>
0-100: 4 6 9 10 14 15 21 22 25 26 33 34 35 38 39 46 49 51 55 57 58 62 65 69 74 77 82 85 86 87 91 93 94 95
1675-1680: 1678 1679
</pre>
 
 
=={{header|BASIC}}==
==={{header|ASIC}}===
{{trans|Tiny BASIC}}
<syntaxhighlight lang="basic">
REM Semiprime
PRINT "Enter an integer ";
INPUT N
N = ABS(N)
 
Count = 0
IF N >= 2 THEN
FOR Factor = 2 TO N
NModFactor = N MOD Factor
WHILE NModFactor = 0
Count = Count + 1
N = N / Factor
NModFactor = N MOD Factor
WEND
NEXT Factor
ENDIF
 
IF Count = 2 THEN
PRINT "It is a semiprime."
ELSE
PRINT "It is not a semiprime."
ENDIF
END
</syntaxhighlight>
{{out}}
<pre>
Enter an integer ?60
It is not a semiprime.
</pre>
<pre>
Enter an integer ?33
It is a semiprime.
</pre>
 
==={{header|BASIC256}}===
<syntaxhighlight lang="basic256">function semiprime$ (n)
a = 2
c = 0
while c < 3 and n > 1
if (n mod a) = 0 then
n = n / a
c = c + 1
else
a = a + 1
end if
end while
if c = 2 then return "True"
return "False"
end function
 
for i = 0 to 64
print i, semiprime$(i)
next i
end</syntaxhighlight>
 
==={{header|Chipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
{{trans|BASIC256}}
<syntaxhighlight lang="qbasic">100 rem Semiprime
110 cls
120 for i = 0 to 64
130 print using "## ";i semiprime$(i)
140 next i
150 end
160 sub semiprime$(n)
170 a = 2
180 c = 0
190 do while c < 3 and n > 1
200 if n mod a = 0 then n = n/a : c = c+1 else a = a+1
210 loop
220 if c = 2 then semiprime$ = "True" else semiprime$ = "False"
230 end sub</syntaxhighlight>
 
==={{header|FreeBASIC}}===
<syntaxhighlight lang="freebasic">function semiprime( n as uinteger ) as boolean
dim as uinteger a = 2, c = 0
while c < 3 andalso n > 1
if n mod a = 0 then
n /= a
c += 1
else
a += 1
end if
wend
if c = 2 then return true
return false
end function
for i as uinteger = 0 to 64
print i, semiprime(i)
next i</syntaxhighlight>
 
==={{header|GW-BASIC}}===
<syntaxhighlight lang="gwbasic">10 INPUT "Enter a number: ", N
20 N=ABS(N)
30 C = 0
40 IF N < 3 THEN GOTO 80
50 F = 2
60 IF N MOD F = 0 THEN C = C + 1 : N = N / F ELSE F = F + 1
70 IF N > 1 THEN GOTO 60
80 IF C=2 THEN PRINT "It's a semiprime." ELSE PRINT "It is not a semiprime."</syntaxhighlight>
 
==={{header|Minimal BASIC}}===
{{trans|Tiny BASIC}}
{{works with|Commodore BASIC|3.5}}
{{works with|Nascom ROM BASIC|4.7}}
<syntaxhighlight lang="gwbasic">
10 REM Semiprime
20 PRINT "Enter an integer";
30 INPUT N
40 LET N = ABS(N)
50 LET C = 0
60 IF N < 2 THEN 130
70 FOR F = 2 TO N
80 IF INT(N/F)*F <> N THEN 120
90 LET C = C+1
100 LET N = N/F
110 GOTO 80
120 NEXT F
130 IF C <> 2 THEN 160
140 PRINT "It is a semiprime."
150 GOTO 170
160 PRINT "It is not a semiprime."
170 END
</syntaxhighlight>
 
==={{header|Palo Alto Tiny BASIC}}===
{{trans|Tiny BASIC}}
<syntaxhighlight lang="basic">
10 REM SEMIPRIME
20 INPUT "ENTER AN INTEGER"N
30 LET N=ABS(N)
40 LET C=0
50 IF N<2 GOTO 90
60 FOR F=2 TO N
70 IF (N/F)*F=N LET C=C+1,N=N/F;GOTO 70
80 NEXT F
90 IF C=2 PRINT "IT IS A SEMIPRIME.";STOP
100 PRINT "IT IS NOT A SEMIPRIME.";STOP
</syntaxhighlight>
{{out}} 2 runs.
<pre>
ENTER AN INTEGER:60
IT IS NOT A SEMIPRIME.
</pre>
<pre>
ENTER AN INTEGER:33
IT IS A SEMIPRIME.
</pre>
 
==={{header|PureBasic}}===
<syntaxhighlight lang="purebasic">Procedure.s semiprime(n.i)
a.i = 2
c.i = 0
While c < 3 And n > 1
If (n % a) = 0
n / a
c + 1
Else
a + 1
EndIf
Wend
If c = 2
ProcedureReturn "True" ;#True
EndIf
ProcedureReturn "False" ;#False
EndProcedure
OpenConsole()
For i.i = 0 To 64
PrintN(Str(i) + #TAB$ + semiprime(i))
Next i
 
PrintN(#CRLF$ + "--- terminado, pulsa RETURN---"): Input()
CloseConsole()
End</syntaxhighlight>
 
==={{header|Run BASIC}}===
<syntaxhighlight lang="vbnet">function semiprime$(n)
a = 2
c = 0
while c < 3 and n > 1
if n mod a = 0 then
n = n / a
c = c + 1
else
a = a + 1
end if
wend
if c = 2 then semiprime$ = "True" else semiprime$ = "False"
end function
 
for i = 0 to 64
print i; chr$(9); semiprime$(i)
next i</syntaxhighlight>
 
==={{header|Tiny BASIC}}===
{{works with|TinyBasic}}
<syntaxhighlight lang="basic">10 REM Semiprime
20 PRINT "Enter an integer"
30 INPUT N
40 IF N < 0 THEN LET N = -N
50 IF N < 2 THEN GOTO 120
60 LET C = 0
70 LET F = 2
80 IF (N / F) * F = N THEN GOTO 150
90 LET F = F + 1
100 IF F > N THEN GOTO 120
110 GOTO 80
120 IF C = 2 THEN PRINT "It is a semiprime."
130 IF C <> 2 THEN PRINT "It is not a semiprime."
140 END
150 LET C = C + 1
160 LET N = N / F
170 GOTO 80</syntaxhighlight>
{{out}}2 runs.
<pre>
Enter an integer
? 60
It is not a semiprime.
</pre>
<pre>
Enter an integer
? 33
It is a semiprime.
</pre>
 
==={{header|True BASIC}}===
<syntaxhighlight lang="qbasic">FUNCTION semiprime$ (n)
LET a = 2
LET c = 0
DO WHILE c < 3 AND n > 1
IF REMAINDER(n, a) = 0 THEN
LET n = n / a
LET c = c + 1
ELSE
LET a = a + 1
END IF
LOOP
IF c = 2 THEN LET semiprime$ = "True" ELSE LET semiprime$ = "False"
END FUNCTION
 
FOR i = 0 TO 64
PRINT i, semiprime$(i)
NEXT i
END</syntaxhighlight>
 
==={{header|Yabasic}}===
<syntaxhighlight lang="yabasic">sub semiprime$ (n)
a = 2
c = 0
while c < 3 and n > 1
if mod(n, a) = 0 then
n = n / a
c = c + 1
else
a = a + 1
end if
wend
if c = 2 then return "True" : fi
return "False"
end sub
 
for i = 0 to 64
print i, chr$(9), semiprime$(i)
next i
end</syntaxhighlight>
 
=={{header|Bracmat}}==
When Bracmat is asked to take the square (or any other) root of a number, it does so by first finding the number's prime factors. It can do that for numbers up to 2^32 or 2^64 (depending on compiler and processor).
<langsyntaxhighlight lang="bracmat">semiprime=
m n a b
. 2^-64:?m
Line 117 ⟶ 681:
& !arg^!m
: (#%?a^!m*#%?b^!m|#%?a^!n&!a:?b)
& (!a.!b);</langsyntaxhighlight>
 
Test with numbers < 2^63:
<langsyntaxhighlight lang="bracmat"> 2^63:?u
& whl
' ( -1+!u:>2:?u
Line 126 ⟶ 690:
|
)
);</langsyntaxhighlight>
 
Output:
Line 177 ⟶ 741:
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdio.h>
 
int semiprime(int n)
Line 197 ⟶ 761:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre> 4 6 9 10 14 15 21 22 25 26 33 34 35 38 39 46 49 51 55 57 58 62 65 69 74 77 82 85 86 87 91 93 94 95</pre>
 
=={{header|C sharp|C#}}==
<syntaxhighlight lang="csharp">
static void Main(string[] args)
{
//test some numbers
for (int i = 0; i < 50; i++)
{
Console.WriteLine("{0}\t{1} ", i,isSemiPrime(i));
}
Console.ReadLine();
}
 
//returns true or false depending if input was considered semiprime
private static bool isSemiPrime(int c)
{
int a = 2, b = 0;
while (b < 3 && c != 1)
{
if ((c % a) == 0)
{
c /= a;
b++;
}
else
{
a++;
};
}
return b == 2;
}
</syntaxhighlight>
{{out}}
<pre>
0 False
1 False
2 False
3 False
4 True
5 False
6 True
7 False
8 False
9 True
10 True
11 False
12 False
13 False
14 True
15 True
16 False
17 False
18 False
19 False
20 False
21 True
22 True
23 False
24 False
25 True
26 True
27 False
28 False
29 False
30 False
31 False
32 False
33 True
34 True
35 True
36 False
37 False
38 True
39 True
40 False
41 False
42 False
43 False
44 False
45 False
46 True
47 False
48 False
49 True
</pre>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">
#include <iostream>
 
Line 224 ⟶ 873:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
4 6 9 10 14 15 21 22 25 26 33 34 35 38 39 46 49 51 55 57 58 62 65 69 74 77 82 85 86 87 91 93 94 95
</pre>
 
=={{header|Clojure}}==
{{trans|C}}
<syntaxhighlight lang="lisp">
(ns example
(:gen-class))
 
(defn semi-prime? [n]
(loop [a 2
b 0
c n]
(cond
(> b 2) false
(<= c 1) (= b 2)
(= 0 (rem c a)) (recur a (inc b) (int (/ c a)))
:else (recur (inc a) b c))))
 
(println (filter semi-prime? (range 1 100)))
</syntaxhighlight>
{{Out}}
<pre>
(4 6 9 10 14 15 21 22 25 26 33 34 35 38 39 46 49 51 55 57 58 62 65 69 74 77 82 85 86 87 91 93 94 95)
</pre>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun semiprimep (n &optional (a 2))
(cond ((> a (isqrt n)) nil)
((zerop (rem n a)) (and (primep a) (primep (/ n a))))
Line 239 ⟶ 911:
(cond ((> a (isqrt n)) t)
((zerop (rem n a)) nil)
(t (primep n (+ a 1)))))</langsyntaxhighlight>
 
Example Usage:
Line 247 ⟶ 919:
CL-USER> (semiprimep 9876543)
NIL</pre>
 
=={{header|Crystal}}==
{{trans|D}}
<syntaxhighlight lang="ruby">def semiprime(n)
nf = 0
(2..n).each do |i|
while n % i == 0
return false if nf == 2
nf += 1
n /= i
end
end
nf == 2
end
 
(1675..1681).each { |n| puts "#{n} -> #{semiprime(n)}" }</syntaxhighlight>
{{out}}
<pre>1675 -> false
1676 -> false
1677 -> false
1678 -> true
1679 -> true
1680 -> false
1681 -> true</pre>
 
Faster version using 'factor' function from [U|Li]nux Core Utilities library.
<syntaxhighlight lang="ruby">def semiprime(n)
`factor #{n}`.split(' ').size == 3
end
n = 0xffffffffffffffff_u64 # 2**64 - 1 = 18446744073709551615
(n-50..n).each { |n| puts "#{n} -> #{semiprime(n)}" }</syntaxhighlight>
{{out}}
<pre>18446744073709551565 -> false
18446744073709551566 -> true
18446744073709551567 -> false
18446744073709551568 -> false
18446744073709551569 -> false
18446744073709551570 -> false
18446744073709551571 -> false
18446744073709551572 -> false
18446744073709551573 -> false
18446744073709551574 -> false
18446744073709551575 -> false
18446744073709551576 -> false
18446744073709551577 -> true
18446744073709551578 -> false
18446744073709551579 -> false
18446744073709551580 -> false
18446744073709551581 -> false
18446744073709551582 -> false
18446744073709551583 -> false
18446744073709551584 -> false
18446744073709551585 -> false
18446744073709551586 -> false
18446744073709551587 -> false
18446744073709551588 -> false
18446744073709551589 -> false
18446744073709551590 -> false
18446744073709551591 -> false
18446744073709551592 -> false
18446744073709551593 -> false
18446744073709551594 -> false
18446744073709551595 -> false
18446744073709551596 -> false
18446744073709551597 -> true
18446744073709551598 -> false
18446744073709551599 -> false
18446744073709551600 -> false
18446744073709551601 -> true
18446744073709551602 -> false
18446744073709551603 -> false
18446744073709551604 -> false
18446744073709551605 -> false
18446744073709551606 -> false
18446744073709551607 -> false
18446744073709551608 -> false
18446744073709551609 -> false
18446744073709551610 -> false
18446744073709551611 -> false
18446744073709551612 -> false
18446744073709551613 -> false
18446744073709551614 -> false
18446744073709551615 -> false</pre>
 
=={{header|D}}==
{{trans|Go}}
<langsyntaxhighlight lang="d">bool semiprime(long n) pure nothrow @safe @nogc {
auto nf = 0;
foreach (immutable i; 2 .. n + 1) {
Line 268 ⟶ 1,023:
foreach (immutable n; 1675 .. 1681)
writeln(n, " -> ", n.semiprime);
}</langsyntaxhighlight>
{{out}}
<pre>1675 -> false
Line 276 ⟶ 1,031:
1679 -> true
1680 -> false</pre>
 
=={{header|DCL}}==
Given a file primes.txt is the list of primes up to the sqrt(2^31-1), i.e. 46337;
<langsyntaxhighlight DCLlang="dcl">$ p1 = f$integer( p1 )
$ if p1 .lt. 2
$ then
Line 325 ⟶ 1,081:
$
$ clean:
$ close primes</langsyntaxhighlight>
{{out}}
<pre>$ @factor 6
Line 335 ⟶ 1,091:
$ @factor 2147483646
FACTORIZATION = "2*3*3*7*11*31*151*331"</pre>
 
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
 
 
<syntaxhighlight lang="Delphi">
{This function would normally be in a library, but it shown here for clarity}
 
procedure GetAllFactors(N: Integer;var IA: TIntegerDynArray);
{Make a list of all irreducible factor of N}
var I: integer;
begin
SetLength(IA,1);
IA[0]:=1;
for I:=2 to N do
while (N mod I)=0 do
begin
SetLength(IA,Length(IA)+1);
IA[High(IA)]:=I;
N:=N div I;
end;
end;
 
 
function IsSemiprime(N: integer): boolean;
{Test if number is semiprime}
var IA: TIntegerDynArray;
begin
{Get all factors of N}
GetAllFactors(N,IA);
Result:=False;
{Since 1 is factor, ignore it}
if Length(IA)<>3 then exit;
Result:=IsPrime(IA[1]) and IsPrime(IA[2]);
end;
 
 
procedure Semiprimes(Memo: TMemo);
var I,Cnt: integer;
var S: string;
begin
Cnt:=0;
S:='';
{Test first 100 number to see if they are semiprime}
for I:=0 to 100-1 do
if IsSemiprime(I) then
begin
Inc(Cnt);
S:=S+Format('%4d',[I]);
if (Cnt mod 10)= 0 then S:=S+CRLF;
end;
Memo.Lines.Add(S);
Memo.Lines.Add('Count='+IntToStr(Cnt));
end;
 
</syntaxhighlight>
{{out}}
<pre>
4 6 9 10 14 15 21 22 25 26
33 34 35 38 39 46 49 51 55 57
58 62 65 69 74 77 82 85 86 87
91 93 94 95
Count=34
Elapsed Time: 5.182 ms.
 
</pre>
 
 
=={{header|EasyLang}}==
<syntaxhighlight>
fastfunc factor num .
i = 2
while i <= sqrt num
if num mod i = 0
return i
.
i += 1
.
return 1
.
func semiprime n .
f1 = factor n
if f1 = 1
return 0
.
f2 = n div f1
if factor f1 = 1 and factor f2 = 1
return 1
.
return 0
.
for i = 1 to 1000
if semiprime i = 1
write i & " "
.
.
</syntaxhighlight>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
(lib 'math)
(define (semi-prime? n)
Line 358 ⟶ 1,212:
(prime-factors 100000000042)
→ (2 50000000021)
</syntaxhighlight>
</lang>
 
=={{header|Elixir}}==
<syntaxhighlight lang="elixir">defmodule Prime do
def semiprime?(n), do: length(decomposition(n)) == 2
def decomposition(n), do: decomposition(n, 2, [])
defp decomposition(n, k, acc) when n < k*k, do: Enum.reverse(acc, [n])
defp decomposition(n, k, acc) when rem(n, k) == 0, do: decomposition(div(n, k), k, [k | acc])
defp decomposition(n, k, acc), do: decomposition(n, k+1, acc)
end
 
IO.inspect Enum.filter(1..100, &Prime.semiprime?(&1))
Enum.each(1675..1680, fn n ->
:io.format "~w -> ~w\t~s~n", [n, Prime.semiprime?(n), Prime.decomposition(n)|>Enum.join(" x ")]
end)</syntaxhighlight>
 
{{out}}
<pre>
[4, 6, 9, 10, 14, 15, 21, 22, 25, 26, 33, 34, 35, 38, 39, 46, 49, 51, 55, 57,
58, 62, 65, 69, 74, 77, 82, 85, 86, 87, 91, 93, 94, 95]
1675 -> false 5 x 5 x 67
1676 -> false 2 x 2 x 419
1677 -> false 3 x 13 x 43
1678 -> true 2 x 839
1679 -> true 23 x 73
1680 -> false 2 x 2 x 2 x 2 x 3 x 5 x 7
</pre>
 
=={{header|Erlang}}==
Another using prime factors from [[Prime_decomposition#Erlang]] :
 
<langsyntaxhighlight lang="erlang">
-module(factors).
-export([factors/1,kthfactor/2]).
Line 383 ⟶ 1,265:
_ ->
false end.
</syntaxhighlight>
</lang>
{out}
<pre>
Line 425 ⟶ 1,307:
 
=={{header|ERRE}}==
<syntaxhighlight lang="text">
PROGRAM SEMIPRIME_NUMBER
 
Line 452 ⟶ 1,334:
PRINT
END PROGRAM
</syntaxhighlight>
</lang>
Output is the same of "C" version.
 
=={{header|Euler}}==
{{Trans|C++}}
<!-- syntaxhighlight lang="euler"> -->
'''begin''' '''new''' isSemiPrime; '''new''' x; '''label''' xLoop;
isSemiPrime <-
` '''formal''' v;
'''begin''' '''new''' a; '''new''' b; '''new''' c; '''label''' again;
a <- 2; b <- 0; c <- v;
again: '''if''' b < 3 '''and''' c > 1 '''then''' '''begin'''
'''if''' c '''mod''' a = 0 '''then''' '''begin'''
c <- c % a;
b <- b + 1
'''end'''
'''else''' a <- a + 1;
'''goto''' again
'''end''' '''else''' 0;
b = 2
'''end'''
'
;
x <- 1;
xLoop: '''if''' [ x <- x + 1 ] < 100 '''then''' '''begin'''
'''if''' isSemiPrime( x ) '''then''' '''out''' x '''else''' 0;
'''goto''' xLoop
'''end''' '''else''' 0
'''end''' $
<!-- </syntaxhighlight> -->
{{out}}
<pre>
NUMBER 4
NUMBER 6
NUMBER 9
NUMBER 10
...
NUMBER 91
NUMBER 93
NUMBER 94
NUMBER 95
</pre>
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">let isSemiprime (n: int) =
let rec loop currentN candidateFactor numberOfFactors =
if numberOfFactors > 2 then numberOfFactors
Line 470 ⟶ 1,392:
|> Seq.choose (fun n -> if isSemiprime n then Some(n) else None)
|> Seq.toList
|> printfn "%A"</langsyntaxhighlight>
{{out}}
<pre>[4; 6; 9; 10; 14; 15; 21; 22; 25; 26; 33; 34; 35; 38; 39; 46; 49; 51; 55; 57; 58; 62; 65; 69; 74; 77; 82; 85; 86; 87; 91; 93; 94; 95]
Line 476 ⟶ 1,398:
</pre>
 
=={{Headerheader|ForthFactor}}==
{{works with|Factor|0.98}}
<lang forth>: semiprime?
<syntaxhighlight lang="text">USING: io kernel math.primes.factors prettyprint sequences ;
 
: semiprime? ( n -- ? ) factors length 2 = ;</syntaxhighlight>
 
Displaying the semiprimes under 100:
 
<syntaxhighlight lang="text">100 <iota> [ semiprime? ] filter [ bl ] [ pprint ] interleave nl</syntaxhighlight>
{{out}}
<pre>
4 6 9 10 14 15 21 22 25 26 33 34 35 38 39 46 49 51 55 57 58 62 65 69 74 77 82 85 86 87 91 93 94 95
</pre>
 
=={{header|Forth}}==
<syntaxhighlight lang="forth">: semiprime?
0 swap dup 2 do
begin dup i mod 0= while i / swap 1+ swap repeat
Line 484 ⟶ 1,420:
;
 
: test 100 2 do i semiprime? if i . then loop cr ;</langsyntaxhighlight>
{{out}}
<pre>
Line 490 ⟶ 1,426:
ok
</pre>
 
=={{Header|Go}}==
=={{header|Frink}}==
<lang go>package main
<syntaxhighlight lang="frink">isSemiprime[n] := length[factorFlat[n]] == 2</syntaxhighlight>
 
=={{header|Go}}==
<syntaxhighlight lang="go">package main
 
import "fmt"
Line 513 ⟶ 1,453:
fmt.Println(v, "->", semiprime(v))
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 526 ⟶ 1,466:
=={{header|Haskell}}==
{{libheader|Data.Numbers.Primes}}
<langsyntaxhighlight Haskelllang="haskell">isSemiprime :: Int -> Bool
isSemiprime n = (length factors) == 2 && (product factors) == n ||
(length factors) == 1 && (head factors) ^ 2 == n
where factors = primeFactors n</langsyntaxhighlight>
 
Alternative (and faster) implementation using pattern matching:
<langsyntaxhighlight Haskelllang="haskell">isSemiprime :: Int -> Bool
isSemiprime n = case (primeFactors n) of
[f1, f2] -> f1 * f2 == n
otherwise -> False</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
 
Works in both languages:
<langsyntaxhighlight lang="unicon">link "factors"
 
procedure main(A)
Line 548 ⟶ 1,488:
procedure semiprime(n) # Succeeds and produces the factors only if n is semiprime.
return (2 = *(nf := factors(n)), nf)
end</langsyntaxhighlight>
 
{{Out}}
Line 562 ⟶ 1,502:
Implementation:
 
<langsyntaxhighlight Jlang="j">isSemiPrime=: 2 = #@q: ::0:"0</langsyntaxhighlight>
 
Example use: find all semiprimes less than 100:
 
<langsyntaxhighlight Jlang="j"> I. isSemiPrime i.100
4 6 9 10 14 15 21 22 25 26 33 34 35 38 39 46 49 51 55 57 58 62 65 69 74 77 82 85 86 87 91 93 94 95</langsyntaxhighlight>
 
Description: factor the number and count the primes in the factorization, is it 2?
Line 576 ⟶ 1,516:
 
Like the Ada example here, this borrows from [[Prime decomposition#Java|Prime decomposition]] and shows the semiprimes below 100 and from 1675 to 1680.
<langsyntaxhighlight lang="java5">import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
Line 632 ⟶ 1,572:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>4 6 9 10 14 15 21 22 25 26 27 33 34 35 38 39 46 49 51 55 57 58 62 65 69 74 77 81 82 85 86 87 91 93 94 95
1678 1679</pre>
 
=={{header|jq}}==
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
<syntaxhighlight lang="jq">
def is_semiprime:
{i: 2, n: ., nf: 0}
| until( .i > .n or .result;
until(.n % .i != 0 or .result;
if .nf == 2 then .result = 0
else .nf += 1
| .n /= .i
end)
| .i += 1)
| if .result == 0 then false else .nf == 2 end;
</syntaxhighlight>
'''Examples'''
<syntaxhighlight lang="jq">
(1679, 1680) | "\(.) => \(is_semiprime)"
</syntaxhighlight>
{{out}}
<pre>
1679 => true
1680 => false
</pre>
 
=={{header|Julia}}==
{{works with|Julia|0.6}}
(Uses the built-in <code>factor</code> function.)
 
<lang julia>semiprime(n) = sum(values(factor(n))) == 2</lang>
<syntaxhighlight lang="julia">using Primes
issemiprime(n::Integer) = sum(values(factor(n))) == 2
@show filter(issemiprime, 1:100)</syntaxhighlight>
 
{{out}}
<pre>filter(issemiprime, 1:100) = [4, 6, 9, 10, 14, 15, 21, 22, 25, 26, 33, 34, 35, 38, 39, 46, 49, 51, 55, 57, 58, 62, 65, 69, 74, 77, 82, 85, 86, 87, 91, 93, 94, 95]</pre>
<pre>julia> filter(semiprime, 1:100)
 
[4,6,9,10,14,15,21,22,25,26,33,34,35,38,39,46,49,51,55,57,58,62,65,69,74,77,82,85,86,87,91,93,94,95]</pre>
=={{header|Kotlin}}==
{{trans|Go}}
<syntaxhighlight lang="scala">// version 1.1.2
 
fun isSemiPrime(n: Int): Boolean {
var nf = 0
var nn = n
for (i in 2..nn)
while (nn % i == 0) {
if (nf == 2) return false
nf++
nn /= i
}
return nf == 2
}
 
fun main(args: Array<String>) {
for (v in 1675..1680)
println("$v ${if (isSemiPrime(v)) "is" else "isn't"} semi-prime")
}</syntaxhighlight>
 
{{out}}
<pre>
1675 isn't semi-prime
1676 isn't semi-prime
1677 isn't semi-prime
1678 is semi-prime
1679 is semi-prime
1680 isn't semi-prime
</pre>
 
=={{header|Ksh}}==
<syntaxhighlight lang="ksh">
#!/bin/ksh
 
# Semiprime - As translated from C
 
# # Variables:
#
 
# # Functions:
#
# Function _issemiprime(p2) - return 1 if p2 semiprime, 0 if not
#
function _issemiprime {
typeset _p2 ; integer _p2=$1
typeset _p _f ; integer _p _f=0
 
for ((_p=2; (_f<2 && _p*_p<=_p2); _p++)); do
while (( _p2 % _p == 0 )); do
(( _p2 /= _p ))
(( _f++ ))
done
done
 
return $(( _f + (_p2 > 1) == 2 ))
}
 
######
# main #
######
 
integer i
for ((i=2; i<100; i++)); do
_issemiprime ${i}
(( $? )) && printf " %d" ${i}
done
echo
</syntaxhighlight>
{{out}}<pre>
4 6 9 10 14 15 21 22 25 26 33 34 35 38 39 46 49 51 55 57 58 62 65 69 74 77 82 85 86 87 91 93 94 95
</pre>
 
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
 
{def factors
{def factors.r
{lambda {:n :i}
{if {> :i :n}
then
else {if {= {% :n :i} 0}
then :i {factors.r {/ :n :i} :i}
else {factors.r :n {+ :i 1}} }}}}
{lambda {:n}
{A.new {factors.r :n 2} }}}
-> factors
 
{factors 491} -> [491] // prime
{factors 492} -> [2,2,3,41]
{factors 493} -> [17,29] // semiprime
{factors 494} -> [2,13,19]
{factors 495} -> [3,3,5,11]
{factors 496} -> [2,2,2,2,31]
{factors 497} -> [7,71] // semiprime
{factors 498} -> [2,3,83]
{factors 499} -> [499] // prime
{factors 500} -> [2,2,5,5,5]
 
{S.replace \s by space in
{S.map {lambda {:i}
{let { {:i :i} {:f {factors :i}}
} {if {= {A.length :f} 2}
then :i={A.first :f}*{A.last :f}
else}} }
{S.serie 1 100}}}
->
4 = 2*2
6 = 2*3
9 = 3*3
10 = 2*5
14 = 2*7
15 = 3*5
21 = 3*7
22 = 2*11
25 = 5*5
26 = 2*13
33 = 3*11
34 = 2*17
35 = 5*7
38 = 2*19
39 = 3*13
46 = 2*23
49 = 7*7
51 = 3*17
55 = 5*11
57 = 3*19
58 = 2*29
62 = 2*31
65 = 5*13
69 = 3*23
74 = 2*37
77 = 7*11
82 = 2*41
85 = 5*17
86 = 2*43
87 = 3*29
91 = 7*13
93 = 3*31
94 = 2*47
95 = 5*19
</syntaxhighlight>
 
=={{header|Lingo}}==
<syntaxhighlight lang="lingo">on isSemiPrime (n)
div = 2
cnt = 0
repeat while cnt < 3 and n <> 1
if n mod div = 0 then
n = n / div
cnt = cnt + 1
else
div = div + 1
end if
end repeat
return cnt=2
end</syntaxhighlight>
 
<syntaxhighlight lang="lingo">res = []
repeat with i = 1 to 100
if isSemiPrime(i) then res.add(i)
end repeat
put res</syntaxhighlight>
 
{{out}}
<pre>
-- [4, 6, 9, 10, 14, 15, 21, 22, 25, 26, 33, 34, 35, 38, 39, 46, 49, 51, 55, 57, 58, 62, 65, 69, 74, 77, 82, 85, 86, 87, 91, 93, 94, 95]
</pre>
 
=={{header|Lua}}==
<syntaxhighlight lang="lua">
function semiprime (n)
local divisor, count = 2, 0
while count < 3 and n ~= 1 do
if n % divisor == 0 then
n = n / divisor
count = count + 1
else
divisor = divisor + 1
end
end
return count == 2
end
 
for n = 1675, 1680 do
print(n, semiprime(n))
end
</syntaxhighlight>
{{out}}
<pre>
1675 false
1676 false
1677 false
1678 true
1679 true
1680 false
</pre>
 
=={{header|Maple}}==
<langsyntaxhighlight Maplelang="maple">SemiPrimes := proc( n )
local fact;
fact := numtheoryNumberTheory:-divisorsDivisors( n ) minus {1, n};
if numelems( fact ) in {1,2} and not( member( 'false', isprime ~ ( fact ) ) ) then
return n;
Line 654 ⟶ 1,820:
end if;
end proc:
{ seq( SemiPrimeSemiPrimes( i ), i = 1..100 ) };</langsyntaxhighlight>
Output:
<syntaxhighlight lang="maple">
<lang Maple>
{ 4,6,9,10,14,15,21,22,25,26,33,34,35,38,39,46,49,51,55,57,58,62,65,69,74,77,82,85,86,87,91,93,94,95 }
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">semiPrimeQ[n_Integer] := Module[{factors, numfactors},
factors = FactorInteger[n] // Transpose;
numfactors = factors[[2]] // Total ;
numfactors == 2
]</syntaxhighlight>
]
</lang>
Example use: find all semiprimes less than 100:
<langsyntaxhighlight Mathematicalang="mathematica">semiPrimeQ[#] & /@ Range[100];
Position[%, True] // Flatten</langsyntaxhighlight>
{{outputout}}
<pre>{4, 6, 9, 10, 14, 15, 21, 22, 25, 26, 33, 34, 35, 38, 39, 46, 49, 51,
55, 57, 58, 62, 65, 69, 74, 77, 82, 85, 86, 87, 91, 93, 94, 95}</pre>
 
=={{header|Maxima}}==
<syntaxhighlight lang="maxima">
/* The first part consider the cases of squares of primes, the second part the remaining cases */
semiprimep(n):=if integerp(sqrt(n)) and primep(sqrt(n)) then true else lambda([x],length(ifactors(x))=2 and unique(map(second,ifactors(x)))=[1])(n)$
 
/* Example */
sublist(makelist(i,i,100),semiprimep);
</syntaxhighlight>
{{out}}
<pre>
[4,6,9,10,14,15,21,22,25,26,33,34,35,38,39,46,49,51,55,57,58,62,65,69,74,77,82,85,86,87,91,93,94,95]
</pre>
 
=={{header|MiniScript}}==
<syntaxhighlight lang="miniscript">isSemiprime = function(num)
divisor = 2
primes = 0
while primes < 3 and num != 1
if num % divisor == 0 then
num = num / divisor;
primes = primes + 1
else
divisor = divisor + 1
end if
end while
return primes == 2
end function
 
print "Semiprimes up to 100:"
results = []
for i in range(2, 100)
if isSemiprime(i) then results.push i
end for
print results</syntaxhighlight>
 
{{output}}
<pre>Semiprimes up to 100:
[4, 6, 9, 10, 14, 15, 21, 22, 25, 26, 33, 34, 35, 38, 39, 46, 49, 51,
55, 57, 58, 62, 65, 69, 74, 77, 82, 85, 86, 87, 91, 93, 94, 95]</pre>
 
=={{header|NewLisp}}==
<syntaxhighlight lang="newlisp">
;;; Practically identical to the EchoLisp solution
(define (semiprime? n)
(= (length (factor n)) 2))
;
;;; Example (sadly factor doesn't accept bigints)
(println (filter semiprime? (sequence 2 100)))
(setq x 9223372036854775807)
(while (not (semiprime? x)) (-- x))
(println "Biggest semiprime reachable: " x " = " ((factor x) 0) " x " ((factor x) 1))
</syntaxhighlight>
{{output}}
<pre>
(4 6 9 10 14 15 21 22 25 26 33 34 35 38 39 46 49 51 55 57 58 62 65 69 74 77 82 85 86 87 91 93 94 95)
Biggest semiprime reachable: 9223372036854775797 = 3 x 3074457345618258599
</pre>
 
=={{header|Nim}}==
<syntaxhighlight lang="nim">proc isSemiPrime(k: int): bool =
var
i = 2
count = 0
x = k
while i <= x and count < 3:
if x mod i == 0:
x = x div i
inc count
else:
inc i
result = count == 2
for k in 1675..1680:
echo k, (if k.isSemiPrime(): " is" else: " isn’t"), " semi-prime"</syntaxhighlight>
 
{{output}}
<pre>1675 isn't semi-prime
1676 isn't semi-prime
1677 isn't semi-prime
1678 is semi-prime
1679 is semi-prime
1680 isn't semi-prime
</pre>
 
=={{header|Objeck}}==
{{trans|Go}}
<langsyntaxhighlight lang="objeck">
class SemiPrime {
function : Main(args : String[]) ~ Nil {
Line 701 ⟶ 1,950:
return nf = 2;
}
}</langsyntaxhighlight>
 
Output:
Line 708 ⟶ 1,957:
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">func: semiprime(n)
{
| i |
0 2 n sqrt asInteger for: i [ while(n i /mod swap 0 &=) [ ->n 1 + ] drop ]
n 1 > ifTrue: [ 1 + ] 2 == ; </syntaxhighlight>
}</lang>
 
{{out}}
Line 722 ⟶ 1,969:
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">issemi(n)=bigomega(n)==2</langsyntaxhighlight>
 
A faster version might use trial division and primality testing:
<langsyntaxhighlight lang="parigp">issemi(n)={
forprime(p=2,97,if(n%p==0, return(isprime(n/p))));
if(isprime(n), return(0));
bigomega(n)==2
};</langsyntaxhighlight>
 
To get faster, partial factorization can be used. At this time GP does not have access to meaningful partial factorization (though it can get it to some extent through flags on <code>factorint</code>), so this version is in PARI:
<langsyntaxhighlight lang="c">long
issemiprime(GEN n)
{
Line 808 ⟶ 2,055:
avma = ltop;
return 0; /* never used */
}</langsyntaxhighlight>
 
=={{header|Pascal}}==
{{libheader|primTrial}}{{works with|Free Pascal}}
 
<langsyntaxhighlight lang="pascal">program SemiPrime;
{$IFDEF FPC}
{$Mode objfpc}// compiler switch to use result
Line 852 ⟶ 2,100:
inc(i);
until i> k;
END.</langsyntaxhighlight>
;output:
<pre>
Line 872 ⟶ 2,120:
=={{header|Perl}}==
{{libheader|ntheory}}
With late versions of the ntheory module, we can use <tt>is_semiprime</tt> to get answers for 64-bit numbers in single microseconds.
<tt>factor</tt> in scalar context gives the number of factors (like <tt>bigomega</tt> in Pari/GP and <tt>PrimeOmega</tt> in Mathematica).
<langsyntaxhighlight lang="perl">use ntheory "factoris_semiprime";
for ([1..100], [1675..1681], [2,4,99,100,1679,5030,32768,1234567,9876543,900660121]) {
print join(" ", grep { scalar factor($_) == 2 } 1..100),"\n";
print join(" ", grep { scalar factoris_semiprime($_) == 2 } 1675..1681@$_),"\n";
}</syntaxhighlight>
print join(" ", grep { scalar factor($_) == 2 } (2,4,99,100,1679,5040,32768,1234567,9876543,900660121)),"\n";</lang>
{{out}}
<pre>4 6 9 10 14 15 21 22 25 26 33 34 35 38 39 46 49 51 55 57 58 62 65 69 74 77 82 85 86 87 91 93 94 95
Line 882 ⟶ 2,130:
4 1679 1234567 900660121</pre>
 
One can also use <tt>factor</tt> in scalar context, which gives the number of factors (like <tt>bigomega</tt> in Pari/GP and <tt>PrimeOmega</tt> in Mathematica). This skips some optimizations but at these small sizes it doesn't matter.
Following Pari/GP's example, for inputs over 10^10 or so, we can save some time by looking for small factors first:
<syntaxhighlight lang ="perl">use ntheory qw/"factor is_prime trial_factor/";
print join(" ", grep { scalar factor($_) == 2 } 1..100),"\n";</syntaxhighlight>
 
While <tt>is_semiprime</tt> is the fastest way, we can do some of its pre-tests by hand, such as:
<syntaxhighlight lang="perl">use ntheory qw/factor is_prime trial_factor/;
sub issemi {
my $n = shift;
Line 891 ⟶ 2,143:
}
2 == factor($n);
}</langsyntaxhighlight>
 
=={{header|Perl 6Phix}}==
<!--<syntaxhighlight lang="phix">-->
Here is a naive, grossly inefficient implementation.
<span style="color: #008080;">function</span> <span style="color: #000000;">semiprime</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
<lang perl6>sub is-semiprime (Int $n --> Bool) {
<span style="color: #008080;">return</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">prime_factors</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #004600;">true</span><span style="color: #0000FF;">))==</span><span style="color: #000000;">2</span>
not $n.is-prime and
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
.is-prime given
<span style="color: #7060A8;">pp</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">filter</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #000000;">100</span><span style="color: #0000FF;">)&</span><span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1680</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1675</span><span style="color: #0000FF;">),</span><span style="color: #000000;">semiprime</span><span style="color: #0000FF;">),{</span><span style="color: #004600;">pp_IntCh</span><span style="color: #0000FF;">,</span><span style="color: #004600;">false</span><span style="color: #0000FF;">})</span>
$n div first $n %% *,
<!--</syntaxhighlight>-->
grep &is-prime, 2 .. *;
{{out}}
<pre>
{4,6,9,10,14,15,21,22,25,26,33,34,35,38,39,46,49,51,55,57,58,62,65,69,74,77,
82,85,86,87,91,93,94,95,1678,1679}
</pre>
 
=={{header|PHP}}==
{{trans|TypeScript}}
<syntaxhighlight lang="php">
<?php
// Semiprime
 
function primeFactorsCount($n)
{
$n = abs($n);
$count = 0; // Result
if ($n >= 2)
for ($factor = 2; $factor <= $n; $factor++)
while ($n % $factor == 0) {
$count++;
$n /= $factor;
}
return $count;
}
 
echo "Enter an integer: ",
use Test;
$n = (int)fgets(STDIN);
my @primes = grep &is-prime, 2 .. 100;
echo (primeFactorsCount($n) == 2 ?
for ^5 {
nok "It is- a semiprime([*].\n" my: @f1"It =is @primesnot a semiprime.roll(1\n")), ~@f1;
?>
ok is-semiprime([*] my @f2 = @primes.roll(2)), ~@f2;
</syntaxhighlight>
nok is-semiprime([*] my @f3 = @primes.roll(3)), ~@f3;
nok is-semiprime([*] my @f4 = @primes.roll(4)), ~@f4;
}</lang>
{{out}}
<pre>ok 1 - 17
Enter an integer: 60
ok 2 - 47 23
It is not a semiprime.
ok 3 - 23 37 41
</pre>
ok 4 - 53 37 67 47
<pre>
ok 5 - 5
Enter an integer: 33
ok 6 - 73 43
It is a semiprime.
ok 7 - 13 53 71
</pre>
ok 8 - 7 79 37 71
ok 9 - 41
ok 10 - 71 37
ok 11 - 37 53 43
ok 12 - 3 2 47 67
ok 13 - 17
ok 14 - 41 61
ok 15 - 71 31 79
ok 16 - 97 17 73 17
ok 17 - 61
ok 18 - 73 47
ok 19 - 13 19 5
ok 20 - 37 97 11 31</pre>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de factor (N)
(make
(let
Line 953 ⟶ 2,214:
(conc (range 1 100) (range 1675 1680)) ) )
(bye)</langsyntaxhighlight>
{{out}}
<pre>(4 6 9 10 14 15 21 22 25 26 33 34 35 38 39 46 49 51 55 57 58 62 65 69 74 77 82 85 86 87 91 93 94 95 1678 1679)</pre>
 
=={{header|PL/0}}==
{{trans|Tiny BASIC}}
PL/0 does not handle strings. So, the program waits for entering a number, and then displays 1 if the number is a semiprime, 0 otherwise.
<syntaxhighlight lang="pascal">
var n, count, factor;
begin
? n;
if n < 0 then n := -n;
count := 0;
if n >= 2 then
begin
factor := 2;
while factor <= n do
begin
while (n / factor) * factor = n do
begin
count := count + 1; n := n / factor
end;
factor := factor + 1
end;
end;
if count = 2 then ! 1;
if count <> 2 then ! 0
end.
</syntaxhighlight>
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">*process source attributes xref nest or(!);
/*--------------------------------------------------------------------
* 22.02.2014 Walter Pachl using the is_prime code from
Line 1,047 ⟶ 2,334:
 
End spb;
</syntaxhighlight>
</lang>
'''Output:'''
<pre> 900660121 1 is semiprime 30011*30011
Line 1,059 ⟶ 2,346:
100 0 is NOT semiprime 2*2*25
5040 0 is NOT semiprime 2*2*1260</pre>
 
=={{header|PL/M}}==
{{Trans|C++}}
{{works with|8080 PL/M Compiler}} ... under CP/M (or an emulator)
<syntaxhighlight lang="plm">
100H: /* FIND SOME SEMI-PRIMES - NUMBERS WITH EXACTLY 2 PRIME FACTORS */
 
/* CP/M BDOS SYSTEM CALL AND I/O ROUTINES */
BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END;
PR$CHAR: PROCEDURE( C ); DECLARE C BYTE; CALL BDOS( 2, C ); END;
PR$STRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S ); END;
PR$NL: PROCEDURE; CALL PR$CHAR( 0DH ); CALL PR$CHAR( 0AH ); END;
PR$NUMBER: PROCEDURE( N ); /* PRINTS A NUMBER IN THE MINIMUN FIELD WIDTH */
DECLARE N ADDRESS;
DECLARE V ADDRESS, N$STR ( 6 )BYTE, W BYTE;
V = N;
W = LAST( N$STR );
N$STR( W ) = '$';
N$STR( W := W - 1 ) = '0' + ( V MOD 10 );
DO WHILE( ( V := V / 10 ) > 0 );
N$STR( W := W - 1 ) = '0' + ( V MOD 10 );
END;
CALL PR$STRING( .N$STR( W ) );
END PR$NUMBER;
 
/* TASK */
 
/* RETURNS TRUE IF V IS SEMI-PRIME, FALSE OTHERWISE */
IS$SEMI$PRIME: PROCEDURE( V )BYTE;
DECLARE V ADDRESS;
DECLARE ( A, B, C ) ADDRESS;
A = 2; B = 0; C = V;
DO WHILE B < 3 AND C > 1;
IF C MOD A = 0 THEN DO;
C = C / A;
B = B + 1;
END;
ELSE A = A + 1;
END;
RETURN B = 2;
END IS$SEMI$PRIME;
 
DECLARE X ADDRESS;
DO X = 2 TO 99;
IF IS$SEMI$PRIME( X ) THEN DO;
CALL PR$NUMBER( X );
CALL PR$CHAR( ' ' );
END;
END;
 
EOF
</syntaxhighlight>
{{out}}
<pre>
4 6 9 10 14 15 21 22 25 26 33 34 35 38 39 46 49 51 55 57 58 62 65 69 74 77 82 85 86 87 91 93 94 95
</pre>
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function isPrime ($n) {
if ($n -le 1) {$false}
Line 1,082 ⟶ 2,425:
$OFS = " x "
"1679: $(semiprime 1679)"
"87: $(semiprime 87)"
"25: $(semiprime 25)"
"12: $(semiprime 12)"
"6: $(semiprime 6)"
$OFS = " "
"semiprime formfrom 1 to 100: $(1..100 | where {semiprime $_})"
</syntaxhighlight>
</lang>
<b>Output:</b>
<pre>
1679: 23 x 73
87: 3 x 29
25: 5 x 5
12:
6: 2 x 3
semiprime formfrom 1 to 100: 4 6 9 10 14 15 21 22 25 26 33 34 35 38 39 46 49 51 55 57 58 62 65 69 74 77 82 85 86 87 91 93 94 95
</pre>
 
=={{header|Prolog}}==
works with swi-prolog
<syntaxhighlight lang="prolog">
factors(N, FList):-
factors(N, 2, 0, FList).
 
factors(1, _, _Count, []).
factors(_, _, Count, []):- Count > 1. % break on 2 factors reached
factors(N, Start, Count, [Fac|FList]):-
N1 is floor(sqrt(N)),
between(Start, N1, Fac),
N mod Fac =:= 0,!,
N2 is N div Fac,
Count1 is Count + 1,
factors(N2, Fac, Count1, FList).
factors(N, _, _, [N]):- N >= 2.
 
semiPrimeList(Limit, List):-
findall(N, semiPrimes(2, Limit, N), List).
 
semiPrimes(Start, Limit, N):-
between(Start, Limit, N),
factors(N, [F1, F2]),
N =:= F1 * F2. % correct factors break
 
do:- semiPrimeList(100, SemiPrimes),
writeln(SemiPrimes),
findall(N, semiPrimes(1675, 1685, N), SemiPrimes2),
writeln(SemiPrimes2).
</syntaxhighlight>
{{out}}
<pre>
?- do.
[4,6,9,10,14,15,21,22,25,26,33,34,35,38,39,46,49,51,55,57,58,62,65,69,74,77,82,85,86,87,91,93,94,95]
[1678,1679,1681,1685]
true.
</pre>
 
=={{header|PROMAL}}==
<syntaxhighlight lang="promal">
;;; find some semiprimes - numbers with two prime factors
 
PROGRAM semiPrimes
INCLUDE library
 
FUNC BYTE isSemiPrime
ARG WORD n
WORD f
WORD factorCount
BYTE result
BEGIN
f = 2
factorCount = 0
WHILE factorCount < 3 AND n > 1
WHILE n % f = 0
factorCount = factorCount + 1
n = n / f
f = f + 1
IF factorCOunt = 2
result = 1
ELSE
result = 0
RETURN result
END
 
WORD n
BEGIN
OUTPUT "Semiprimes under 100:#C "
FOR n = 1 TO 99
IF isSemiPrime( n )
OUTPUT " #W", n
OUTPUT "#CSemiprimes between 1670 and 1690:#C "
FOR n = 1670 TO 1690
IF isSemiPrime( n )
OUTPUT " #W", n
END
</syntaxhighlight>
{{out}}
<pre>
Semiprimes under 100:
4 6 9 10 14 15 21 22 25 26 33 34 35 38 39 46 49 51 55 57 58 62 65 69 74 77 82 85 86 87 91 93 94 95
Semiprimes between 1670 and 1690:
1671 1673 1678 1679 1681 1685 1687 1689
</pre>
 
=={{header|Python}}==
This imports [[Prime decomposition#Python]]
<langsyntaxhighlight lang="python">from prime_decomposition import decompose
 
def semiprime(n):
Line 1,105 ⟶ 2,535:
try:
return next(d) * next(d) == n
except StopIteration:
return False</langsyntaxhighlight>
 
{{out}}
From Idle:
<langsyntaxhighlight lang="python">>>> semiprime(1679)
True
>>> [n for n in range(1,101) if semiprime(n)]
[4, 6, 9, 10, 14, 15, 21, 22, 25, 26, 33, 34, 35, 38, 39, 46, 49, 51, 55, 57, 58, 62, 65, 69, 74, 77, 82, 85, 86, 87, 91, 93, 94, 95]
>>> </langsyntaxhighlight>
 
=={{header|Quackery}}==
 
<code>primefactors</code> is defined at [http://rosettacode.org/wiki/Prime_decomposition#Quackery Prime decomposition].
 
<syntaxhighlight lang="quackery"> [ primefactors size 2 = ] is semiprime ( n --> b )
 
say "Semiprimes less than 100:" cr
100 times [ i^ semiprime if [ i^ echo sp ] ]</syntaxhighlight>
 
{{out}}
 
<pre>Semiprimes less than 100:
4 6 9 10 14 15 21 22 25 26 33 34 35 38 39 46 49 51 55 57 58 62 65 69 74 77 82 85 86 87 91 93 94 95</pre>
 
=={{header|Racket}}==
The first implementation considers all pairs of factors multiplying up to the given number and determines if any of them is a pair of primes.
<langsyntaxhighlight Racketlang="racket">#lang racket
(require math)
 
Line 1,132 ⟶ 2,576:
(for/or ((pair (pair-factorize n)))
(for/and ((el pair))
(prime? el))))</langsyntaxhighlight>
 
The alternative implementation operates directly on the list of prime factors and their multiplicities. It is approximately 1.6 times faster than the first one (according to some simple tests of mine).
<langsyntaxhighlight Racketlang="racket">#lang racket
(require math)
 
Line 1,146 ⟶ 2,590:
(= (expt (caar prime-factors) (cadar prime-factors)) n))
(and (= (length prime-factors) 2)
(= (foldl (λ (x y) (* (car x) y)) 1 prime-factors) n)))))</langsyntaxhighlight>
 
=={{header|Raku}}==
(formerly Perl 6)
Here is a naive, grossly inefficient implementation.
<syntaxhighlight lang="raku" line>sub is-semiprime (Int $n --> Bool) {
not $n.is-prime and
.is-prime given
$n div first $n %% *, flat grep &is-prime, 2 .. *;
}
 
use Test;
my @primes = flat grep &is-prime, 2 .. 100;
for ^5 {
nok is-semiprime([*] my @f1 = @primes.roll(1)), ~@f1;
ok is-semiprime([*] my @f2 = @primes.roll(2)), ~@f2;
nok is-semiprime([*] my @f3 = @primes.roll(3)), ~@f3;
nok is-semiprime([*] my @f4 = @primes.roll(4)), ~@f4;
}</syntaxhighlight>
{{out}}
<pre>ok 1 - 17
ok 2 - 47 23
ok 3 - 23 37 41
ok 4 - 53 37 67 47
ok 5 - 5
ok 6 - 73 43
ok 7 - 13 53 71
ok 8 - 7 79 37 71
ok 9 - 41
ok 10 - 71 37
ok 11 - 37 53 43
ok 12 - 3 2 47 67
ok 13 - 17
ok 14 - 41 61
ok 15 - 71 31 79
ok 16 - 97 17 73 17
ok 17 - 61
ok 18 - 73 47
ok 19 - 13 19 5
ok 20 - 37 97 11 31</pre>
 
===More efficient example===
Here is a more verbose, but MUCH more efficient implementation. Demonstrating using it to find an infinite list of semiprimes and to check a range of integers to find the semiprimes.
{{works with|Rakudo|2017.02}}
 
<syntaxhighlight lang="raku" line>sub is-semiprime ( Int $n where * > 0 ) {
return False if $n.is-prime;
my $factor = find-factor( $n );
return True if $factor.is-prime && ( $n div $factor ).is-prime;
False;
}
 
sub find-factor ( Int $n, $constant = 1 ) {
my $x = 2;
my $rho = 1;
my $factor = 1;
while $factor == 1 {
$rho *= 2;
my $fixed = $x;
for ^$rho {
$x = ( $x * $x + $constant ) % $n;
$factor = ( $x - $fixed ) gcd $n;
last if 1 < $factor;
}
}
$factor = find-factor( $n, $constant + 1 ) if $n == $factor;
$factor;
}
 
INIT my $start = now;
 
# Infinite list of semiprimes
constant @semiprimes = lazy gather for 4 .. * { .take if .&is-semiprime };
 
# Show the semiprimes < 100
say 'Semiprimes less than 100:';
say @semiprimes[^ @semiprimes.first: * > 100, :k ], "\n";
 
# Check individual integers, or in this case, a range
my $s = 2⁹⁷ - 1;
say "Is $_ semiprime?: ", .&is-semiprime for $s .. $s + 30;
 
say 'elapsed seconds: ', now - $start;
</syntaxhighlight>
{{out}}
<pre>Semiprimes less than 100:
(4 6 9 10 14 15 21 22 25 26 33 34 35 38 39 46 49 51 55 57 58 62 65 69 74 77 82 85 86 87 91 93 94 95)
 
Is 158456325028528675187087900671 semiprime?: True
Is 158456325028528675187087900672 semiprime?: False
Is 158456325028528675187087900673 semiprime?: False
Is 158456325028528675187087900674 semiprime?: False
Is 158456325028528675187087900675 semiprime?: False
Is 158456325028528675187087900676 semiprime?: False
Is 158456325028528675187087900677 semiprime?: False
Is 158456325028528675187087900678 semiprime?: False
Is 158456325028528675187087900679 semiprime?: False
Is 158456325028528675187087900680 semiprime?: False
Is 158456325028528675187087900681 semiprime?: False
Is 158456325028528675187087900682 semiprime?: False
Is 158456325028528675187087900683 semiprime?: False
Is 158456325028528675187087900684 semiprime?: False
Is 158456325028528675187087900685 semiprime?: False
Is 158456325028528675187087900686 semiprime?: False
Is 158456325028528675187087900687 semiprime?: False
Is 158456325028528675187087900688 semiprime?: False
Is 158456325028528675187087900689 semiprime?: False
Is 158456325028528675187087900690 semiprime?: False
Is 158456325028528675187087900691 semiprime?: False
Is 158456325028528675187087900692 semiprime?: False
Is 158456325028528675187087900693 semiprime?: False
Is 158456325028528675187087900694 semiprime?: False
Is 158456325028528675187087900695 semiprime?: False
Is 158456325028528675187087900696 semiprime?: False
Is 158456325028528675187087900697 semiprime?: False
Is 158456325028528675187087900698 semiprime?: False
Is 158456325028528675187087900699 semiprime?: False
Is 158456325028528675187087900700 semiprime?: False
Is 158456325028528675187087900701 semiprime?: True
elapsed seconds: 0.0574433</pre>
 
=={{header|REXX}}==
===version 1===
<langsyntaxhighlight lang="rexx">/* REXX ---------------------------------------------------------------
* 20.02.2014 Walter Pachl relying on 'prime decomposition'
* 21.02.2014 WP Clarification: I copied the algorithm created by
Line 1,205 ⟶ 2,768:
z=z%j /*% (percent) is integer divide.*/
end /*while z··· */ /* // ?---remainder integer ÷.*/
return /*finished, now return to invoker*/</langsyntaxhighlight>
'''Output'''
<pre>4 is semiprime 2 2
Line 1,214 ⟶ 2,777:
 
===version 2===
The method used is to examine numbersintegers, skipping primes.
 
If it's composite (the 1<sup>st</sup> factor is prime), then check if the 2<sup>nd</sup> factor is prime. &nbsp; If so, the number is a &nbsp; ''semiprime''.
 
The &nbsp; '''isPrime''' &nbsp; function could be optimized by utilizing an integer square root function instead of testing if &nbsp; '''j*j>x''' &nbsp; for every divisor.
<langsyntaxhighlight lang="rexx">/*REXX program determines if any numberinteger (or a range of integers) is/are semiprime. */
parse arg bot top . /*obtain optional numbersarguments from the C.L.CL*/
if bot=='' | bot=="," then bot=random() /*None given? User wants us to guess.*/
if top=='' | top=="," then top=bot /*maybe define a range of numbers. */
tell= top=>0 | top==bot /*should results be shown to the term? */
w=max(length(bot), length(top)) /*obtain the maximum width of numbers. */
numeric digits w=max(9length(bot),w length(top)) + 5 /*ensureobtain the maximum there'rewidth enoughof decimalnumbers. digits*/
numeric digits max(9, w) do n=bot to top /*show results for aensure rangethere're ofenough numbers.decimal digits*/
#=0 if isSemiPrime(n) then say right(n,w) " is semiprime." /*initialize number of semiprimes found*/
do n=bot to abs(top) else/*show sayresults right(n,w)for a range of numbers. " isn't semiprime."*/
?=isSemiPrime(n); #=#+? /*Is N a semiprime?; Maybe bump counter*/
if tell then say right(n,w) right(word("isn't" 'is', ?+1), 6) 'semiprime.'
end /*n*/
say
exit /*stick a fork in it, we're all done. */
if bot\==top then say 'found ' # " semiprimes."
/*────────────────────────────────────────────────────────────────────────────*/
exit /*stick a fork in it, we're all done. */
isPrime: procedure; parse arg x; if x<2 then return 0 /*number too low*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
if wordpos(x, '2 3 5 7 11 13 17 19 23')\==0 then return 1 /*it's low prime*/
ifisPrime: x//2==0procedure; thenparse returnarg 0x; if x//3==0 if x<2 then return 0 /*÷ by 2;÷number bytoo 3low?*/
do j=5 by 6 until j*j>if wordpos(x;, '2 if3 5 7 x//j11 13 17 19 23')\==0 then return 0 1 /*notit's alow prime. */
if x//2==0 then return 0; if x//(j+2)3==0 then return 0 /*÷ " " " by 2; ÷ by 3?*/
do j=5 by 6 until j*j>x; if x//j==0 then return 0 /*not a prime. */
end /*j*/
return 1 if x//(j+2)==0 then return 0 /*indicate that" " X" is a prime number. */
end /*j*/
/*────────────────────────────────────────────────────────────────────────────*/
return 1 /*indicate that X is a prime number. */
isSemiPrime: procedure; parse arg x; if \datatype(x,'W') | x<4 then return 0
/*──────────────────────────────────────────────────────────────────────────────────────*/
x=x/1
isSemiPrime: procedure; parse arg x; do i=2 for 2; if x//i==0 then if isPrime(x%i)<4 then return 10
 
else return 0
end /* do i*=2 for 2; if x//i==0 then if isPrime(x%i) then return 1
/* ___ */ else return 0
do j=5 by 6; if j*j>x then return 0 end /* > √ x ? i*/
/* ___ */
do k=j by 2 for 2; if x//k==0 then if isPrime(x%k) then return 1
do j=5 by 6; if j*j>x then return 0 /* > x else return 0?*/
end /*k*/ do k=j by 2 for 2; if x/*/k==0 [↑] then see if 2ndisPrime(x%k) factor isthen primereturn or ¬*/1
end /*j*/ /* [↑] never ÷ by J if J is mult. of 3*/</lang> else return 0
end /*k*/ /* [↑] see if 2nd factor is prime or ¬*/
'''output''' &nbsp; when the input is: &nbsp; <tt> -1 &nbsp; 106 </tt>
end /*j*/ /* [↑] J is never a multiple of three.*/</syntaxhighlight>
<pre style="height:40ex">
{{out|output|text=&nbsp; when using the input of: &nbsp; <tt> -1 &nbsp; 106 </tt>}}
-1 isn't semiprime.
 
0 isn't semiprime.
(Shown at &nbsp; <big> '''<sup>5</sup>/<sub>6</sub>''' </big> &nbsp; size.)
1 isn't semiprime.
<pre style="font-size:84%;height:100ex">
2 isn't semiprime.
3 -1 isn't semiprime.
4 is0 isn't semiprime.
5 1 isn't semiprime.
6 is2 isn't semiprime.
7 3 isn't semiprime.
8 isn't 4 is semiprime.
9 is5 isn't semiprime.
10 6 is semiprime.
11 7 isn't semiprime.
12 8 isn't semiprime.
13 isn't 9 is semiprime.
14 10 is semiprime.
15 is 11 isn't semiprime.
16 12 isn't semiprime.
17 13 isn't semiprime.
18 isn't 14 is semiprime.
19 isn't 15 is semiprime.
20 16 isn't semiprime.
21 is 17 isn't semiprime.
22 is 18 isn't semiprime.
23 19 isn't semiprime.
24 20 isn't semiprime.
25 21 is semiprime.
26 22 is semiprime.
27 23 isn't semiprime.
28 24 isn't semiprime.
29 isn't 25 is semiprime.
30 isn't 26 is semiprime.
31 27 isn't semiprime.
32 28 isn't semiprime.
33 is 29 isn't semiprime.
34 is 30 isn't semiprime.
35 is 31 isn't semiprime.
36 32 isn't semiprime.
37 isn't 33 is semiprime.
38 34 is semiprime.
39 35 is semiprime.
40 36 isn't semiprime.
41 37 isn't semiprime.
42 isn't 38 is semiprime.
43 isn't 39 is semiprime.
44 40 isn't semiprime.
45 41 isn't semiprime.
46 is 42 isn't semiprime.
47 43 isn't semiprime.
48 44 isn't semiprime.
49 is 45 isn't semiprime.
50 isn't 46 is semiprime.
51 is 47 isn't semiprime.
52 48 isn't semiprime.
53 isn't 49 is semiprime.
54 50 isn't semiprime.
55 51 is semiprime.
56 52 isn't semiprime.
57 is 53 isn't semiprime.
58 is 54 isn't semiprime.
59 isn't 55 is semiprime.
60 56 isn't semiprime.
61 isn't 57 is semiprime.
62 58 is semiprime.
63 59 isn't semiprime.
64 60 isn't semiprime.
65 is 61 isn't semiprime.
66 isn't 62 is semiprime.
67 63 isn't semiprime.
68 64 isn't semiprime.
69 65 is semiprime.
70 66 isn't semiprime.
71 67 isn't semiprime.
72 68 isn't semiprime.
73 isn't 69 is semiprime.
74 is 70 isn't semiprime.
75 71 isn't semiprime.
76 72 isn't semiprime.
77 is 73 isn't semiprime.
78 isn't 74 is semiprime.
79 75 isn't semiprime.
80 76 isn't semiprime.
81 isn't 77 is semiprime.
82 is 78 isn't semiprime.
83 79 isn't semiprime.
84 80 isn't semiprime.
85 is 81 isn't semiprime.
86 82 is semiprime.
87 is 83 isn't semiprime.
88 84 isn't semiprime.
89 isn't 85 is semiprime.
90 isn't 86 is semiprime.
91 87 is semiprime.
92 88 isn't semiprime.
93 is 89 isn't semiprime.
94 is 90 isn't semiprime.
95 91 is semiprime.
96 92 isn't semiprime.
97 isn't 93 is semiprime.
98 isn't 94 is semiprime.
99 isn't 95 is semiprime.
100 96 isn't semiprime.
101 97 isn't semiprime.
102 98 isn't semiprime.
103 99 isn't semiprime.
104 100 isn't semiprime.
105 101 isn't semiprime.
106 is102 isn't semiprime.
103 isn't semiprime.
104 isn't semiprime.
105 isn't semiprime.
106 is semiprime.
 
found 35 semiprimes.
</pre>
'''{{out|output''' |text=&nbsp; when using the input isof: &nbsp; <tt> 99888111555 &nbsp; 99888111600 </tt>}}
 
<pre style="height:40ex">
(Shown at &nbsp; <big> '''<sup>5</sup>/<sub>6</sub>''' </big> &nbsp; size.)
99888111555 isn't semiprime.
<pre style="font-size:84%;height:100ex">
99888111556 isn't semiprime.
99888111557 99888111555 isn't semiprime.
99888111558 99888111556 isn't semiprime.
99888111559 99888111557 isn't semiprime.
99888111560 99888111558 isn't semiprime.
99888111561 99888111559 isn't semiprime.
99888111562 99888111560 isn't semiprime.
99888111563 is99888111561 isn't semiprime.
99888111564 99888111562 isn't semiprime.
99888111565 isn't 99888111563 is semiprime.
99888111566 is99888111564 isn't semiprime.
99888111567 99888111565 isn't semiprime.
99888111568 isn't 99888111566 is semiprime.
99888111569 is99888111567 isn't semiprime.
99888111570 99888111568 isn't semiprime.
99888111571 isn't 99888111569 is semiprime.
99888111572 99888111570 isn't semiprime.
99888111573 99888111571 isn't semiprime.
99888111574 is99888111572 isn't semiprime.
99888111575 99888111573 isn't semiprime.
99888111576 isn't 99888111574 is semiprime.
99888111577 99888111575 isn't semiprime.
99888111578 is99888111576 isn't semiprime.
99888111579 99888111577 isn't semiprime.
99888111580 isn't 99888111578 is semiprime.
99888111581 99888111579 isn't semiprime.
99888111582 99888111580 isn't semiprime.
99888111583 99888111581 isn't semiprime.
99888111584 99888111582 isn't semiprime.
99888111585 99888111583 isn't semiprime.
99888111586 99888111584 isn't semiprime.
99888111587 99888111585 isn't semiprime.
99888111588 99888111586 isn't semiprime.
99888111589 99888111587 isn't semiprime.
99888111590 99888111588 isn't semiprime.
99888111591 is99888111589 isn't semiprime.
99888111592 99888111590 isn't semiprime.
99888111593 99888111591 is semiprime.
99888111594 99888111592 isn't semiprime.
99888111595 isn't 99888111593 is semiprime.
99888111596 99888111594 isn't semiprime.
99888111597 99888111595 isn't semiprime.
99888111598 99888111596 isn't semiprime.
99888111599 99888111597 isn't semiprime.
99888111600 99888111598 isn't semiprime.
99888111599 isn't semiprime.
99888111600 isn't semiprime.
 
found 7 semiprimes.
</pre>
 
===version 3, with memoization===
This REXX version is overt 20% faster than version 2 &nbsp; (when in the &nbsp; ''millions'' &nbsp; range).
 
If the 2<sup>nd</sup> argument &nbsp; ('''top''') &nbsp; is negative &nbsp; (it's absolute value is used), &nbsp; individual numbers in the range aren't shown, but the &nbsp; ''count'' &nbsp; of semiprimes found is shown.
 
It gets its speed increase by the use of memoization of the prime numbers found, an unrolled primality (division) check, and other speed improvements.
<syntaxhighlight lang="rexx">/*REXX program determines if any integer (or a range of integers) is/are semiprime. */
parse arg bot top . /*obtain optional arguments from the CL*/
if bot=='' | bot=="," then bot=random() /*None given? User wants us to guess.*/
if top=='' | top=="," then top=bot /*maybe define a range of numbers. */
tell= bot=>0 & top=>0 /*should results be shown to the term? */
w=max(length(bot), length(top)) /*obtain the maximum width of numbers. */
!.=; !.2=1; !.3=1; !.5=1; !.7=1; !.11=1; !.13=1; !.17=1; !.19=1; !.23=1; !.29=1; !.31=1
numeric digits max(9, w) /*ensure there're enough decimal digits*/
#=0 /*initialize number of semiprimes found*/
do n=abs(bot) to abs(top) /*show results for a range of numbers. */
?=isSemiPrime(n); #=#+? /*Is N a semiprime?; Maybe bump counter*/
if tell then say right(n,w) right(word("isn't" 'is', ?+1), 6) 'semiprime.'
end /*n*/
say
if bot\==top then say 'found ' # " semiprimes."
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
isPrime: procedure expose !.; parse arg x; if x<2 then return 0 /*number too low?*/
if !.x==1 then return 1 /*a known prime. */
if x// 2==0 then return 0; if x//3==0 then return 0 /*÷ by 2;÷by 3?*/
parse var x '' -1 _; if _==5 then return 0 /*last digit a 5?*/
if x// 7==0 then return 0; if x//11==0 then return 0 /*÷ by 7;÷by 11?*/
if x//13==0 then return 0; if x//17==0 then return 0 /*÷ by 13;÷by 17?*/
if x//19==0 then return 0; if x//23==0 then return 0 /*÷ by 19;÷by 23?*/
do j=29 by 6 until j*j>x; if x//j==0 then return 0 /*not a prime. */
if x//(j+2)==0 then return 0 /* " " " */
end /*j*/
!.x=1; return 1 /*indicate that X is a prime number. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
isSemiPrime: procedure expose !.; parse arg x; if x<4 then return 0
 
do i=2 for 2; if x//i==0 then if isPrime(x%i) then return 1
else return 0
end /*i*/
/* ___ */
do j=5 by 6 until j*j>x /* > √ x ?*/
do k=j by 2 for 2; if x//k==0 then if isPrime(x%k) then return 1
else return 0
end /*k*/ /* [↑] see if 2nd factor is prime or ¬*/
end /*j*/ /* [↑] J is never a multiple of three.*/
return 0</syntaxhighlight>
{{out|output|text=&nbsp; is identical to the previous REXX version.}} <br><br>
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
prime = 1679
decomp(prime)
 
func decomp nr
x = ""
sum = 0
for i = 1 to nr
if isPrime(i) and nr % i = 0
sum = sum + 1
x = x + string(i) + " * " ok
if i = nr and sum = 2
x2 = substr(x,1,(len(x)-2))
see string(nr) + " = " + x2 + "is semiprime" + nl
but i = nr and sum != 2 see string(nr) + " is not semiprime" + nl ok
next
 
func isPrime n
if n < 2 return false ok
if n < 4 return true ok
if n % 2 = 0 and n != 2 return false ok
for d = 3 to sqrt(n) step 2
if n % d = 0 return false ok
next
return true
</syntaxhighlight>
 
=={{header|RPL}}==
<code>PDIV</code> is defined at [[Prime decomposition#RPL|Prime decomposition]]
≪ <span style="color:blue">'''PDIV'''</span> SIZE 2 == ≫ '<span style="color:blue">'''SPR1?'''</span>' STO
≪ { } 1 100 '''FOR''' n '''IF''' n <span style="color:blue">'''SPR1?'''</span> '''THEN''' n + '''END NEXT''' ≫ EVAL
{{out}}
<pre>
1: { 4 6 9 10 14 15 21 22 25 26 33 34 35 38 39 46 49 51 55 57 58 62 65 69 74 77 82 85 86 87 91 93 94 95 }
</pre>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">require 'prime'
# 75.prime_division # Returns the factorization.75 divides by 3 once and by 5 twice => [[3, 1], [5, 2]]
 
class Integer
def semi_prime?
prime_division.mapsum( &:last ).inject( &:+ ) == 2
end
end
Line 1,424 ⟶ 3,086:
p ( 1..100 ).select( &:semi_prime? )
# [4, 6, 9, 10, 14, 15, 21, 22, 25, 26, 33, 34, 35, 38, 39, 46, 49, 51, 55, 57, 58, 62, 65, 69, 74, 77, 82, 85, 86, 87, 91, 93, 94, 95]
</syntaxhighlight>
</lang>
 
Faster version using 'factor' function from [U|Li]nux Core Utilities library.
<syntaxhighlight lang="ruby">def semiprime(n)
`factor #{n}`.split.size == 3
end
n = 2**72 - 1 #4722366482869645213695
(n-50..n).each { |n| puts "#{n} -> #{semiprime(n)}" }</syntaxhighlight>
{{out}}
<pre>4722366482869645213645 -> false
4722366482869645213646 -> false
4722366482869645213647 -> false
4722366482869645213648 -> false
4722366482869645213649 -> false
4722366482869645213650 -> false
4722366482869645213651 -> true
4722366482869645213652 -> false
4722366482869645213653 -> false
4722366482869645213654 -> false
4722366482869645213655 -> false
4722366482869645213656 -> false
4722366482869645213657 -> false
4722366482869645213658 -> false
4722366482869645213659 -> false
4722366482869645213660 -> false
4722366482869645213661 -> false
4722366482869645213662 -> false
4722366482869645213663 -> true
4722366482869645213664 -> false
4722366482869645213665 -> false
4722366482869645213666 -> false
4722366482869645213667 -> false
4722366482869645213668 -> false
4722366482869645213669 -> false
4722366482869645213670 -> false
4722366482869645213671 -> false
4722366482869645213672 -> false
4722366482869645213673 -> true
4722366482869645213674 -> false
4722366482869645213675 -> false
4722366482869645213676 -> false
4722366482869645213677 -> false
4722366482869645213678 -> false
4722366482869645213679 -> false
4722366482869645213680 -> false
4722366482869645213681 -> false
4722366482869645213682 -> false
4722366482869645213683 -> false
4722366482869645213684 -> false
4722366482869645213685 -> false
4722366482869645213686 -> false
4722366482869645213687 -> false
4722366482869645213688 -> false
4722366482869645213689 -> true
4722366482869645213690 -> false
4722366482869645213691 -> false
4722366482869645213692 -> false
4722366482869645213693 -> false
4722366482869645213694 -> false
4722366482869645213695 -> false</pre>
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">extern crate primal;
 
fn isqrt(n: usize) -> usize {
(n as f64).sqrt() as usize
}
 
fn is_semiprime(mut n: usize) -> bool {
let root = isqrt(n) + 1;
let primes1 = primal::Sieve::new(root);
let mut count = 0;
 
for i in primes1.primes_from(2).take_while(|&x| x < root) {
while n % i == 0 {
n /= i;
count += 1;
}
if n == 1 {
break;
}
}
 
if n != 1 {
count += 1;
}
count == 2
}
 
#[test]
fn test1() {
assert_eq!((2..10).filter(|&n| is_semiprime(n)).count(), 3);
}
 
#[test]
fn test2() {
assert_eq!((2..100).filter(|&n| is_semiprime(n)).count(), 34);
}
 
#[test]
fn test3() {
assert_eq!((2..1_000).filter(|&n| is_semiprime(n)).count(), 299);
}
 
#[test]
fn test4() {
assert_eq!((2..10_000).filter(|&n| is_semiprime(n)).count(), 2_625);
}
 
#[test]
fn test5() {
assert_eq!((2..100_000).filter(|&n| is_semiprime(n)).count(), 23_378);
}
 
#[test]
fn test6() {
assert_eq!((2..1_000_000).filter(|&n| is_semiprime(n)).count(), 210_035);
}</syntaxhighlight>
functional version of is_semiprime:
<syntaxhighlight lang="rust">fn is_semiprime(n: usize) -> bool {
fn iter(x: usize, start: usize, count: usize) -> usize {
if count > 2 {return count} // break for semi_prime
let limit = (x as f64).sqrt().ceil() as usize;
match (start..=limit).skip_while(|i| x % i > 0).next() {
Some(v) => iter(x / v, v, count + 1),
None => if x < 2 { count }
else { count + 1 }
}
}
iter(n, 2, 0) == 2
}</syntaxhighlight>
{{out}}
<pre>
running 6 tests
test test1 ... ok
test test2 ... ok
test test3 ... ok
test test4 ... ok
test test5 ... ok
test test6 ... ok
 
test result: ok. 6 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
</pre>
 
=={{header|Scala}}==
{{works with|Scala 2.9.1}}
<langsyntaxhighlight Scalalang="scala">object Semiprime extends App {
 
def isSP(n: Int): Boolean = {
Line 1,447 ⟶ 3,251:
1675 to 1681 foreach {i => println(i+" -> "+isSP(i))}
}</langsyntaxhighlight>
{{out}}
<pre>4 6 9 10 14 15 21 22 25 26 33 34 35 38 39 46 49 51 55 57 58 62 65 69 74 77 82 85 86 87 91 93 94 95
Line 1,459 ⟶ 3,263:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const func boolean: semiPrime (in var integer: n) is func
Line 1,485 ⟶ 3,289:
writeln(v <& " -> " <& semiPrime(v));
end for;
end func;</langsyntaxhighlight>
 
{{out}}
Line 1,498 ⟶ 3,302:
 
=={{header|Sidef}}==
Built-in:
<lang ruby>require 'ntheory';
<syntaxhighlight lang="ruby">say is_semiprime(2**128 + 1) #=> true
say is_semiprime(2**256 - 1) #=> false</syntaxhighlight>
 
User-defined function, with trial division up to a given bound '''B''':
func is_semiprime(n) {
<syntaxhighlight lang="ruby">func is_semiprime(n, B=1e4) {
static nt = %S'ntheory';
if (var p = [nt.trial_factor(n, 500)]) {
return false if (p.len > 2);
return !!nt.is_prime(p[1]) if (p.len == 2);
}
[nt.factor(n)].len == 2;
}
 
with (n.trial_factor(B)) { |f|
say [2,4,99,100,1679,32768,1234567,9876543,900660121].grep{ is_semiprime(_) }</lang>
return false if (f.len > 2)
return f.all { .is_prime } if (f.len == 2)
}
 
n.factor.len == 2
}
 
say [2,4,99,100,1679,32768,1234567,9876543,900660121].grep(is_semiprime)</syntaxhighlight>
{{out}}
<pre>
Line 1,518 ⟶ 3,325:
=={{header|Swift}}==
 
<langsyntaxhighlight lang="swift">import Foundation
 
func primes(n: Int) -> AnyGenerator<Int> {
Line 1,554 ⟶ 3,361:
}
return false
}</langsyntaxhighlight>
 
=={{header|Tcl}}==
{{tcllib|math::numtheory}}
<langsyntaxhighlight lang="tcl">package require math::numtheory
 
proc isSemiprime n {
Line 1,581 ⟶ 3,388:
puts "NOT a semiprime"
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,590 ⟶ 3,397:
1679 is ... a semiprime
1680 is ... NOT a semiprime
</pre>
 
== {{header|TypeScript}} ==
{{trans|ASIC}}
<syntaxhighlight lang="javascript">
// Semiprime
 
function primeFactorsCount(n: number): number {
n = Math.abs(n);
var count = 0; // Result
if (n >= 2)
for (factor = 2; factor <= n; factor++)
while n % factor == 0) {
count++;
n /= factor;
}
return count;
}
 
const readline = require('readline').createInterface({
input: process.stdin, output: process.stdout
});
 
readline.question('Enter an integer: ', sn => {
var n = parseInt(sn);
console.log(primeFactorsCount(n) == 2 ?
"It is a semiprime." : "It is not a semiprime.");
readline.close();
});
</syntaxhighlight>
{{out}}
<pre>
Enter an integer: 33
It is a semiprime.
</pre>
<pre>
Enter an integer: 60
It is not a semiprime.
</pre>
 
=={{header|Wren}}==
{{trans|Go}}
<syntaxhighlight lang="wren">var semiprime = Fn.new { |n|
if (n < 3) return false
var nf = 0
for (i in 2..n) {
while (n%i == 0) {
if (nf == 2) return false
nf = nf + 1
n = (n/i).floor
}
}
return nf == 2
}
 
for (v in 1675..1680) {
System.print("%(v) -> %(semiprime.call(v) ? "is" : "is not") semi-prime")
}</syntaxhighlight>
 
{{out}}
<pre>
1675 -> isn't semi-prime
1676 -> isn't semi-prime
1677 -> isn't semi-prime
1678 -> is semi-prime
1679 -> is semi-prime
1680 -> isn't semi-prime
</pre>
 
=={{header|XPL0}}==
<syntaxhighlight lang="xpl0">func Semiprime(N); \Return 'true' if N is semiprime
int N, F, C;
[C:= 0; F:= 2;
repeat if rem(N/F) = 0 then
[C:= C+1;
N:= N/F;
]
else F:= F+1;
until F > N;
return C = 2;
];
 
int N;
[for N:= 1 to 100 do
if Semiprime(N) then
[IntOut(0, N); ChOut(0, ^ )];
]</syntaxhighlight>
 
{{out}}
<pre>
4 6 9 10 14 15 21 22 25 26 33 34 35 38 39 46 49 51 55 57 58 62 65 69 74 77 82 85 86 87 91 93 94 95
</pre>
 
=={{header|zkl}}==
{{trans|C}}
<langsyntaxhighlight lang="zkl">fcn semiprime(n){
reg f = 0;
p:=2; while(f < 2 and p*p <= n){
Line 1,601 ⟶ 3,499:
}
return(f + (n > 1) == 2);
}</langsyntaxhighlight>
{{out}}
<pre>
2,063

edits