Anti-primes: Difference between revisions

85,871 bytes added ,  12 days ago
Added Uiua solution
m (optimisation lifted from julia)
(Added Uiua solution)
 
(167 intermediate revisions by 79 users not shown)
Line 1:
[[Category:Prime Numbers]]
{{task}}
 
The [https://youtu.be/2JM2oImb9Qg anti-primes]
(or [https://en.wikipedia.org/wiki/Highly_composite_number highly composite numbers], sequence [https://oeis.org/A002182 A002182] in the [https://oeis.org/ OEIS])
are the natural numbers with more factors than any smaller than itself.
 
 
;Task:
Generate and show here, the first twenty anti-primes.
 
 
;Related tasks:
#:*   [[Factors of an integer]]
#:*   [[Sieve of Eratosthenes]]
<br><br>
&nbsp;
 
=={{header|11l}}==
<langsyntaxhighlight lang="11l">AV max_divisors = 0
AV c = 0
AV n = 1
L
AV divisors = 1
L(i) 1 .. n I/ 2
I n % i == 0
Line 29 ⟶ 33:
L.break
 
n++</langsyntaxhighlight>
{{out}}
<pre>1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560</pre>
 
=={{header|8086 Assembly}}==
<syntaxhighlight lang="asm">puts: equ 9 ; MS-DOS print string syscall
amount: equ 20 ; Amount of antiprimes to find
cpu 8086
org 100h
xor si,si ; SI = current number
xor cx,cx ; CH = max # of factors, CL = # of antiprimes
cand: inc si
mov di,si ; DI = maximum factor to test
shr di,1
mov bp,1 ; BP = current candidate
xor bl,bl ; BL = factor count
.test: mov ax,si ; Test current candidate
xor dx,dx
div bp
test dx,dx ; Evenly divisible?
jnz .next
inc bx ; Then increment factors
.next: inc bp ; Next possible factor
cmp bp,si ; Are we there yet?
jbe .test ; If not, try next factor
cmp bl,ch ; Is it an antiprime?
jbe cand ; If not, next candidate
inc cx ; If so, increment the amount of antiprimes seen
mov ch,bl ; Update maximum amount of factors
mov bx,nbuf ; Convert current number to ASCII
mov ax,si
mov di,10
digit: xor dx,dx ; Extract a digit
div di
add dl,'0' ; Add ASCII 0
dec bx
mov [bx],dl ; Store it
test ax,ax ; Any more digits?
jnz digit ; If so, get next digit
mov dx,bx
mov ah,puts
int 21h ; Print using MS-DOS
cmp cl,amount ; Do we need any more antiprimes?
jb cand ; If so, find the next one
ret ; Otherwise, back to DOS
db '.....' ; Placeholder for decimal output
nbuf: db ' $'</syntaxhighlight>
{{out}}
<pre>1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560 </pre>
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits <br> or android 64 bits with application Termux }}
<syntaxhighlight lang="aarch64 assembly">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program antiprime64.s */
/************************************/
/* Constantes */
/************************************/
.include "../includeConstantesARM64.inc"
.equ NMAXI, 20
.equ MAXLINE, 5
/*********************************/
/* Initialized data */
/*********************************/
.data
sMessResult: .asciz " @ "
szCarriageReturn: .asciz "\n"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
ldr x3,qNMaxi // load limit
mov x5,#0 // maxi
mov x6,#0 // result counter
mov x7,#0 // display counter
mov x4,#1 // number begin
1:
mov x0,x4 // number
bl decFactor // compute number factors
cmp x0,x5 // maxi ?
cinc x4,x4,le // no -> increment indice
//addle x4,x4,#1 // no -> increment indice
ble 1b // and loop
mov x5,x0
mov x0,x4
bl displayResult
add x7,x7,#1 // increment display counter
cmp x7,#MAXLINE // line maxi ?
blt 2f
mov x7,#0
ldr x0,qAdrszCarriageReturn
bl affichageMess // display message
2:
add x6,x6,#1 // increment result counter
add x4,x4,#1 // increment number
cmp x6,x3 // end ?
blt 1b
100: // standard end of the program
mov x0, #0 // return code
mov x8,EXIT
svc #0 // perform the system call
qAdrszCarriageReturn: .quad szCarriageReturn
qNMaxi: .quad NMAXI
/***************************************************/
/* display message number */
/***************************************************/
/* x0 contains number 1 */
/* x1 contains number 2 */
displayResult:
stp x1,lr,[sp,-16]! // save registers
ldr x1,qAdrsZoneConv
bl conversion10 // call décimal conversion
ldr x0,qAdrsMessResult
ldr x1,qAdrsZoneConv // insert conversion in message
bl strInsertAtCharInc
bl affichageMess // display message
ldp x1,lr,[sp],16 // restaur registers
ret
qAdrsMessResult: .quad sMessResult
qAdrsZoneConv: .quad sZoneConv
/***************************************************/
/* compute factors sum */
/***************************************************/
/* x0 contains the number */
decFactor:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
mov x5,#0 // init number factors
mov x4,x0 // save number
mov x1,#1 // start factor -> divisor
1:
mov x0,x4 // dividende
udiv x2,x0,x1
msub x3,x2,x1,x0
cmp x1,x2 // divisor > quotient ?
bgt 3f
cmp x3,#0 // remainder = 0 ?
bne 2f
add x5,x5,#1 // increment counter factors
cmp x1,x2 // divisor = quotient ?
beq 3f // yes -> end
add x5,x5,#1 // no -> increment counter factors
2:
add x1,x1,#1 // increment factor
b 1b // and loop
3:
mov x0,x5 // return counter
ldp x4,x5,[sp],16 // restaur registers
ldp x2,x3,[sp],16 // restaur registers
ldp x1,lr,[sp],16 // restaur registers
ret
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../includeARM64.inc"
</syntaxhighlight>
<pre>
1 2 4 6 12
24 36 48 60 120
180 240 360 720 840
1260 1680 2520 5040 7560
</pre>
=={{header|Action!}}==
<syntaxhighlight lang="action!">BYTE FUNC CountDivisors(INT a)
INT i
BYTE prod,count
 
prod=1 count=0
WHILE a MOD 2=0
DO
count==+1
a==/2
OD
prod==*(1+count)
 
i=3
WHILE i*i<=a
DO
count=0
WHILE a MOD i=0
DO
count==+1
a==/i
OD
prod==*(1+count)
i==+2
OD
 
IF a>2 THEN
prod==*2
FI
RETURN (prod)
 
PROC Main()
BYTE toFind=[20],found=[0],count,max=[0]
INT i=[1]
 
PrintF("The first %B Anti-primes are:%E",toFind)
WHILE found<toFind
DO
count=CountDivisors(i)
IF count>max THEN
max=count
found==+1
PrintI(i)
IF found<toFind THEN
Print(", ")
FI
FI
i==+1
OD
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Anti-primes.png Screenshot from Atari 8-bit computer]
<pre>
The first 20 Anti-primes are:
1, 2, 4, 6, 12, 24, 36, 48, 60, 120, 180, 240, 360, 720, 840, 1260, 1680, 2520, 5040, 7560
</pre>
 
=={{header|Ada}}==
<syntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO;
 
procedure Antiprimes is
 
function Count_Divisors (N : Integer) return Integer is
Count : Integer := 1;
begin
for i in 1 .. N / 2 loop
if N mod i = 0 then
Count := Count + 1;
end if;
end loop;
return Count;
end Count_Divisors;
 
Results : array (1 .. 20) of Integer;
Candidate : Integer := 1;
Divisors : Integer;
Max_Divisors : Integer := 0;
 
begin
for i in Results'Range loop
loop
Divisors := Count_Divisors (Candidate);
if Max_Divisors < Divisors then
Results (i) := Candidate;
Max_Divisors := Divisors;
exit;
end if;
Candidate := Candidate + 1;
end loop;
end loop;
Put_Line ("The first 20 anti-primes are:");
for I in Results'Range loop
Put (Integer'Image (Results (I)));
end loop;
New_Line;
end Antiprimes;</syntaxhighlight>
{{out}}
<pre>
The first 20 anti-primes are:
1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560
</pre>
 
=={{header|ALGOL 68}}==
<syntaxhighlight lang="algol68">
BEGIN # find some anti-primes: numbers with more divisors than the #
# previous numbers #
REF[]INT ndc := HEAP[ 1 : 0 ]INT; # table of divisor counts #
INT max divisors := 0;
INT a count := 0;
FOR n WHILE a count < 20 DO
IF n > UPB ndc THEN
# need a bigger table of divisor counts #
ndc := HEAP[ 1 : UPB ndc + 5 000 ]INT;
FOR i FROM 1 TO UPB ndc DO ndc[ i ] := 1 OD;
FOR i FROM 2 TO UPB ndc DO
FOR j FROM i BY i TO UPB ndc DO ndc[ j ] +:= 1 OD
OD
FI;
IF ndc[ n ] > max divisors THEN
print( ( " ", whole( n, 0 ) ) );
max divisors := ndc[ n ];
a count +:= 1
FI
OD;
print( ( newline ) )
END
</syntaxhighlight>
{{out}}
<pre>
1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560
</pre>
 
=={{header|ALGOL W}}==
<syntaxhighlight lang="algolw">begin
% find some anti-primes - numbers with more factors than the numbers %
% smaller than them %
% calculates the number of divisors of v %
integer procedure divisor_count( integer value v ) ; begin
integer total, n, p;
total := 1; n := v;
while not odd( n ) do begin
total := total + 1;
n := n div 2
end while_not_odd_n ;
p := 3;
while ( p * p ) <= n do begin
integer count;
count := 1;
while n rem p = 0 do begin
count := count + 1;
n := n div p
end while_n_rem_p_eq_0 ;
p := p + 2;
total := total * count
end while_p_x_p_le_n ;
if n > 1 then total := total * 2;
total
end divisor_count ;
begin
integer maxAntiPrime, antiPrimeCount, maxDivisors, n;
maxAntiPrime := 20;
n := maxDivisors := antiPrimeCount := 0;
while antiPrimeCount < maxAntiPrime do begin
integer divisors;
n := n + 1;
divisors := divisor_count( n );
if divisors > maxDivisors then begin
writeon( i_w := 1, s_w := 0, " ", n );
maxDivisors := divisors;
antiPrimeCount := antiPrimeCount + 1
end if_have_an_anti_prime
end while_antiPrimeCoiunt_lt_maxAntiPrime
end
end.</syntaxhighlight>
{{out}}
<pre>
1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560
</pre>
 
=={{header|AppleScript}}==
<syntaxhighlight lang="applescript">on factorCount(n)
set counter to 0
set sqrt to n ^ 0.5
set limit to sqrt div 1
if (limit = sqrt) then
set counter to counter + 1
set limit to limit - 1
end if
repeat with i from limit to 1 by -1
if (n mod i is 0) then set counter to counter + 2
end repeat
return counter
end factorCount
 
on antiprimes(howMany)
set output to {}
set mostFactorsSoFar to 0
set n to 0
repeat until ((count output) = howMany)
set n to n + 1
tell (factorCount(n))
if (it > mostFactorsSoFar) then
set end of output to n
set mostFactorsSoFar to it
end if
end tell
end repeat
return output
end antiprimes
 
antiprimes(20)</syntaxhighlight>
 
{{output}}
<syntaxhighlight lang="applescript">{1, 2, 4, 6, 12, 24, 36, 48, 60, 120, 180, 240, 360, 720, 840, 1260, 1680, 2520, 5040, 7560}</syntaxhighlight>
 
=={{header|APL}}==
Works in [[Dyalog APL]]
<syntaxhighlight lang="apl">f←{⍸≠⌈\(⍴∘∪⊢∨⍳)¨⍳⍵}</syntaxhighlight>
{{out}}
<pre>
f 8000
1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560</pre>
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi <br> or android 32 bits with application Termux}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI or android with termux */
/* program antiprime.s */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/* for constantes see task include a file in arm assembly */
/************************************/
/* Constantes */
/************************************/
.include "../constantes.inc"
.equ NMAXI, 20
.equ MAXLINE, 5
/*********************************/
/* Initialized data */
/*********************************/
.data
sMessResult: .asciz " @ "
szCarriageReturn: .asciz "\n"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
ldr r3,iNMaxi @ load limit
mov r5,#0 @ maxi
mov r6,#0 @ result counter
mov r7,#0 @ display counter
mov r4,#1 @ number begin
1:
mov r0,r4 @ number
bl decFactor @ compute number factors
cmp r0,r5 @ maxi ?
addle r4,r4,#1 @ no -> increment indice
ble 1b @ and loop
mov r5,r0
mov r0,r4
bl displayResult
add r7,r7,#1 @ increment display counter
cmp r7,#MAXLINE @ line maxi ?
blt 2f
mov r7,#0
ldr r0,iAdrszCarriageReturn
bl affichageMess @ display message
2:
add r6,r6,#1 @ increment result counter
add r4,r4,#1 @ increment number
cmp r6,r3 @ end ?
blt 1b
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrszCarriageReturn: .int szCarriageReturn
iNMaxi: .int NMAXI
/***************************************************/
/* display message number */
/***************************************************/
/* r0 contains number 1 */
/* r1 contains number 2 */
displayResult:
push {r1,lr} @ save registers
ldr r1,iAdrsZoneConv
bl conversion10 @ call décimal conversion
ldr r0,iAdrsMessResult
ldr r1,iAdrsZoneConv @ insert conversion in message
bl strInsertAtCharInc
bl affichageMess @ display message
pop {r1,pc} @ restaur des registres
iAdrsMessResult: .int sMessResult
iAdrsZoneConv: .int sZoneConv
/***************************************************/
/* compute factors sum */
/***************************************************/
/* r0 contains the number */
decFactor:
push {r1-r5,lr} @ save registers
mov r5,#0 @ init number factors
mov r4,r0 @ save number
mov r1,#1 @ start factor -> divisor
1:
mov r0,r4 @ dividende
bl division
cmp r1,r2 @ divisor > quotient ?
bgt 3f
cmp r3,#0 @ remainder = 0 ?
bne 2f
add r5,r5,#1 @ increment counter factors
cmp r1,r2 @ divisor = quotient ?
beq 3f @ yes -> end
add r5,r5,#1 @ no -> increment counter factors
2:
add r1,r1,#1 @ increment factor
b 1b @ and loop
3:
mov r0,r5 @ return counter
pop {r1-r5,pc} @ restaur registers
 
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../affichage.inc"
</syntaxhighlight>
<pre>
1 2 4 6 12
24 36 48 60 120
180 240 360 720 840
1260 1680 2520 5040 7560
</pre>
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">found: 0
i: 1
maxDiv: 0
 
while [found<20][
fac: size factors i
if fac > maxDiv [
print i
maxDiv: fac
found: found + 1
]
i: i + 1
]</syntaxhighlight>
 
{{out}}
 
<pre>1
2
4
6
12
24
36
48
60
120
180
240
360
720
840
1260
1680
2520
5040
7560</pre>
 
=={{header|AWK}}==
{{trans|Go}}<syntaxhighlight lang="awk"># syntax: GAWK -f ANTI-PRIMES.AWK
BEGIN {
print("The first 20 anti-primes are:")
while (count < 20) {
d = count_divisors(++n)
if (d > max_divisors) {
printf("%d ",n)
max_divisors = d
count++
}
}
printf("\n")
exit(0)
}
function count_divisors(n, count,i) {
if (n < 2) {
return(1)
}
count = 2
for (i=2; i<=n/2; i++) {
if (n % i == 0) {
count++
}
}
return(count)
}</syntaxhighlight>
{{out}}
<pre>The first 20 anti-primes are:
1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560</pre>
 
=={{header|BASIC}}==
==={{header|BASIC256}}===
<syntaxhighlight lang="vbnet">
Dim Results(20)
Candidate = 1
max_divisors = 0
 
Print "Los primeros 20 anti-primos son:"
For j = 0 To 19
Do
divisors = count_divisors(Candidate)
If max_divisors < divisors Then
Results[j] = Candidate
max_divisors = divisors
Exit Do
End If
Candidate += 1
Until false
Print Results[j];" ";
Next j
 
Function count_divisors(n)
cont = 1
For i = 1 To n/2
If (n % i) = 0 Then cont += 1
Next i
count_divisors = cont
End Function
</syntaxhighlight>
{{out}}
<pre>
Los primeros 20 anti-primos son:
1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560
</pre>
 
==={{header|FreeBASIC}}===
<syntaxhighlight lang="freebasic">
' convertido desde Ada
Declare Function count_divisors(n As Integer) As Integer
 
Dim As Integer max_divisors, divisors, results(1 To 20), candidate, j
candidate = 1
 
Function count_divisors(n As Integer) As Integer
Dim As Integer i, count = 1
For i = 1 To n/2
If (n Mod i) = 0 Then count += 1
Next i
count_divisors = count
End Function
 
Print "Los primeros 20 anti-primos son:"
For j = 1 To 20
Do
divisors = count_divisors(Candidate)
If max_divisors < divisors Then
Results(j) = Candidate
max_divisors = divisors
Exit Do
End If
Candidate += 1
Loop
Next j
For j = 1 To 20
Print Results(j);
Next j
Print
Sleep
</syntaxhighlight>
{{out}}
<pre>
Los primeros 20 anti-primos son:
1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560
</pre>
 
==={{header|Gambas}}===
<syntaxhighlight lang="gambas">Function count_divisors(n As Integer) As Integer
 
Dim i, count As Integer
If n < 2 Then Return 1
count = 2
For i = 2 To n / 2
If Not (n Mod i) Then Inc count
Next
Return count
 
End Function
 
Public Sub Main()
 
Dim count, max_divisors, n, d As Integer
Print "Los primeros 20 anti-primos son:"
While (count < 20)
Inc n
d = count_divisors(n)
If d > max_divisors Then
Print n; " ";
max_divisors = d
Inc count
End If
Wend
End</syntaxhighlight>
{{out}}
<pre>The first 20 anti-primes are:
1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560 </pre>
 
==={{header|GW-BASIC}}===
{{works with|BASICA}}
<syntaxhighlight lang="gwbasic">10 REM Anti-primes
20 DEFINT A-Z
30 N=1
40 IF S>=20 THEN END ELSE F=1
50 IF N<2 GOTO 80 ELSE FOR I=1 TO N\2
60 IF N MOD I=0 THEN F=F+1
70 NEXT
80 IF F<=M GOTO 120
90 PRINT N,
100 M=F
110 S=S+1
120 N=N+1
130 GOTO 40</syntaxhighlight>
{{out}}
<pre> 1 2 4 6 12
24 36 48 60 120
180 240 360 720 840
1260 1680 2520 5040 7560</pre>
 
Another solution:
{{works with|BASICA}}
<syntaxhighlight lang="gwbasic">10 REM Anti-primes
20 C = -999
30 N = N + 1
40 GOSUB 70
50 IF T = 20 THEN END
60 GOTO 30
70 D = 0
80 FOR F = 1 TO INT(N/2)
90 IF N MOD F = 0 THEN D = D + 1
100 NEXT F
110 IF D > C THEN GOSUB 130
120 RETURN
130 C = D
140 T = T + 1
150 PRINT N
160 RETURN</syntaxhighlight>
{{out}}
<pre> 1
2
4
6
12
24
36
48
60
120
180
240
360
720
840
1260
1680
2520
5040
7560</pre>
 
==={{header|Palo Alto Tiny BASIC}}===
{{trans|Tiny BASIC}}
<syntaxhighlight lang="basic">
100 REM ANTI-PRIMES
110 LET N=1,H=0
120 PRINT "THE FIRST 20 ANTI-PRIMES ARE:"
130 FOR A=1 TO 20
140 GOSUB 300
150 LET H=F
160 PRINT N
170 LET N=N+1
180 NEXT A
190 STOP
290 REM SEARCH NEXT ANTI-PRIME
300 GOSUB 400
310 IF F>H RETURN
320 LET N=N+1
330 GOTO 300
390 REM COUNT DIVISORS
400 LET F=1
410 IF N>1 LET F=2
420 LET C=2
430 IF C*C>=N GOTO 470
440 IF (N/C)*C=N LET F=F+2
450 LET C=C+1
460 GOTO 430
470 IF C*C=N F=F+1
480 RETURN
</syntaxhighlight>
{{out}}
<pre>
THE FIRST 20 ANTI-PRIMES ARE:
1
2
4
6
12
24
36
48
60
120
180
240
360
720
840
1260
1680
2520
5040
7560
</pre>
 
==={{header|PureBasic}}===
{{trans|C}}<syntaxhighlight lang="purebasic">Procedure.i cntDiv(n.i)
Define.i i, count
If n < 2 : ProcedureReturn 1 : EndIf
count = 2 : i = 2
While i <= n / 2
If n % i = 0 : count + 1 : EndIf
i + 1
Wend
ProcedureReturn count
EndProcedure
 
; - - - MAIN - - -
Define.i n = 1, d, maxDiv = 0, count = 0
If OpenConsole("")
PrintN("The first 20 anti-primes are: ")
While count < 20
d = cntDiv(n)
If d > maxDiv
Print(Str(n) + " ")
maxDiv = d : count + 1
EndIf
n + 1
Wend
PrintN("")
Input()
EndIf
End 0</syntaxhighlight>
{{out}}
<pre>The first 20 anti-primes are:
1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560
</pre>
 
==={{header|QBasic}}===
{{works with|QBasic|1.1}}
{{works with|QuickBasic|4.5}}
<syntaxhighlight lang="qbasic">MaxAntiPrime = 20
n = 0
MaxDivisors = 0
AntiPrimeCount = 0
PRINT "The first 20 anti-primes are: "
WHILE AntiPrimeCount < MaxAntiPrime
n = n + 1
Divisors = DivisorCount(n)
IF Divisors > MaxDivisors THEN
PRINT n;
MaxDivisors = Divisors
AntiPrimeCount = AntiPrimeCount + 1
END IF
WEND
END
 
FUNCTION DivisorCount (v)
total = 1
n = v
WHILE n MOD 2 = 0
total = total + 1
n = n \ 2
WEND
p = 3
WHILE (p * p) <= n
count = 1
WHILE n MOD p = 0
count = count + 1
n = n \ p
WEND
p = p + 2
total = total * count
WEND
IF n > 1 THEN total = total * 2
DivisorCount = total
END FUNCTION</syntaxhighlight>
{{out}}
<pre>The first 20 anti-primes are:
1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560 </pre>
 
==={{header|QuickBASIC}}===
{{trans|ALGOL W}}
{{works with|QBasic|1.1}}
{{works with|QuickBasic|4.5}}
<syntaxhighlight lang="qbasic">
' Anti-primes
DECLARE FUNCTION DivisorCount (V%)
 
MaxAntiPrime% = 20
N% = 0: MaxDivisors% = 0: AntiPrimeCount% = 0
WHILE AntiPrimeCount% < MaxAntiPrime%
N% = N% + 1
Divisors% = DivisorCount(N%)
IF Divisors% > MaxDivisors% THEN
PRINT STR$(N%);
MaxDivisors% = Divisors%
AntiPrimeCount% = AntiPrimeCount% + 1
END IF
WEND
PRINT
END
 
FUNCTION DivisorCount (V%)
Total% = 1: N% = V%
WHILE N% MOD 2 = 0
Total% = Total% + 1
N% = N% \ 2
WEND
P% = 3
WHILE (P% * P%) <= N%
Count% = 1
WHILE N% MOD P% = 0
Count% = Count% + 1
N% = N% \ P%
WEND
P% = P% + 2
Total% = Total% * Count%
WEND
IF N% > 1 THEN Total% = Total% * 2
DivisorCount = Total%
END FUNCTION
</syntaxhighlight>
{{out}}
<pre>
1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560
</pre>
 
==={{header|Run BASIC}}===
{{works with|Just BASIC}}
{{works with|Liberty BASIC}}
<syntaxhighlight lang="lb">MaxAntiPrime = 20
n = 0
MaxDivisors = 0
AntiPrimeCount = 0
print "The first 20 anti-primes are: "
while AntiPrimeCount < MaxAntiPrime
n = n +1
Divisors = DivisorCount(n)
if Divisors > MaxDivisors then
print n; " ";
MaxDivisors = Divisors
AntiPrimeCount = AntiPrimeCount +1
end if
wend
end
 
function DivisorCount(v)
total = 1
n = v
while n mod 2 = 0
total = total +1
n = int(n / 2)
wend
p = 3
while (p * p) <= n
count = 1
while n mod p = 0
count = count +1
n = int(n / p)
wend
p = p +2
total = total * count
wend
if n > 1 then total = total *2
DivisorCount = total
end function</syntaxhighlight>
{{out}}
<pre>The first 20 anti-primes are:
1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560 </pre>
 
==={{header|Tiny BASIC}}===
{{works with|TinyBasic}}
<syntaxhighlight lang="basic">100 REM Anti-primes
110 LET A=0
120 LET N=1
130 LET H=0
140 PRINT "The first 20 anti-primes are:"
150 GOSUB 300
160 LET H=F
170 LET A=A+1
180 PRINT N
190 LET N=N+1
200 IF A<20 THEN GOTO 150
210 END
290 REM Search next anti-prime
300 GOSUB 400
310 IF F>H THEN RETURN
320 LET N=N+1
330 GOTO 300
390 REM Count divisors
400 LET F=1
410 IF N>1 THEN LET F=2
420 LET C=2
430 IF C*C>=N THEN GOTO 470
440 IF (N/C)*C=N THEN LET F=F+2
450 LET C=C+1
460 GOTO 430
470 IF C*C=N THEN LET F=F+1
480 RETURN
</syntaxhighlight>
{{out}}
<pre>The first 20 anti-primes are:
1
2
4
6
12
24
36
48
60
120
180
240
360
720
840
1260
1680
2520
5040
7560
</pre>
 
==={{header|VBA}}===
{{trans|Phix}}
<syntaxhighlight lang="vb">Private Function factors(n As Integer) As Collection
Dim f As New Collection
For i = 1 To Sqr(n)
If n Mod i = 0 Then
f.Add i
If n / i <> i Then f.Add n / i
End If
Next i
f.Add n
Set factors = f
End Function
Public Sub anti_primes()
Dim n As Integer, maxd As Integer
Dim res As New Collection, lenght As Integer
Dim lf As Integer
n = 1: maxd = -1
Length = 0
Do While res.count < 20
lf = factors(n).count
If lf > maxd Then
res.Add n
maxd = lf
End If
n = n + IIf(n > 1, 2, 1)
Loop
Debug.Print "The first 20 anti-primes are:";
For Each x In res
Debug.Print x;
Next x
End Sub</syntaxhighlight>{{out}}
<pre>The first 20 anti-primes are: 1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560
</pre>
 
==={{header|Visual Basic .NET}}===
{{trans|D}}
<syntaxhighlight lang="vbnet">Module Module1
 
Function CountDivisors(n As Integer) As Integer
If n < 2 Then
Return 1
End If
Dim count = 2 '1 and n
For i = 2 To n \ 2
If n Mod i = 0 Then
count += 1
End If
Next
Return count
End Function
 
Sub Main()
Dim maxDiv, count As Integer
Console.WriteLine("The first 20 anti-primes are:")
 
Dim n = 1
While count < 20
Dim d = CountDivisors(n)
 
If d > maxDiv Then
Console.Write("{0} ", n)
maxDiv = d
count += 1
End If
n += 1
End While
 
Console.WriteLine()
End Sub
 
End Module</syntaxhighlight>
{{out}}
<pre>The first 20 anti-primes are:
1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560</pre>
 
==={{header|Yabasic}}===
{{trans|AWK}}
<syntaxhighlight lang="yabasic">print "The first 20 anti-primes are:"
 
while (count < 20)
n = n + 1
d = count_divisors(n)
if d > max_divisors then
print n;
max_divisors = d
count = count + 1
end if
wend
print
 
sub count_divisors(n)
local count, i
if n < 2 return 1
count = 2
for i = 2 to n/2
if not(mod(n, i)) count = count + 1
next
return count
end sub</syntaxhighlight>
{{out}}
<pre>The first 20 anti-primes are:
1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560</pre>
 
{{trans|Lua}}
<syntaxhighlight lang="yabasic">// First 20 antiprimes.
sub count_factors(number)
local count, attempt
for attempt = 1 to number
if not mod(number, attempt) count = count + 1
next
return count
end sub
sub antiprimes$(goal)
local factors, list$, number, mostFactors, nitems
number = 1
while nitems < goal
factors = count_factors(number)
if factors > mostFactors then
list$ = list$ + ", " + str$(number)
nitems = nitems + 1
mostFactors = factors
endif
number = number + 1
wend
return list$
end sub
 
print "The first 20 antiprimes:"
print mid$(antiprimes$(20), 3)
print "Done."</syntaxhighlight>
{{out}}
<pre>The first 20 antiprimes:
1, 2, 4, 6, 12, 24, 36, 48, 60, 120, 180, 240, 360, 720, 840, 1260, 1680, 2520, 5040, 7560
Done.</pre>
 
 
=={{header|BCPL}}==
<syntaxhighlight lang="bcpl">get "libhdr"
manifest $( LIMIT = 20 $)
 
let nfactors(n) =
n < 2 -> 1, valof
$( let c = 2
for i=2 to n/2
if n rem i = 0 then c := c + 1
resultis c
$)
 
let start() be
$( let max = 0 and seen = 0 and n = 1
while seen < LIMIT
$( let f = nfactors(n)
if f > max
$( writef("%N ",n)
max := f
seen := seen + 1
$)
n := n + 1
$)
wrch('*N')
$)</syntaxhighlight>
{{out}}
<pre>1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560</pre>
=={{header|C}}==
{{trans|Go}}
<langsyntaxhighlight lang="c">#include <stdio.h>
 
int countDivisors(int n) {
Line 60 ⟶ 1,264:
printf("\n");
return 0;
}</langsyntaxhighlight>
 
{{out}}
<pre>
The first 20 anti-primes are:
1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560
</pre>
 
=={{header|C sharp|C#}}==
{{works with|C sharp|7}}
<syntaxhighlight lang="csharp">using System;
using System.Linq;
using System.Collections.Generic;
public static class Program
{
public static void Main() =>
Console.WriteLine(string.Join(" ", FindAntiPrimes().Take(20)));
static IEnumerable<int> FindAntiPrimes() {
int max = 0;
for (int i = 1; ; i++) {
int divisors = CountDivisors(i);
if (divisors > max) {
max = divisors;
yield return i;
}
}
int CountDivisors(int n) => Enumerable.Range(1, n / 2).Count(i => n % i == 0) + 1;
}
}</syntaxhighlight>
{{out}}
<pre>
1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560
</pre>
 
=={{header|C++}}==
{{trans|C}}
<langsyntaxhighlight lang="cpp">#include <iostream>
 
int countDivisors(int n) {
Line 94 ⟶ 1,326:
std::cout << std::endl;
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 102 ⟶ 1,334:
</pre>
 
=={{header|FactorCLU}}==
<syntaxhighlight lang="clu">% Count factors
<lang factor>USING: assocs formatting kernel locals make math
factors = proc (n: int) returns (int)
math.primes.factors sequences.extras ;
if n<2 then return(1) end
IN: rosetta-code.anti-primes
count: int := 2
for i: int in int$from_to(2, n/2) do
if n//i = 0 then count := count + 1 end
end
return(count)
end factors
 
% Generate antiprimes
<PRIVATE
antiprimes = iter () yields (int)
max: int := 0
n: int := 1
while true do
f: int := factors(n)
if f > max then
yield(n)
max := f
end
n := n + 1
end
end antiprimes
 
% Show the first 20 antiprimes
: count-divisors ( n -- m )
start_up = proc ()
dup 1 = [ group-factors values [ 1 + ] map-product ] unless ;
max = 20
po: stream := stream$primary_output()
count: int := 0
for i: int in antiprimes() do
stream$puts(po, int$unparse(i) || " ")
count := count + 1
if count = max then break end
end
end start_up</syntaxhighlight>
{{out}}
<pre>1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560</pre>
 
=={{header|COBOL}}==
: (n-anti-primes) ( md n count -- ?md' n' ?count' )
<syntaxhighlight lang="cobol">
dup 0 >
******************************************************************
[| max-div! n count! |
* COBOL solution to Anti-primes challange
n count-divisors :> d
* The program was run on OpenCobolIDE
d max-div > [ d max-div! n , count 1 - count! ] when
******************************************************************
max-div n dup 60 >= 20 1 ? + count (n-anti-primes)
IDENTIFICATION DIVISION.
] when ;
PROGRAM-ID. ANGLE-PRIMES.
 
ENVIRONMENT DIVISION.
PRIVATE>
DATA DIVISION.
WORKING-STORAGE SECTION.
77 ANTI-PRIMES-CTR PIC 9(3) VALUE 0.
77 FACTORS-CTR PIC 9(3) VALUE 0.
77 WS-INTEGER PIC 9(5) VALUE 1.
77 WS-MAX PIC 9(5) VALUE 0.
77 WS-I PIc 9(5) VALUE 0.
77 WS-LIMIT PIC 9(5) VALUE 1.
77 WS-REMAINDER PIC 9(5).
 
01 OUT-HDR PIC X(23) VALUE 'SEQ ANTI-PRIME FACTORS'.
: n-anti-primes ( n -- seq )
01 OUT-LINE.
[ 0 1 ] dip [ (n-anti-primes) 3drop ] { } make ;
05 OUT-SEQ PIC 9(3).
05 FILLER PIC X(3) VALUE SPACES.
05 OUT-ANTI PIC ZZZZ9.
05 FILLER PIC X(4) VALUE SPACES.
05 OUT-FACTORS PIC ZZZZ9.
 
PROCEDURE DIVISION.
: anti-primes-demo ( -- )
000-MAIN.
20 n-anti-primes "First 20 anti-primes:\n%[%d, %]\n" printf ;
DISPLAY OUT-HDR.
PERFORM 100-GET-ANTI-PRIMES
VARYING WS-INTEGER FROM 1 By 1
UNTIL ANTI-PRIMES-CTR >= 20.
STOP RUN.
 
100-GET-ANTI-PRIMES.
SET FACTORS-CTR TO 0.
COMPUTE WS-LIMIT = 1 + WS-INTEGER ** .5.
PERFORM 200-COUNT-FACTORS
VARYING WS-I FROM 1 BY 1
UNTIL WS-I >= WS-LIMIT.
IF FACTORS-CTR > WS-MAX
ADD 1 TO ANTI-PRIMES-CTR
COMPUTE WS-MAX = FACTORS-CTR
MOVE ANTI-PRIMES-CTR TO OUT-SEQ
MOVE WS-INTEGER TO OUT-ANTI
MOVE FACTORS-CTR TO OUT-FACTORS
DISPLAY OUT-LINE
END-IF.
 
200-COUNT-FACTORS.
COMPUTE WS-REMAINDER =
FUNCTION MOD(WS-INTEGER WS-I).
IF WS-REMAINDER = ZERO
ADD 1 TO FACTORS-CTR
IF WS-INTEGER NOT = WS-I ** 2
ADD 1 TO FACTORS-CTR
END-IF
END-IF.
 
******************************************************************
* OUTPUT:
******************************************************************
* SEQ ANTI-PRIME FACTORS
* 001 1 1
* 002 2 2
* 003 4 3
* 004 6 4
* 005 12 6
* 006 24 8
* 007 36 9
* 008 48 10
* 009 60 12
* 010 120 16
* 011 180 18
* 012 240 20
* 013 360 24
* 014 720 30
* 015 840 32
* 016 1260 36
* 017 1680 40
* 018 2520 48
* 019 5040 60
* 020 7560 64
******************************************************************
</syntaxhighlight>
 
=={{header|Common Lisp}}==
<syntaxhighlight lang="lisp">(defun factors (n &aux (lows '()) (highs '()))
(do ((limit (1+ (isqrt n))) (factor 1 (1+ factor)))
((= factor limit)
(when (= n (* limit limit))
(push limit highs))
(remove-duplicates (nreconc lows highs)))
(multiple-value-bind (quotient remainder) (floor n factor)
(when (zerop remainder)
(push factor lows)
(push quotient highs)))))
 
(defun anti-prime ()
(format t "The first 20 anti-primes are :~%")
(do ((dmax 0) (c 0) (i 0 (1+ i)))
((= c 20))
(setf facts (list-length (factors i)))
(when (< dmax facts)
(format t "~d " i)
(setq dmax facts)
(incf c))))</syntaxhighlight>
{{out}}
<pre>The first 20 anti-primes are :
1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560</pre>
 
=={{header|Cowgol}}==
<syntaxhighlight lang="cowgol">include "cowgol.coh";
const AMOUNT := 20;
 
sub countFactors(n: uint16): (count: uint16) is
var i: uint16 := 1;
count := 1;
while i <= n/2 loop
if n%i == 0 then
count := count + 1;
end if;
i := i + 1;
end loop;
end sub;
 
var max: uint16 := 0;
var seen: uint8 := 0;
var n: uint16 := 1;
var f: uint16 := 0;
 
while seen < AMOUNT loop;
f := countFactors(n);
if f > max then
print_i16(n);
print_char(' ');
max := f;
seen := seen + 1;
end if;
n := n + 1;
end loop;
print_nl();</syntaxhighlight>
{{out}}
<pre>1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560</pre>
 
=={{header|Crystal}}==
{{trans|C++}}
<syntaxhighlight lang="ruby">def count_divisors(n : Int64) : Int64
return 1_i64 if n < 2
count = 2_i64
 
i = 2
while i <= n // 2
count += 1 if n % i == 0
i += 1
end
 
count
end
 
max_div = 0_i64
count = 0_i64
 
print "The first 20 anti-primes are: "
 
n = 1_i64
while count < 20
d = count_divisors n
 
if d > max_div
print "#{n} "
max_div = d
count += 1
end
 
n += 1
end
 
puts ""
</syntaxhighlight>
 
MAIN: anti-primes-demo</lang>
{{out}}
<pre>
The first 20 anti-primes are: 1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560
First 20 anti-primes:
</pre>
{ 1, 2, 4, 6, 12, 24, 36, 48, 60, 120, 180, 240, 360, 720, 840, 1260, 1680, 2520, 5040, 7560 }
 
=={{header|D}}==
{{trans|C++}}
<syntaxhighlight lang="d">import std.stdio;
 
int countDivisors(int n) {
if (n < 2) {
return 1;
}
int count = 2; // 1 and n
for (int i = 2; i <= n/2; ++i) {
if (n % i == 0) {
++count;
}
}
return count;
}
 
void main() {
int maxDiv, count;
writeln("The first 20 anti-primes are:");
for (int n = 1; count < 20; ++n) {
int d = countDivisors(n);
if (d > maxDiv) {
write(n, ' ');
maxDiv = d;
count++;
}
}
writeln;
}</syntaxhighlight>
{{out}}
<pre>The first 20 anti-primes are:
1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560</pre>
 
=={{header|Dart}}==
{{trans|C++}}
<syntaxhighlight lang="dart">int countDivisors(int n) {
if (n < 2) return 1;
int count = 2; // 1 and n
for (int i = 2; i <= n / 2; ++i) {
if (n % i == 0) ++count;
}
return count;
}
 
void main() {
int maxDiv = 0, count = 0;
print("The first 20 anti-primes are:");
for (int n = 1; count < 20; ++n) {
int d = countDivisors(n);
if (d > maxDiv) {
print("$n ");
maxDiv = d;
count++;
}
}
print("");
}</syntaxhighlight>
 
=={{header|Delphi}}==
See [[#Pascal]].
=={{header|EasyLang}}==
{{trans|FutureBasic}}
<syntaxhighlight lang=easylang>
func divcnt v .
n = v
tot = 1
p = 2
while p <= sqrt n
cnt = 1
while n mod p = 0
cnt += 1
n = n div p
.
p += 1
tot *= cnt
.
if n > 1
tot *= 2
.
return tot
.
while count < 20
n += 1
divs = divcnt n
if divs > max
print n
max = divs
count += 1
.
.
</syntaxhighlight>
 
=={{header|Elixir}}==
{{trans|Erlang}}<syntaxhighlight lang="elixir">defmodule AntiPrimes do
def divcount(n) when is_integer(n), do: divcount(n, 1, 0)
 
def divcount(n, d, count) when d * d > n, do: count
def divcount(n, d, count) do
divs = case rem(n, d) do
0 ->
case n - d * d do
0 -> 1
_ -> 2
end
_ -> 0
end
divcount(n, d + 1, count + divs)
end
 
def antiprimes(n), do: antiprimes(n, 1, 0, [])
 
def antiprimes(0, _, _, l), do: Enum.reverse(l)
def antiprimes(n, m, max, l) do
count = divcount(m)
case count > max do
true -> antiprimes(n-1, m+1, count, [m|l])
false -> antiprimes(n, m+1, max, l)
end
end
 
def main() do
:io.format("The first 20 anti-primes are ~w~n", [antiprimes(20)])
end
end</syntaxhighlight>
{{out}}
<pre>
The first 20 anti-primes are [1,2,4,6,12,24,36,48,60,120,180,240,360,720,840,1260,1680,2520,5040,7560]
</pre>
 
=={{header|EMal}}==
{{trans|Java}}
<syntaxhighlight lang="emal">
fun countDivisors = int by int n
if n < 2 do return 1 end
int count = 2
for int i = 2; i <= n / 2; ++i
if n % i == 0 do ++count end
end
return count
end
int maxDiv = 0
int count = 0
writeLine("The first 20 anti-primes are:")
for int n = 1; count < 20; ++n
int d = countDivisors(n)
if d <= maxDiv do continue end # never nester version
write(n + " ")
maxDiv = d
++count
end
writeLine()
</syntaxhighlight>
{{out}}
<pre>
The first 20 anti-primes are:
1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560
</pre>
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">divcount(N) -> divcount(N, 1, 0).
 
divcount(N, D, Count) when D*D > N -> Count;
divcount(N, D, Count) ->
Divs = case N rem D of
0 ->
case N - D*D of
0 -> 1;
_ -> 2
end;
_ -> 0
end,
divcount(N, D + 1, Count + Divs).
 
 
antiprimes(N) -> antiprimes(N, 1, 0, []).
 
antiprimes(0, _, _, L) -> lists:reverse(L);
antiprimes(N, M, Max, L) ->
Count = divcount(M),
case Count > Max of
true -> antiprimes(N-1, M+1, Count, [M|L]);
false -> antiprimes(N, M+1, Max, L)
end.
 
 
main(_) ->
io:format("The first 20 anti-primes are ~w~n", [antiprimes(20)]).
</syntaxhighlight>
{{out}}
<pre>
The first 20 anti-primes are [1,2,4,6,12,24,36,48,60,120,180,240,360,720,840,1260,1680,2520,5040,7560]
</pre>
 
=={{header|F_Sharp|F#}}==
===The Function===
{{incorrect|F_SharpTask asks for a specific number of terms that would stop excessive output - check other solutions and task description if in doubt.}};The Function:
This task uses [http://www.rosettacode.org/wiki/Extensible_prime_generator#The_function Extensible Prime Generator (F#)]
<langsyntaxhighlight lang="fsharp">
// Find Antı-Primes. Nigel Galloway: Secember 10th., 2018
let N=200000000000000000000000000I
Line 145 ⟶ 1,766:
let fE n i=n|>Seq.collect(fun(n,e,g)->Seq.map(fun(a,c,b)->(a,c*e,g*b)) (i|>Seq.takeWhile(fun(g,_,_)->g<=n)) |> Seq.takeWhile(fun(_,_,n)->n<N))
let fL,_=Seq.concat(Seq.scan(fun n g->fE n (fG g)) (seq[(2147483647,1,1I)]) fI)|>List.ofSeq|>List.sortBy(fun(_,_,n)->n)|>List.fold(fun ((a,b) as z) (_,n,g)->if n>b then ((n,g)::a,n) else z) ([],0)
</syntaxhighlight>
</lang>
===The Task===
 
<syntaxhighlight lang="fsharp">
;The Task:
printfn "The first 20 anti-primes are :-"; for (_,g) in (List.rev fL)|>List.take 20 do printfn "%A" g
<lang fsharp>
</syntaxhighlight>
{{out}}
<pre>
The first 20 anti-primes are :-
1
2
4
6
12
24
36
48
60
120
180
240
360
720
840
1260
1680
2520
5040
7560
</pre>
===Extra Credit===
<syntaxhighlight lang="fsharp">
printfn "There are %d anti-primes less than %A:-" (List.length fL) N; for (n,g) in (List.rev fL) do printfn "%A has %d dividers" g n
</syntaxhighlight>
</lang>
{{out}}
<pre style="height:35ex">
Real: 00:00:10.683, CPU: 00:00:10.880, GC gen0: 1394, gen1: 1
There are 245 anti-primes less than 200000000000000000000000000:-
1 has 1 dividers
Line 400 ⟶ 2,047:
162606865137787447184808000 has 3096576 dividers
193814243295544634018256000 has 3145728 dividers
</pre>
 
=={{header|Factor}}==
<syntaxhighlight lang="factor">USING: assocs formatting kernel locals make math
math.primes.factors sequences.extras ;
IN: rosetta-code.anti-primes
 
<PRIVATE
 
: count-divisors ( n -- m )
dup 1 = [ group-factors values [ 1 + ] map-product ] unless ;
 
: (n-anti-primes) ( md n count -- ?md' n' ?count' )
dup 0 >
[| max-div! n count! |
n count-divisors :> d
d max-div > [ d max-div! n , count 1 - count! ] when
max-div n dup 60 >= 20 1 ? + count (n-anti-primes)
] when ;
 
PRIVATE>
 
: n-anti-primes ( n -- seq )
[ 0 1 ] dip [ (n-anti-primes) 3drop ] { } make ;
 
: anti-primes-demo ( -- )
20 n-anti-primes "First 20 anti-primes:\n%[%d, %]\n" printf ;
 
MAIN: anti-primes-demo</syntaxhighlight>
{{out}}
<pre>
First 20 anti-primes:
{ 1, 2, 4, 6, 12, 24, 36, 48, 60, 120, 180, 240, 360, 720, 840, 1260, 1680, 2520, 5040, 7560 }
</pre>
 
=={{header|Forth}}==
This task uses [http://rosettacode.org/wiki/Factors_of_an_integer#Alternative_version_with_vectored_execution Factors of an Integer with vectored execution]
<syntaxhighlight lang="forth">
include ./factors.fs
 
: max-count ( n1 n2 -- n f )
\ n is max(n1, factor-count n2); if n is new maximum then f = true.
\
count-factors 2dup <
if nip true
else drop false
then ;
 
: .anti-primes ( n -- )
0 1 rot \ stack: max, candidate, count
begin
>r dup >r max-count
if r> dup . r> 1-
else r> r>
then swap 1+ swap
dup 0= until drop 2drop ;
 
." The first 20 anti-primes are: " 20 .anti-primes cr
bye
</syntaxhighlight>
{{Out}}
<pre>
The first 20 anti-primes are: 1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560
</pre>
 
=={{header|Fortran}}==
{{trans|C}}
<syntaxhighlight lang="fortran">
program anti_primes
use iso_fortran_env, only: output_unit
implicit none
 
integer :: n, d, maxDiv, pCount
 
write(output_unit,*) "The first 20 anti-primes are:"
n = 1
maxDiv = 0
pCount = 0
do
if (pCount >= 20) exit
 
d = countDivisors(n)
if (d > maxDiv) then
write(output_unit,'(I0,x)', advance="no") n
maxDiv = d
pCount = pCount + 1
end if
n = n + 1
end do
write(output_unit,*)
contains
pure function countDivisors(n)
integer, intent(in) :: n
integer :: countDivisors
integer :: i
 
countDivisors = 1
if (n < 2) return
countDivisors = 2
do i = 2, n/2
if (modulo(n, i) == 0) countDivisors = countDivisors + 1
end do
end function countDivisors
end program anti_primes
</syntaxhighlight>
 
{{out}}
<pre>
The first 20 anti-primes are:
1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560
</pre>
 
=={{header|Frink}}==
<syntaxhighlight lang="frink">smallest = 0
n = 1
results = new array
do
{
len = length[allFactors[n]]
if len > smallest
{
results.push[n]
smallest = len
}
n = n + 1
} until length[results] == 20
 
println[join[" ", results]]</syntaxhighlight>
{{out}}
<pre>
1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560
</pre>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
local fn DivisorCount( v as long ) as long
long total = 1, n = v, p, count
while ( n mod 2 ) == 0
total++
n = int( n / 2 )
wend
p = 3
while ( p * p ) <= n
count = 1
while ( n mod p ) == 0
count++
n = int( n / p )
wend
p = p + 2
total = total * count
wend
if n > 1 then total = total * 2
end fn = total
 
void local fn AntiPrimes( howMany as long )
long n = 0, count = 0, divisors, max_divisors = 0
printf @"The first %ld anti-primes are:", howMany
while ( count < howMany )
n++
divisors = fn DivisorCount( n )
if ( divisors > max_divisors )
printf @"%ld \b", n
max_divisors = divisors
count++
end if
wend
end fn
 
fn AntiPrimes( 20 )
 
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
The first 20 anti-primes are:
1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560
</pre>
 
=={{header|Go}}==
Simple brute force approach which is quick enough here.
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 434 ⟶ 2,260:
}
fmt.Println()
}</langsyntaxhighlight>
 
{{out}}
Line 441 ⟶ 2,267:
1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560
</pre>
 
=={{header|Grain}}==
<syntaxhighlight lang="haskell">
import File from "sys/file"
let mut maxDiv = 0
let mut count = 0
let numaprimes = 20
let countDivisors = n => {
if (n < 1) {
1
} else {
let mut count = 2
let mut target = n / 2
for (let mut i = 1; i <= target; i += 1) {
if (n % i == 0) {
count += 1
} else {
void
}
}
count
}
}
print("\nThe first 20 anti-primes are: ")
let mut d = 0
for (let mut j = 1; count < numaprimes; j += 1) {
d = countDivisors(j)
if (d > maxDiv) {
File.fdWrite(File.stdout, Pervasives.toString(j))
File.fdWrite(File.stdout, " ")
maxDiv = d
count += 1
}
}
</syntaxhighlight>
{{out}}
<pre>
The first 20 anti-primes are:
1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560
</pre>
 
=={{header|Groovy}}==
Solution (uses [[Factors_of_an_integer#Groovy|Factors of an integer]] function "factorize()"):
<syntaxhighlight lang="groovy">def getAntiPrimes(def limit = 10) {
def antiPrimes = []
def candidate = 1L
def maxFactors = 0
 
while (antiPrimes.size() < limit) {
def factors = factorize(candidate)
if (factors.size() > maxFactors) {
maxFactors = factors.size()
antiPrimes << candidate
}
candidate++
}
antiPrimes
}</syntaxhighlight>
 
Test:
<syntaxhighlight lang="groovy">println (getAntiPrimes(20))</syntaxhighlight>
 
Output:
<pre>[1, 2, 4, 6, 12, 24, 36, 48, 60, 120, 180, 240, 360, 720, 840, 1260, 1680, 2520, 5040, 7560]</pre>
 
=={{header|Haskell}}==
<syntaxhighlight lang="haskell">import Data.List (find, group)
import Data.Maybe (fromJust)
 
firstPrimeFactor :: Int -> Int
firstPrimeFactor n = head $ filter ((0 ==) . mod n) [2 .. n]
 
allPrimeFactors :: Int -> [Int]
allPrimeFactors 1 = []
allPrimeFactors n =
let first = firstPrimeFactor n
in first : allPrimeFactors (n `div` first)
 
factorCount :: Int -> Int
factorCount 1 = 1
factorCount n = product ((succ . length) <$> group (allPrimeFactors n))
 
divisorCount :: Int -> (Int, Int)
divisorCount = (,) <*> factorCount
 
hcnNext :: (Int, Int) -> (Int, Int)
hcnNext (num, factors) =
fromJust $ find ((> factors) . snd) (divisorCount <$> [num ..])
 
hcnSequence :: [Int]
hcnSequence = fst <$> iterate hcnNext (1, 1)
 
main :: IO ()
main = print $ take 20 hcnSequence</syntaxhighlight>
{{output}}
<pre>
[1,2,4,6,12,24,36,48,60,120,180,240,360,720,840,1260,1680,2520,5040,7560]
</pre>
 
=={{header|J}}==
<syntaxhighlight lang="j">
NB. factor count is the product of the incremented powers of prime factors
factor_count =: [: */ [: >: _&q:
 
NB. N are the integers 1 to 10000
NB. FC are the corresponding factor counts
FC =: factor_count&> N=: >: i. 10000
 
NB. take from the integers N{~
NB. the indexes of truth I.
NB. the vector which doesn't equal itself when rotated by one position (~: _1&|.)
NB. where that vector is the maximum over all prefixes of the factor counts >./\FC
N{~I.(~: _1&|.)>./\FC
1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560
</syntaxhighlight>
 
=={{header|Java}}==
{{trans|Go}}
<langsyntaxhighlight lang="java">public class Antiprime {
 
static int countDivisors(int n) {
Line 468 ⟶ 2,409:
System.out.println();
}
}</langsyntaxhighlight>
 
{{output}}
Line 474 ⟶ 2,415:
The first 20 anti-primes are:
1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560
</pre>
 
=={{header|Javascript}}==
<syntaxhighlight lang="javascript">
function factors(n) {
var factors = [];
for (var i = 1; i <= n; i++) {
if (n % i == 0) {
factors.push(i);
}
}
return factors;
}
 
function generateAntiprimes(n) {
var antiprimes = [];
var maxFactors = 0;
for (var i = 1; antiprimes.length < n; i++) {
var ifactors = factors(i);
if (ifactors.length > maxFactors) {
antiprimes.push(i);
maxFactors = ifactors.length;
}
}
return antiprimes;
}
 
function go() {
var number = document.getElementById("n").value;
document.body.removeChild(document.getElementById("result-list"));
document.body.appendChild(showList(generateAntiprimes(number)));
}
 
function showList(array) {
var list = document.createElement("ul");
list.id = "result-list";
for (var i = 0; i < array.length; i++) {
var item = document.createElement("li");
item.appendChild(document.createTextNode(array[i]));
list.appendChild(item);
}
return list;
}
</syntaxhighlight>
Html to test with some styling
<pre>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<script src="antiprimes.js"></script>
<title>Anti-Primes</title>
<style>
body {padding: 50px;width: 50%;box-shadow: 0 0 15px 0 rgba(0, 0, 0, 0.25);margin: 15px auto;font-family: "Gill Sans", "Gill Sans MT", Calibri, "Trebuchet MS", sans-serif;letter-spacing: 1px;}
a {color: #00aadd;text-decoration: none;}
input {width: 50px;text-align: center;}
ul {list-style: none;padding: 0;margin: 0;width: 25%;margin: auto;border: 1px solid #aaa;}
li {text-align: center;background-color: #eaeaea;}
li:nth-child(even) {background: #fff;}
</style>
</head>
<body onload="go()">
<h1>Anti-Primes</h1>
<div class="info">
The <a href="https://youtu.be/2JM2oImb9Qg">anti-primes</a> (or
<a href="https://en.wikipedia.org/wiki/Highly_composite_number">highly composite numbers</a>, sequence
<a href="https://oeis.org/A002182">A002182</a> in the <a href="https://oeis.org/">OEIS</a>) are the natural numbers with more factors than any
smaller than itself.
</div>
<p>Generate first <input id="n" type="text" placeholder="Enter the number" value="20" /> anti-primes. <button onclick="go()">Go</button></p>
<ul id="result-list"></ul>
</body>
</html>
</pre>
 
=={{header|jq}}==
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
<syntaxhighlight lang="jq">
# Compute the number of divisors, without calling sqrt
def ndivisors:
def sum(s): reduce s as $x (null; .+$x);
if . == 1 then 1
else . as $n
| sum( label $out
| range(1; $n) as $i
| ($i * $i) as $i2
| if $i2 > $n then break $out
else if $i2 == $n
then 1
elif ($n % $i) == 0
then 2
else empty
end
end)
end;
 
# Emit the antiprimes as a stream
def antiprimes:
1,
foreach range(2; infinite; 2) as $i ({maxfactors: 1};
.emit = null
| ($i | ndivisors) as $nfactors
| if $nfactors > .maxfactors
then .emit = $i
| .maxfactors = $nfactors
else .
end;
select(.emit).emit);
"The first 20 anti-primes are:", limit(20; antiprimes)
</syntaxhighlight>
{{out}}
<pre>
The first 20 anti-primes are:
1
2
4
6
12
24
36
48
60
120
180
240
360
720
840
1260
1680
2520
5040
7560
</pre>
 
=={{header|Julia}}==
 
<langsyntaxhighlight lang="julia">using Primes, Combinatorics
 
function antiprimes(N, maxmaxn = 2000000)
antip = [1] # special case: 1 is antiprime
count = 1
maxfactors = 1
for i in 2:2:maxmaxn # antiprimes > 2 should be even
lenfac = length(unique(sort(collect(combinations(factor(Vector, i)))))) + 1
if lenfac > maxfactors
Line 499 ⟶ 2,577:
println("The first 20 anti-primes are:\n", antiprimes(20))
println("The first 40 anti-primes are:\n", antiprimes(40))
</langsyntaxhighlight>{{output}}<pre>
The first 20 anti-primes are:
[1, 2, 4, 6, 12, 24, 36, 48, 60, 120, 180, 240, 360, 720, 840, 1260, 1680, 2520, 5040, 7560]
Line 510 ⟶ 2,588:
=={{header|Kotlin}}==
{{trans|Go}}
<langsyntaxhighlight lang="scala">// Version 1.3.10
 
fun countDivisors(n: Int): Int {
Line 536 ⟶ 2,614:
}
println()
}</langsyntaxhighlight>
 
{{output}}
Line 542 ⟶ 2,620:
The first 20 anti-primes are:
1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560
</pre>
 
=={{header|Lambdatalk}}==
 
==1) lambdatalk only==
<syntaxhighlight lang="scheme">
{def factors
{def factors.filter
{lambda {:n :a :i}
{if {= {% :n :i} 0}
then {A.addlast! :i :a}
else}}}
{lambda {:n}
{S.last
{S.map {factors.filter :n {A.new}}
{S.serie 1 :n}}}}}
-> factors
 
{def antiprimes
{def antiprimes.filter
{lambda {:ap :max :i}
{let { {:ap :ap} {:max :max} {:i :i}
{:len {A.length {factors :i}}}
} {if {> :len {A.get 0 :max}}
then {A.addlast! :i :ap}
{A.set! 0 :len :max}
else} }}}
{lambda {:n}
{S.first
{S.map {antiprimes.filter {A.new 1} {A.new 1}}
{S.serie 1 :n}}}}}
-> antiprimes
 
{antiprimes 8000} // 8000 choosen manually to reach 20 antiprimes
-> [1,2,4,6,12,24,36,48,60,120,180,240,360,720,840,1260,1680,2520,5040,7560]
// in 105400ms on my iPad
 
</syntaxhighlight>
 
==2) using javascript==
Lambdatalk can call javascript code, here simply copying the code written in the javascript entry.
 
<syntaxhighlight lang="scheme">
1) building the interface to the javascript function.
 
{script
LAMBDATALK.DICT['jsgenerateAntiprimes'] = function() {
function factors(n) {
var factors = [];
for (var i = 1; i <= n; i++) {
if (n % i == 0) {
factors.push(i);
}
}
return factors;
}
 
function generateAntiprimes(n) {
var antiprimes = [];
var maxFactors = 0;
for (var i = 1; antiprimes.length < n; i++) {
var ifactors = factors(i);
if (ifactors.length > maxFactors) {
antiprimes.push(i);
maxFactors = ifactors.length;
}
}
return antiprimes;
}
return generateAntiprimes( arguments[0].trim() )
};
}
 
2) and using it in the wiki page as a builtin primitive
 
{jsgenerateAntiprimes 20}
->
1,2,4,6,12,24,36,48,60,120,180,240,360,720,840,1260,1680,2520,5040,7560 // in 100ms
 
</syntaxhighlight>
 
=={{header|langur}}==
{{trans|D}}
<syntaxhighlight lang="langur">val countDivisors = fn(n) {
if n < 2: return 1
for[=2] i = 2; i <= n\2; i += 1 {
if n div i: _for += 1
}
}
 
writeln "The first 20 anti-primes are:"
var maxDiv, cnt = 0, 0
for n = 1; cnt < 20; n += 1 {
val d = countDivisors(n)
if d > maxDiv {
write n, " "
maxDiv = d
cnt += 1
}
}
writeln()
</syntaxhighlight>
 
{{out}}
<pre>1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560
</pre>
 
=={{header|Lua}}==
 
<lang lua>-- First 20 antiprimes.
===Counting the factors using modulo===
<syntaxhighlight lang="lua">-- First 20 antiprimes.
 
function count_factors(number)
Line 580 ⟶ 2,765:
recite(antiprimes(20))
print("Done.")
</syntaxhighlight>
</lang>
 
{{output}}
Line 605 ⟶ 2,790:
7560
Done.</pre>
 
===Using a table of divisor counts===
 
<syntaxhighlight lang="lua">
-- Find the first 20 antiprimes.
 
-- returns a table of the first goal antiprimes
function antiprimes(goal)
local maxNumber = 0
local ndc = {} -- table of divisor counts - initially empty
local list, number, mostFactors = {}, 1, 0
while #list < goal do
if number > #ndc then
-- need a bigger table of divisor counts
maxNumber = maxNumber + 5000
ndc = {}
for i = 1, maxNumber do ndc[ i ] = 1 end
for i = 2, maxNumber do
for j = i, maxNumber, i do ndc[ j ] = ndc[ j ] + 1 end
end
end
local factors = ndc[ number ]
if factors > mostFactors then
table.insert( list, number )
mostFactors = factors
end
number = number + 1
end
return list
end
 
-- display the antiprimes
oo.write( table.concat( antiprimes( 20 ), " " ) )
</syntaxhighlight>.
 
{{out}}
<pre>
1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560
</pre>
 
=={{header|Maple}}==
<syntaxhighlight lang="maple">antiprimes := proc(n)
local ap, i, max_divisors, num_divisors;
max_divisors := 0;
ap := [];
 
for i from 1 while numelems(ap) < n do
num_divisors := numelems(NumberTheory:-Divisors(i));
if num_divisors > max_divisors then
ap := [op(ap), i];
max_divisors := num_divisors;
end if;
end do;
 
return ap;
end proc:
antiprimes(20);</syntaxhighlight>
{{out}}
<pre>[1, 2, 4, 6, 12, 24, 36, 48, 60, 120, 180, 240, 360, 720, 840, 1260, 1680, 2520, 5040, 7560]</pre>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">sigma = DivisorSigma[0, #] &;
currentmax = -\[Infinity];
res = {};
Do[
s = sigma[v];
If[s > currentmax,
AppendTo[res, v];
currentmax = s;
];
If[Length[res] >= 25, Break[]]
,
{v, \[Infinity]}
]
res</syntaxhighlight>
{{out}}
<pre>{1,2,4,6,12,24,36,48,60,120,180,240,360,720,840,1260,1680,2520,5040,7560,10080,15120,20160,25200,27720}</pre>
 
=={{header|MiniScript}}==
{{Trans|Lua|Using a table of divisor counts}}
<syntaxhighlight lang="miniscript">
// Find the first 20 antiprimes.
 
// returns a table of the first goal antiprimes
antiprimes = function(goal)
maxNumber = 0
ndc = [] // table of divisor counts - initially empty
list = [0] * goal; number = 1; mostFactors = 0
aCount = 0
while aCount < goal
if number > maxNumber then
// need a bigger table of divisor counts
maxNumber = maxNumber + 5000
ndc = [1] * ( maxNumber + 1 )
ndc[ 0 ] = 0
for i in range( 2, maxNumber )
for j in range( i, maxNumber, i )
ndc[ j ] = ndc[ j ] + 1
end for
end for
end if
factors = ndc[ number ]
if factors > mostFactors then
list[ aCount ] = number
mostFactors = factors
aCount = aCount + 1
end if
number = number + 1
end while
return list
end function
 
// display the antiprimes
print antiprimes( 20 ).join( " " )
</syntaxhighlight>
{{out}}
<pre>
1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560
</pre>
 
=={{header|Modula-2}}==
<syntaxhighlight lang="modula2">MODULE Antiprimes;
FROM InOut IMPORT WriteCard, WriteLn;
 
CONST Amount = 20;
VAR max, seen, n, f: CARDINAL;
 
PROCEDURE factors(n: CARDINAL): CARDINAL;
VAR facs, div: CARDINAL;
BEGIN
IF n<2 THEN RETURN 1; END;
facs := 2;
FOR div := 2 TO n DIV 2 DO
IF n MOD div = 0 THEN
INC(facs);
END;
END;
RETURN facs;
END factors;
 
BEGIN
max := 0;
seen := 0;
n := 1;
WHILE seen < Amount DO
f := factors(n);
IF f > max THEN
WriteCard(n,5);
max := f;
INC(seen);
IF seen MOD 10 = 0 THEN WriteLn(); END;
END;
INC(n);
END;
END Antiprimes.</syntaxhighlight>
{{out}}
<pre> 1 2 4 6 12 24 36 48 60 120
180 240 360 720 840 1260 1680 2520 5040 7560</pre>
 
=={{header|Modula-3}}==
{{trans|Modula-2}}
<syntaxhighlight lang="modula3">MODULE AntiPrimes EXPORTS Main;
 
IMPORT IO,Fmt;
 
CONST
Amount = 20;
VAR
Max,Seen,N,F:CARDINAL;
 
PROCEDURE Factors(N:CARDINAL):CARDINAL =
VAR
Facts:CARDINAL;
BEGIN
IF N < 2 THEN RETURN 1 END;
Facts := 2;
FOR Div := 2 TO N DIV 2 DO
IF N MOD Div = 0 THEN INC(Facts) END;
END;
RETURN Facts;
END Factors;
BEGIN
Max := 0;
Seen := 0;
N := 1;
WHILE Seen < Amount DO
F := Factors(N);
IF F > Max THEN
IO.Put(Fmt.F("%5s",Fmt.Int(N)));
Max := F;
INC(Seen);
IF Seen MOD 10 = 0 THEN IO.Put("\n") END;
END;
INC(N);
END;
END AntiPrimes.
</syntaxhighlight>
{{output}}
<pre> 1 2 4 6 12 24 36 48 60 120
180 240 360 720 840 1260 1680 2520 5040 7560</pre>
 
=={{header|Nanoquery}}==
{{trans|C}}
<syntaxhighlight lang="nanoquery">def countDivisors(n)
if (n < 2)
return 1
end
count = 2
for i in range(2, int(n/2))
if (n % i) = 0
count += 1
end
end
return count
end
 
maxDiv = 0
count = 0
println "The first 20 anti-primes are:"
 
for (n = 1) (count < 20) (n += 1)
d = countDivisors(n)
if d > maxDiv
print format("%d ", n)
maxDiv = d
count += 1
end
end
println</syntaxhighlight>
{{out}}
<pre>The first 20 anti-primes are:
1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560 </pre>
 
=={{header|Nim}}==
<syntaxhighlight lang="nim"># First 20 antiprimes
 
proc countDivisors(n: int): int =
if n < 2:
return 1
var count = 2
for i in countup(2, (n / 2).toInt()):
if n %% i == 0:
count += 1
return count
 
proc antiPrimes(n: int) =
echo("The first ", n, " anti-primes:")
var maxDiv = 0
var count = 0
var i = 1
while count < n:
let d = countDivisors(i)
if d > maxDiv:
echo(i)
maxDiv = d
count += 1
i += 1
 
antiPrimes(20)
</syntaxhighlight>
{{output}}
<pre>The first 20 anti-primes:
1
2
4
6
12
24
36
48
60
120
180
240
360
720
840
1260
1680
2520
5040
7560</pre>
 
=={{header|Oberon-2}}==
{{trans|Modula-2}}
<syntaxhighlight lang="oberon2">MODULE AntiPrimes;
 
IMPORT Out;
CONST
Amount = 20;
VAR
Max,Seen,N,F:INTEGER;
 
PROCEDURE Factors(N:INTEGER):INTEGER;
VAR
Facts,Div:INTEGER;
BEGIN
IF N < 2 THEN RETURN 1 END;
Facts := 2;
FOR Div := 2 TO N DIV 2 DO
IF N MOD Div = 0 THEN INC(Facts) END;
END;
RETURN Facts;
END Factors;
BEGIN
Max := 0;
Seen := 0;
N := 1;
WHILE Seen < Amount DO
F := Factors(N);
IF F > Max THEN
Out.Int(N,5);
Max := F;
INC(Seen);
IF Seen MOD 10 = 0 THEN Out.Ln END;
END;
INC(N);
END;
END AntiPrimes.
</syntaxhighlight>
{{output}}
<pre>
1 2 4 6 12 24 36 48 60 120
180 240 360 720 840 1260 1680 2520 5040 7560
</pre>
 
=={{header|Objeck}}==
{{trans|Java}}
<syntaxhighlight lang="objeck">class AntiPrimes {
function : Main(args : String[]) ~ Nil {
maxDiv := 0; count := 0;
"The first 20 anti-primes are:"->PrintLine();
for(n := 1; count < 20; ++n;) {
d := CountDivisors(n);
if(d > maxDiv) {
"{$n} "->Print();
maxDiv := d;
count++;
};
};
'\n'->Print();
}
 
function : native : CountDivisors(n : Int) ~ Int {
if (n < 2) { return 1; };
count := 2;
for(i := 2; i <= n/2; ++i;) {
if(n%i = 0) { ++count; };
};
return count;
}
}</syntaxhighlight>
 
{{output}}
<pre>
1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560
</pre>
 
=={{header|Odin}}==
Anti-Primes
Odin Build: dev-2023-07-nightly:3072479c
<syntaxhighlight lang="go">
package antiprimes
import "core:fmt"
 
main :: proc() {
AntiPrimeCount, MaxDivisors, Divisors, n: u64
MaxAntiPrime: u64 = 20
fmt.print("\nFirst 20 anti-primes\n")
fmt.println("--------------------")
for (AntiPrimeCount < MaxAntiPrime) {
n += 1
Divisors = DivisorCount(n)
if Divisors > MaxDivisors {
fmt.print(n, " ")
MaxDivisors = Divisors
AntiPrimeCount += 1
}
}
}
 
DivisorCount :: proc(v: u64) -> u64 {
total: u64 = 1
a := v
if a == 0 {
return 0
}
for a % 2 == 0 {
total += 1
a /= 2
}
for p: u64 = 3; p * p <= a; p += 2 {
count: u64 = 1
for a % p == 0 {
count += 1
a /= p
}
total *= count
}
if a > 1 {
total *= 2
}
return total
}
</syntaxhighlight>
{{out}}
<pre>
First 20 anti-primes
--------------------
1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560
</pre>
 
=={{header|Pascal}}==
Easy factoring without primes.Decided to show count of factors.
<langsyntaxhighlight lang="pascal">program AntiPrimes;
{$IFdef FPC}
{$MOde Delphi}
Line 656 ⟶ 3,257:
until Count >= 20;
writeln;
end.</langsyntaxhighlight>;Output:<pre>1(1),2(2),4(3),6(4),12(6),24(8),36(9),48(10),60(12),120(16),180(18),240(20),
360(24),720(30),840(32),1260(36),1680(40),2520(48),5040(60),7560(64)</pre>
 
=={{header|PARI/GP}}==
 
<syntaxhighlight lang="parigp">
countfactors(n)={
my(count(m)= prod(i=1,#factor(m)~,factor(m)[i,2]+1));
v=vector(n);
v[1]=1;
for(x=2,n,
v[x]=v[x-1]+1;
while(count(v[x-1])>=count(v[x]),v[x]++));
return(v)}
countfactors(20)
</syntaxhighlight>
 
=={{header|Perl}}==
{{libheader|ntheory}}
<langsyntaxhighlight lang="perl">use ntheory qw(divisors);
 
my @anti_primes;
Line 674 ⟶ 3,289:
}
 
printf("%s\n", join(' ', @anti_primes));</langsyntaxhighlight>
{{out}}
<pre>
Line 680 ⟶ 3,295:
</pre>
 
=={{header|Perl 6Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
{{works with|Rakudo|2018.11}}
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
At its heart, this task is almost exactly the same as [[Proper_Divisors]], it is just asking for slightly different results. Much of this code is lifted straight from there.
<span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">maxd</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">1</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
<span style="color: #008080;">while</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">)<</span><span style="color: #000000;">20</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">lf</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">factors</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">))</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">lf</span><span style="color: #0000FF;">></span><span style="color: #000000;">maxd</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">res</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">n</span>
<span style="color: #000000;">maxd</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">lf</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">n</span> <span style="color: #0000FF;">+=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">></span><span style="color: #000000;">1</span><span style="color: #0000FF;">?</span><span style="color: #000000;">2</span><span style="color: #0000FF;">:</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</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;">"The first 20 anti-primes are: %V\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">res</span><span style="color: #0000FF;">})</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
The first 20 anti-primes are: {1,2,4,6,12,24,36,48,60,120,180,240,360,720,840,1260,1680,2520,5040,7560}
</pre>
 
=={{header|Phixmonti}}==
Implemented as an auto-extending lazy list. Displaying the count of anti-primes less than 5e5 also because... why not.
<syntaxhighlight lang="phixmonti">0 var count
0 var n
0 var max_divisors
 
"The first 20 anti-primes are:" print nl
<lang perl6>sub propdiv (\x) {
my @l = 1 if x > 1;
(2 .. x.sqrt.floor).map: -> \d {
unless x % d { @l.push: d; my \y = x div d; @l.push: y if y != d }
}
@l
}
 
def count_divisors
my atomicint $last = 0;
dup 2 < if
drop
1
else
2
swap 1 over 2 / 2 tolist
for
over swap mod not if swap 1 + swap endif
endfor
drop
endif
enddef
 
true
my @anti-primes = lazy 1, |(|(2..59), 60, *+60 … *).hyper.grep: -> $c {
while
my \mx = +propdiv($c);
nextcount if mx20 <= $last;dup if
$last = mx; n 1 + var n
n count_divisors
$c
dup max_divisors > if
}
n print " " print
var max_divisors
count 1 + var count
else
drop
endif
endif
endwhile
 
nl
my $upto = 5e5;
msec print</syntaxhighlight>
 
=={{header|Picat}}==
put "First 20 anti-primes:\n{ @anti-primes[^20] }";
{{trans|Go}}
{{works with|Picat}}
<syntaxhighlight lang="picat">
count_divisors(1) = 1.
 
count_divisors(N) = Count, N >= 2 =>
put "\nCount of anti-primes <= $upto: {+@anti-primes[^(@anti-primes.first: * > $upto, :k)]}";</lang>
Count = 2,
foreach (I in 2..N/2)
if (N mod I == 0) then
Count := Count + 1
end
end.
 
main =>
println("The first 20 anti-primes are:"),
MaxDiv = 0,
Count = 0,
N = 1,
while (Count < 20)
D := count_divisors(N),
if (D > MaxDiv) then
printf("%d ", N),
MaxDiv := D,
Count := Count + 1
end,
N := N + 1
end,
nl.
</syntaxhighlight>
{{out}}
<pre>
<pre>First 20 anti-primes:
The first 20 anti-primes are:
1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560
</pre>
 
=={{header|PicoLisp}}==
Count of anti-primes <= 500000: 35</pre>
<syntaxhighlight lang="picolisp">(de factors (N)
(let C 1
(when (>= N 2)
(inc 'C)
(for (I 2 (>= (/ N 2) I) (inc I))
(and (=0 (% N I)) (inc 'C)) ) )
C ) )
(de anti (X)
(let (M 0 I 0 N 0)
(make
(while (> X I)
(inc 'N)
(let R (factors N)
(when (> R M)
(link N)
(setq M R)
(inc 'I) ) ) ) ) ) )
(println (anti 20))</syntaxhighlight>
{{out}}
<pre>(1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560)</pre>
 
=={{header|PhixPILOT}}==
<syntaxhighlight lang="pilot">C :n=1
<lang Phix>integer n=1, maxd = -1
:max=0
sequence res = {}
:seen=0
while length(res)<20 do
integer lf = length(factors(n,1))
*number
if lf>maxd then
U :*count
res &= n
T (c>max):#n
maxd = lf
C (c>max):seen=seen+1
end if
C (c>max):max=c
n += iff(n>1?2:1)
:n=n+1
end while
J (seen<20):*number
printf(1,"The first 20 anti-primes are: ") ?res</lang>
E :
 
*count
C (n=1):c=1
E (n=1):
C :c=2
:i=2
*cnloop
E (i>n/2):
C (i*(n/i)=n):c=c+1
:i=i+1
J :*cnloop</syntaxhighlight>
{{out}}
<pre>1
2
4
6
12
24
36
48
60
120
180
240
360
720
840
1260
1680
2520
5040
7560</pre>
 
=={{header|PL/0}}==
{{trans|Tiny BASIC}}
<syntaxhighlight lang="pascal">
var i, n, maxdivcnt, divcnt;
 
procedure countdivs;
var p;
begin
divcnt := 1;
if n > 1 then divcnt := 2;
p := 2;
while p * p < n do
begin
if (n / p) * p = n then divcnt := divcnt + 2;
p := p + 1
end;
if p * p = n then divcnt := divcnt + 1
end;
 
procedure searchnext;
begin
call countdivs;
while divcnt <= maxdivcnt do
begin
n := n + 1;
call countdivs
end
end;
 
begin
i := 1; n := 1; maxdivcnt := 0;
while i <= 20 do
begin
call searchnext;
maxdivcnt := divcnt;
i := i + 1;
! n;
n := n + 1
end
end.
</syntaxhighlight>
{{out}}
<pre>
1
The first 20 anti-primes are: {1,2,4,6,12,24,36,48,60,120,180,240,360,720,840,1260,1680,2520,5040,7560}
2
4
6
12
24
36
48
60
120
180
240
360
720
840
1260
1680
2520
5040
7560
</pre>
 
=={{header|PL/I}}==
<syntaxhighlight lang="pli">antiprimes: procedure options(main);
 
/* count the factors of a number */
countFactors: procedure(n) returns(fixed);
declare (n, i, count) fixed;
if n<2 then return(1);
count = 1;
do i=1 to n/2;
if mod(n,i) = 0 then count = count + 1;
end;
return(count);
end countFactors;
declare maxFactors fixed static init (0);
declare seen fixed static init (0);
declare n fixed;
declare factors fixed;
do n=1 repeat(n+1) while(seen < 20);
factors = countFactors(n);
if factors > maxFactors then do;
put edit(n) (F(5));
maxFactors = factors;
seen = seen + 1;
if mod(seen,15) = 0 then put skip;
end;
end;
end antiprimes;</syntaxhighlight>
{{out}}
<pre> 1 2 4 6 12 24 36 48 60 120 180 240 360 720 840
1260 1680 2520 5040 7560</pre>
 
=={{header|PL/M}}==
<syntaxhighlight lang="pli">100H:
/* CP/M CALLS */
BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;
EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT;
PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9,S); END PRINT;
 
/* PRINT A NUMBER */
PRINT$NUMBER: PROCEDURE (N);
DECLARE S (7) BYTE INITIAL ('..... $');
DECLARE (N, P) ADDRESS, C BASED P BYTE;
P = .S(5);
DIGIT:
P = P - 1;
C = N MOD 10 + '0';
N = N / 10;
IF N > 0 THEN GO TO DIGIT;
CALL PRINT(P);
END PRINT$NUMBER;
 
/* COUNT THE FACTORS OF A NUMBER */
COUNT$FACTORS: PROCEDURE (N) ADDRESS;
DECLARE (N, I, COUNT) ADDRESS;
IF N<2 THEN RETURN 1;
COUNT = 1;
DO I=1 TO N/2;
IF N MOD I = 0 THEN COUNT = COUNT + 1;
END;
RETURN COUNT;
END COUNT$FACTORS;
 
DECLARE MAX$FACTORS ADDRESS INITIAL (0);
DECLARE SEEN BYTE INITIAL (0);
DECLARE N ADDRESS INITIAL (1);
DECLARE FACTORS ADDRESS;
 
DO WHILE SEEN < 20;
FACTORS = COUNT$FACTORS(N);
IF FACTORS > MAX$FACTORS THEN DO;
CALL PRINT$NUMBER(N);
MAX$FACTORS = FACTORS;
SEEN = SEEN + 1;
END;
N = N + 1;
END;
CALL EXIT;
EOF</syntaxhighlight>
{{out}}
<pre>1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560</pre>
 
=={{header|Processing}}==
<syntaxhighlight lang="processing">void setup() {
int most_factors = 0;
IntList anti_primes = new IntList();
int n = 1;
while (anti_primes.size() < 20) {
int counter = 1;
for (int i = 1; i <= n / 2; i++) {
if (n % i == 0) {
counter++;
}
}
if (counter > most_factors) {
anti_primes.append(n);
most_factors = counter;
}
n++;
}
for (int num : anti_primes) {
print(num + " ");
}
}</syntaxhighlight>
{{out}}
<pre>1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560</pre>
 
=={{header|Prolog}}==
{{trans|Erlang}}<syntaxhighlight lang="prolog">
divcount(N, Count) :- divcount(N, 1, 0, Count).
 
divcount(N, D, C, C) :- D*D > N, !.
divcount(N, D, C, Count) :-
succ(D, D2),
divs(N, D, A), plus(A, C, C2),
divcount(N, D2, C2, Count).
 
divs(N, D, 0) :- N mod D =\= 0, !.
divs(N, D, 1) :- D*D =:= N, !.
divs(_, _, 2).
 
 
antiprimes(N, L) :- antiprimes(N, 1, 0, [], L).
 
antiprimes(0, _, _, L, R) :- reverse(L, R), !.
antiprimes(N, M, Max, L, R) :-
divcount(M, Count),
succ(M, M2),
(Count > Max
-> succ(N0, N), antiprimes(N0, M2, Count, [M|L], R)
; antiprimes(N, M2, Max, L, R)).
 
main :-
antiprimes(20, X),
write("The first twenty anti-primes are "), write(X), nl,
halt.
 
?- main.
</syntaxhighlight>
{{out}}
<pre>
The first twenty anti-primes are [1,2,4,6,12,24,36,48,60,120,180,240,360,720,840,1260,1680,2520,5040,7560]
</pre>
 
=={{header|Python}}==
Uses the fast prime function from [[Factors of an integer#Python]]
<langsyntaxhighlight lang="python">from itertools import chain, count, cycle, islice, accumulate
def factors(n):
Line 742 ⟶ 3,679:
d,p = (), c
while not n%c:
n,p,d = n//c, p*c, d + (p,)
yield( d)
if n > 1: yield(( n,))
r = [1]
Line 753 ⟶ 3,690:
def antiprimes():
mx = 0
foryield c in count(1):
for c in count(2,2):
if c >= 58: break
ln = len(factors(c))
if ln > mx:
yield c
mx = ln
for c in count(60,30):
ln = len(factors(c))
if ln > mx:
yield c
mx = ln
 
if __name__ == '__main__':
print(list(*islice(antiprimes(), 2040)))</langsyntaxhighlight>
 
{{out}}
<pre>[1, 2, 4, 6, 12, 24, 36, 48, 60, 120, 180, 240, 360, 720, 840, 1260, 1680, 2520, 5040, 7560]</pre> 10080 15120 20160 25200 27720 45360 50400 55440 83160 110880 166320 221760 277200 332640 498960 554400 665280 720720 1081080 1441440
old algorithm (without count(60,30) part) time to find first 40 antiprimes: around 14 seconds
new algorithm (with count(60,30) part) time to find first 40 antiprimes: around 0.4 seconds</pre>
 
=={{header|Quackery}}==
<code>factors</code> is defined at [http://rosettacode.org/wiki/Factors_of_an_integer#Quackery Factors of an integer].
 
<syntaxhighlight lang="quackery"> 0 temp put
[] 0
[ 1+ dup factors size
dup temp share > iff
[ temp replace
dup dip join ]
else drop
over size 20 = until ]
temp release
drop echo</syntaxhighlight>
 
{{out}}
 
<pre>[ 1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560 ]</pre>
 
=={{header|R}}==
Uses brute force. My first entry!
<syntaxhighlight lang="r"># Antiprimes
 
max_divisors <- 0
 
findFactors <- function(x){
myseq <- seq(x)
myseq[(x %% myseq) == 0]
}
 
antiprimes <- vector()
x <- 1
n <- 1
while(length(antiprimes) < 20){
y <- findFactors(x)
if (length(y) > max_divisors){
antiprimes <- c(antiprimes, x)
max_divisors <- length(y)
n <- n + 1
}
x <- x + 1
}
 
antiprimes</syntaxhighlight>
 
{{out}}
<pre> [1] 1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560</pre>
 
=={{header|Racket}}==
 
<syntaxhighlight lang="racket">#lang racket
 
(require racket/generator
math/number-theory)
 
(define (get-divisors n)
(apply * (map (λ (factor) (add1 (second factor))) (factorize n))))
 
(define antiprimes
(in-generator
(for/fold ([prev 0]) ([i (in-naturals 1)])
(define divisors (get-divisors i))
(when (> divisors prev) (yield i))
(max prev divisors))))
 
(for/list ([i (in-range 20)] [antiprime antiprimes]) antiprime)</syntaxhighlight>
 
{{out}}
<pre>
'(1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560)
</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2018.11}}
At its heart, this task is almost exactly the same as [[Proper_Divisors]], it is just asking for slightly different results. Much of this code is lifted straight from there.
 
Implemented as an auto-extending lazy list. Displaying the count of anti-primes less than 5e5 also because... why not.
 
<syntaxhighlight lang="raku" line>sub propdiv (\x) {
my @l = 1 if x > 1;
(2 .. x.sqrt.floor).map: -> \d {
unless x % d { @l.push: d; my \y = x div d; @l.push: y if y != d }
}
@l
}
 
my $last = 0;
 
my @anti-primes = lazy 1, |(|(2..59), 60, *+60 … *).grep: -> $c {
my \mx = +propdiv($c);
next if mx <= $last;
$last = mx;
$c
}
 
my $upto = 5e5;
 
put "First 20 anti-primes:\n{ @anti-primes[^20] }";
 
put "\nCount of anti-primes <= $upto: {+@anti-primes[^(@anti-primes.first: * > $upto, :k)]}";</syntaxhighlight>
{{out}}
<pre>First 20 anti-primes:
1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560
 
Count of anti-primes <= 500000: 35</pre>
=={{header|Red}}==
<syntaxhighlight lang="rebol">Red []
inc: func ['v] [set v 1 + get v] ;; shortcut function for n: n + 1
 
n: 0 found: 0 max_div: 0
print "the first 20 anti-primes are:"
while [ inc n] [
nDiv: 1 ;; count n / n extra
if n > 1 [ repeat div n / 2 [ if n % div = 0 [inc nDiv] ] ]
if nDiv > max_div [
max_div: nDiv
prin [n ""]
if 20 <= inc found [halt]
]
]
</syntaxhighlight>
{{out}}<pre>
the first 20 anti-primes are:
1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560 (halted)
</pre>
 
=={{header|REXX}}==
Line 771 ⟶ 3,843:
This REXX version is using a modified version of a highly optimized &nbsp; ''proper divisors'' &nbsp; function.
 
Programming note: &nbsp; although the solution to this Rosetta Code task is trivial, a fair amount of optimization was incorporated into the REXX program to find larger anti─primes (also known as &nbsp; ''highly─composite numbers'').
 
The &nbsp; #DIVS &nbsp; function could be further optimized by only processing &nbsp; ''even'' &nbsp; numbers, with unity being treated as a special case.
<langsyntaxhighlight lang="rexx">/*REXX program finds and displays N number of anti─primes oranti-primes highly─composite(highly-composite) numbers.*/
parseParse argArg N . /* obtain optional argument from the CL. */
ifIf N=='' | N=="," thenThen N=20 /* Not specified? Then use the default. */
maxD= 0 /* the maximum number of divisors so far */
saySay '─index─-index- ──anti─prime──--anti-prime--' /* display a title forFor the numbers shown */
#nn= 0 /* the count of anti─primesanti-primes found " " */
Do i=1 For 59 While nn<N /* step through possible numbers by twos */
do once=1 for 1
d=nndivs(i) do i=1 for 59 /* get nn divisors; /*step through possible numbers by twos*/
If d>maxD Then Do d= #divs(i); if d<=maxD then iterate /*get #found divisors;an anti-prime Isnn set new maxD too small? Skip.*/
maxD=d
#= # + 1; maxD= d /*found an anti─prime #; set new minD.*/
nn=nn+1
say center(#, 7) right(i, 10) /*display the index and the anti─prime.*/
Say center(nn,7) if #>=N then leave once right(i,10) /*if wedisplay havethe enoughindex anti─primes,and donethe anti-prime. */
end /*i*/End
End /*i*/
 
Do do ji=60 by 20 While nn<N /* step through possible numbers by 20. */
d=nndivs(i)
d= #divs(j); if d<=maxD then iterate /*get # divisors; Is too small? Skip.*/
If d>maxD Then Do #= # + 1; maxD= d /* found an anti─prime #;anti-prime nn set new minD.maxD */
maxD=d
say center(#, 7) right(j, 10) /*display the index and the anti─prime.*/
nn=nn+1
if #>=N then leave once /*if we have enough anti─primes, done. */
Say center(nn,7) right(i,10) /* display the index and the anti-prime. */
end /*j*/
End
end /*once*/
End /*i*/
exit /*stick a fork in it, we're all done. */
Exit /* stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
/*-----------------------------------------------------------------------------------*/
#divs: procedure; parse arg x 1 y /*X and Y: both set from 1st argument.*/
nndivs: Procedure if x<3 then return x /* compute the number of proper /*handle special cases for onedivisors and two.*/
Parse Arg x
if x==4 then return 3 /* " " " " four. */
If x<2 Then
if x<6 then return 2 /* " " " " three or five*/
Return 1
odd= x // 2 /*check if X is odd or not. */
odd=x//2
if odd then do; #= 1; end /*Odd? Assume Pdivisors count of 1.*/
n=1 else do; #= 3; y= x%2; end /*Even? " /* 1 is a proper divisor " " " 3.*/
Do j=2+odd by 1+odd While j*j<x /* test all possible integers /* [↑] start with known num of Pdivs.*/
do k=3 for x%2-3 by 1+odd while k<y /*for oddup To but excluding sqrt(x) numbers, skip evens.*/
If x//j==0 Then if x//k==0* j thenis doa divisor,so is x%j /*if no remainder, then found a divisor*/
n=n+2
#=#+2; y=x%k /*bump # Pdivs, calculate limit Y. */
End
if k>=y then do; #= #-1; leave; end /*limit?*/
If j*j==x Then /* If x is enda square /* ___ */
n=n+1 else if k*k>x then leave /* sqrt(x) is a proper divisor /*only divide up to x */
n=n+1 end /*k*/ /* x is a proper divisor /* [↑] this form of DO loop is faster.*/
Return n</syntaxhighlight>
return #+1 /*bump "proper divisors" to "divisors".*/</lang>
{{out|output|text=&nbsp; when using the default input of: &nbsp; &nbsp; <tt> 20 </tt>}}
<pre>
Line 901 ⟶ 3,974:
This REXX version only processes &nbsp; ''even'' &nbsp; numbers &nbsp; (unity is treated as a special case.)
 
It's about &nbsp; '''1017%''' &nbsp; faster than the 1<sup>st</sup> REXX version.
<langsyntaxhighlight lang="rexx">/*REXX program finds and displays N number of anti─primes or highly─composite numbers.*/
parse arg N . /*obtain optional argument from the CL.*/
if N=='' | N=="," then N=20 20 /*Not specified? Then use the default.*/
@.= .; @.1= 1; @.2= 2; @.4= 3; @.5= 2; @.6= 4
say '─index─ ──anti─prime──' /*display a title for the numbers shown*/
#= 1 /*the count of anti─primes found " " */
Line 923 ⟶ 3,996:
say center(#, 7) right(j, 10) /*display the index and the anti─prime.*/
if #>=N then leave once /*if we have enough anti─primes, done. */
L= length(j) /*obtain the length of the index (J). */
if L>3 then j= j + left(4, L-2, 0) - 20 /*Length>3? Then calculate a long jump*/
end /*j*/
end /*once*/
Line 928 ⟶ 4,003:
/*──────────────────────────────────────────────────────────────────────────────────────*/
#divs: parse arg x; if @.x\==. then return @.x /*if pre─computed, then return shortcut*/
$= 3; y= x % 2
/* [↑] start with known num of Pdivs.*/
do k=3 for x%2-3 while k<y
if x//k==0 then do; $= $ + 2 /*if no remainder, then found a divisor*/
$=$+2; y= x % k /*bump $ Pdivs, calculate limit Y. */
if k>=y then do; $= $ - 1; leave; end /*limit?*/
end /* /* ___ */
else if k*k>x then leave /*only divide up to √ x */
end /*k*/ /* [↑] this form of DO loop is faster.*/
return $+1 /*bump "proper divisors" to "divisors".*/</langsyntaxhighlight>
{{out|output|text=&nbsp; is identical to the 1<sup>st</sup> REXX version.}} <br><br>
 
=={{header|Ring}}==
===Counting the divisors using modulo===
<syntaxhighlight lang="ring">
# Project : Anti-primes
 
see "working..." + nl
see "wait for done..." + nl + nl
see "the first 20 anti-primes are:" + nl + nl
maxDivisor = 0
num = 0
n = 0
result = list(20)
while num < 20
n = n + 1
div = factors(n)
if (div > maxDivisor)
maxDivisor = div
num = num + 1
result[num] = n
ok
end
see "["
for n = 1 to len(result)
if n < len(result)
see string(result[n]) + ","
else
see string(result[n]) + "]" + nl + nl
ok
next
see "done..." + nl
 
func factors(an)
ansum = 2
if an < 2
return(1)
ok
for nr = 2 to an/2
if an%nr = 0
ansum = ansum+1
ok
next
return ansum
</syntaxhighlight>
{{out}}
<pre>
working...
wait for done...
 
the first 20 anti-primes are:
 
[1,2,4,6,12,24,36,48,60,120,180,240,360,720,840,1260,1680,2520,5040,7560]
 
done...
</pre>
 
===Counting the divisors using a table===
 
<syntaxhighlight lang="ring">
# find the first 20 antiprimes
# - numbers woth more divisors than the previous numbers
 
numberOfDivisorCounts = 0
maxDivisor = 0
num = 0
n = 0
result = list(20)
while num < 20
n += 1
if n > numberOfDivisorCounts
# need a bigger table of divisor counts
numberOfDivisorCounts += 5000
ndc = list(numberOfDivisorCounts)
for i = 1 to numberOfDivisorCounts
ndc[ i ] = 1
next
for i = 2 to numberOfDivisorCounts
j = i
while j <= numberOfDivisorCounts
ndc[ j ] = ndc[ j ] + 1
j += i
end
next
ok
div = ndc[ n ]
if (div > maxDivisor)
maxDivisor = div
num += 1
result[num] = n
ok
end
see result[1]
for n = 2 to len(result)
see " " + string(result[n])
next
</syntaxhighlight>
 
{{out}}
<pre>
1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560
</pre>
 
=={{header|RPL}}==
We use here complex numbers to limit the stack size and ease its handling.
{{works with|Halcyon Calc|4.2.7}}
≪ → nb
≪ 1
1 nb 2 / '''FOR''' j
nb j MOD NOT +
'''NEXT'''
≫ ≫ ‘<span style="color:blue">NDIV</span>’ STO
≪ 1 - → items
≪ { } (2,0)
'''DO'''
DUP RE <span style="color:blue">NDIV</span>
'''IF''' OVER IM OVER < '''THEN'''
SWAP RE SWAP R→C
SWAP OVER RE + SWAP
'''ELSE''' DROP '''END'''
1 +
'''UNTIL''' OVER SIZE items > '''END'''
DROP
≫ ≫ ‘<span style="color:blue">ANTIP</span>’ STO
 
15 <span style="color:blue">ANTIP</span>
{{out}}
<pre>
{ 1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 }
</pre>
 
=={{header|Ruby}}==
<syntaxhighlight lang="ruby">require 'prime'
def num_divisors(n)
n.prime_division.inject(1){|prod, (_p,n)| prod * (n + 1) }
end
 
anti_primes = Enumerator.new do |y| # y is the yielder
max = 0
y << 1 # yield 1
2.step(nil,2) do |candidate| # nil is taken as Infinity
num = num_divisors(candidate)
if num > max
y << candidate # yield the candidate
max = num
end
end
end
 
puts anti_primes.take(20).join(" ")
</syntaxhighlight>
{{out}}
<pre>
1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560
</pre>
 
=={{header|Rust}}==
{{trans|Go}}
<syntaxhighlight lang="rust">fn count_divisors(n: u64) -> usize {
if n < 2 {
return 1;
}
2 + (2..=(n / 2)).filter(|i| n % i == 0).count()
}
 
fn main() {
println!("The first 20 anti-primes are:");
(1..)
.scan(0, |max, n| {
let d = count_divisors(n);
Some(if d > *max {
*max = d;
Some(n)
} else {
None
})
})
.flatten()
.take(20)
.for_each(|n| print!("{} ", n));
println!();
}</syntaxhighlight>
{{out}}
<pre>The first 20 anti-primes are:
1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560 </pre>
 
=={{header|Scala}}==
This program uses an iterator to count the factors of a number, then builds a lazily evaluated list of all anti-primes. Finding the first 20 anti-primes involves merely taking the first 20 elements of the list.
<syntaxhighlight lang="scala">def factorCount(num: Int): Int = Iterator.range(1, num/2 + 1).count(num%_ == 0) + 1
def antiPrimes: LazyList[Int] = LazyList.iterate((1: Int, 1: Int)){case (n, facs) => Iterator.from(n + 1).map(i => (i, factorCount(i))).dropWhile(_._2 <= facs).next}.map(_._1)</syntaxhighlight>
{{out}}
<pre>scala> print(antiPrimes.take(20).mkString(", "))
1, 2, 4, 6, 12, 24, 36, 48, 60, 120, 180, 240, 360, 720, 840, 1260, 1680, 2520, 5040, 7560</pre>
 
=={{header|Seed7}}==
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const func integer: countDivisors (in integer: number) is func
result
var integer: count is 1;
local
var integer: num is 0;
begin
for num range 1 to number div 2 do
if number rem num = 0 then
incr(count);
end if;
end for;
end func;
 
const proc: main is func
local
var integer: maxDiv is 0;
var integer: count is 0;
var integer: number is 1;
var integer: divisors is 1;
begin
writeln("The first 20 anti-primes are:");
while count < 20 do
divisors := countDivisors(number);
if divisors > maxDiv then
write(number <& " ");
maxDiv := divisors;
incr(count);
end if;
incr(number);
end while;
writeln;
end func;</syntaxhighlight>
 
{{out}}
<pre>The first 20 anti-primes are:
1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560
</pre>
 
=={{header|Sidef}}==
Using the built-in ''Number.sigma0'' method to count the number of divisors.
<langsyntaxhighlight lang="ruby">say with (0) {|max|
1..Inf -> lazy.grep { (.sigma0 > max) && (max = .sigma0) }.first(20)
}</langsyntaxhighlight>
{{out}}
<pre>
[1, 2, 4, 6, 12, 24, 36, 48, 60, 120, 180, 240, 360, 720, 840, 1260, 1680, 2520, 5040, 7560]
</pre>
 
=={{header|Swift}}==
 
<syntaxhighlight lang="swift">extension BinaryInteger {
@inlinable
public func countDivisors() -> Int {
var workingN = self
var count = 1
 
while workingN & 1 == 0 {
workingN >>= 1
 
count += 1
}
 
var d = Self(3)
 
while d * d <= workingN {
var (quo, rem) = workingN.quotientAndRemainder(dividingBy: d)
 
if rem == 0 {
var dc = 0
 
while rem == 0 {
dc += count
workingN = quo
 
(quo, rem) = workingN.quotientAndRemainder(dividingBy: d)
}
 
count += dc
}
 
d += 2
}
 
return workingN != 1 ? count * 2 : count
}
}
 
var antiPrimes = [Int]()
var maxDivs = 0
 
for n in 1... {
guard antiPrimes.count < 20 else {
break
}
 
let divs = n.countDivisors()
 
if maxDivs < divs {
maxDivs = divs
antiPrimes.append(n)
}
}
 
print("First 20 anti-primes are \(Array(antiPrimes))")</syntaxhighlight>
 
{{out}}
 
<pre>First 20 anti-primes are [1, 2, 4, 6, 12, 24, 36, 48, 60, 120, 180, 240, 360, 720, 840, 1260, 1680, 2520, 5040, 7560]</pre>
 
=={{header|Tcl}}==
{{trans|Java}}
 
<syntaxhighlight lang="tcl">
proc countDivisors {n} {
if {$n < 2} {return 1}
set count 2
set n2 [expr $n / 2]
for {set i 2} {$i <= $n2} {incr i} {
if {[expr $n % $i] == 0} {incr count}
}
return $count
}
 
# main
set maxDiv 0
set count 0
 
puts "The first 20 anti-primes are:"
for {set n 1} {$count < 20} {incr n} {
set d [countDivisors $n]
if {$d > $maxDiv} {
puts $n
set maxDiv $d
incr count
}
}
</syntaxhighlight>
{{out}}<pre>
./anti_primes.tcl
The first 20 anti-primes are:
1
2
4
6
12
24
36
48
60
120
180
240
360
720
840
1260
1680
2520
5040
7560
</pre>
 
=={{header|Transd}}==
<syntaxhighlight lang="scheme">
#lang transd
 
MainModule: {
countDivs: (λ n Int() ret_ Int()
(= ret_ 2)
(for i in Range(2 (to-Int (/ (to-Double n) 2) 1)) do
(if (not (mod n i)) (+= ret_ 1)))
(ret ret_)
),
 
_start: (λ locals: max 0 tmp 0 N 1 i 2
(textout 1 " ")
(while (< N 20)
(= tmp (countDivs i))
(if (> tmp max)
(textout i " ") (= max tmp) (+= N 1))
(+= i 1)
))
}</syntaxhighlight>{{out}}
<pre>
1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560
</pre>
 
=={{header|Uiua}}==
<syntaxhighlight lang="uiua">
# slightly faster than the simplistic /+=0◿+1⇡.
NDivs ← ⟨+2/+=0◿(↘1+1⇡⌊÷2).|1⟩<2.
⇌⊙◌◌⍢(
# Inc n, get NDiv: if >m, join n to accum, store new m.
⟨◌|⟜(⊂⊢)⍜(⊡1|◌):⟩:⟜<NDivs°⊟.⍜⊢(+1)
|
⋅(<:⧻) # Repeat until we have enough values.
)0_0 [] 20 # [n m] [accum] limit
</syntaxhighlight>
{{out}}
<pre>
[1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560]
</pre>
 
=={{header|Vala}}==
{{trans|C}}
<syntaxhighlight lang="vala">int count_divisors(int n) {
if (n < 2) return 1;
var count = 2;
for (int i = 2; i <= n/2; ++i)
if (n%i == 0) ++count;
return count;
}
void main() {
var max_div = 0;
var count = 0;
stdout.printf("The first 20 anti-primes are:\n");
for (int n = 1; count < 20; ++n) {
var d = count_divisors(n);
if (d > max_div) {
stdout.printf("%d ", n);
max_div = d;
count++;
}
}
stdout.printf("\n");
}</syntaxhighlight>
{{out}}
<pre>
The first 20 anti-primes are:
1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560
</pre>
 
=={{header|V (Vlang)}}==
{{trans|go}}
<syntaxhighlight lang="v (vlang)">fn count_divisors(n int) int {
if n < 2 {
return 1
}
mut count := 2 // 1 and n
for i := 2; i <= n/2; i++ {
if n%i == 0 {
count++
}
}
return count
}
fn main() {
println("The first 20 anti-primes are:")
mut max_div := 0
mut count := 0
for n := 1; count < 20; n++ {
d := count_divisors(n)
if d > max_div {
print("$n ")
max_div = d
count++
}
}
println('')
}</syntaxhighlight>
 
{{out}}
<pre>
The first 20 anti-primes are:
1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560
</pre>
 
=={{header|Wren}}==
{{libheader|Wren-math}}
<syntaxhighlight lang="wren">import "./math" for Int
 
System.print("The first 20 anti-primes are:")
var maxDiv = 0
var count = 0
var n = 1
while (count < 20) {
var d = Int.divisors(n).count
if (d > maxDiv) {
System.write("%(n) ")
maxDiv = d
count = count + 1
}
n = n + 1
}
System.print()</syntaxhighlight>
 
{{out}}
<pre>
The first 20 anti-primes are:
1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560
</pre>
 
=={{header|XPL0}}==
<syntaxhighlight lang="xpl0">int Counter, Num, Cnt, Div, Max;
[Counter:= 0;
Max:= 0;
Num:= 1;
loop [Cnt:= 0;
Div:= 1;
repeat if rem(Num/Div) = 0 then Cnt:= Cnt+1;
Div:= Div+1;
until Div > Num;
if Cnt > Max then
[IntOut(0, Num); ChOut(0, ^ );
Max:= Cnt;
Counter:= Counter+1;
if Counter >= 20 then quit;
];
Num:= Num+1;
];
]</syntaxhighlight>
 
{{out}}
<pre>
1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560
</pre>
 
=={{header|zkl}}==
{{trans|Perl6Raku}}
<langsyntaxhighlight lang="zkl">fcn properDivsN(n) //--> count of proper divisors. 1-->1, wrong but OK here
{ [1.. (n + 1)/2 + 1].reduce('wrap(p,i){ p + (n%i==0 and n!=i) }) }
fcn antiPrimes{ // -->iterator
Line 961 ⟶ 4,540:
c
}.fp1(Ref(0))).push(1); // 1 has no proper divisors
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">println("First 20 anti-primes:\n ",antiPrimes().walk(20).concat(" "));</langsyntaxhighlight>
{{out}}
<pre>
157

edits