Möbius function: Difference between revisions

From Rosetta Code
Content added Content deleted
(Added various BASIC dialects (Gambas, MSX Basic, PureBasic and XBasic))
 
(39 intermediate revisions by 17 users not shown)
Line 29: Line 29:
:*; [[Mertens function]]
:*; [[Mertens function]]
<br><br>
<br><br>

=={{header|11l}}==
{{trans|Python}}

<syntaxhighlight lang="11l">
F isPrime(n)
I n < 2
R 0B
L(i) 2 .. n
I i * i <= n & n % i == 0
R 0B
R 1B

F mobius(n)
I n == 1
R 1

V p = 0
L(i) 1 .. n
I n % i == 0 & isPrime(i)
I n % (i * i) == 0
R 0
E
p = p + 1

I p % 2 != 0
R -1
E
R 1

print(‘Mobius numbers from 1..99:’)

L(i) 1..99
print(f:‘{mobius(i):4}’, end' ‘’)

I i % 20 == 0
print()
</syntaxhighlight>

{{out}}
<pre>
Mobius numbers from 1..99:
1 -1 -1 0 -1 1 -1 0 0 1 -1 0 -1 1 1 0 -1 0 -1 0
1 1 -1 0 0 1 0 0 -1 -1 -1 0 1 1 1 0 -1 1 1 0
-1 -1 -1 0 0 1 -1 0 0 0 1 0 -1 0 1 0 1 1 -1 0
-1 1 0 0 1 -1 -1 0 1 -1 -1 0 -1 1 0 0 1 -1 -1 0
0 1 -1 0 1 1 1 0 -1 0 1 0 1 1 1 0 -1 0 0
</pre>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
{{Trans|C}}
{{Trans|C}}
<lang algol68>BEGIN
<syntaxhighlight lang="algol68">BEGIN
# show the first 199 values of the moebius function #
# show the first 199 values of the moebius function #
INT sq root = 1 000;
INT sq root = 1 000;
Line 58: Line 106:
IF ( i + 1 ) MOD 20 = 0 THEN print( ( newline ) ) FI
IF ( i + 1 ) MOD 20 = 0 THEN print( ( newline ) ) FI
OD
OD
END</lang>
END</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 72: Line 120:
0 1 0 -1 0 -1 1 -1 0 0 -1 0 0 -1 -1 0 0 1 1 -1
0 1 0 -1 0 -1 1 -1 0 0 -1 0 0 -1 -1 0 0 1 1 -1
0 -1 -1 1 0 1 -1 1 0 0 -1 -1 0 -1 1 -1 0 -1 0 -1
0 -1 -1 1 0 1 -1 1 0 0 -1 -1 0 -1 1 -1 0 -1 0 -1
</pre>

=={{header|Amazing Hopper}}==
{{Trans|Python}}
<syntaxhighlight lang="c">
#include <basico.h>

#proto cálculodeMobius(_X_)
#synon _cálculodeMobius calcularMobius

algoritmo
imprimir ("Mobius numbers from 1..199\n")
i=0, s=1
iterar grupo( ++i, #(i<=199), calcular Mobius (i), \
solo si (#( iszero(s%20) ), NL;s=0 ), imprimir, ++s )
saltar
terminar

subrutinas

cálculo de Mobius (n)
si( #(n==0) ) ; tomar '" "'
sino si( #(n==1) ); tomar '" 1"'
sino; p=0
iterar para (i=1, #(i<=n+1), ++i)
si ( #( iszero(n%i) && isprime(i)) )
cuando ( #( iszero(n%(i*i)) ) ){
tomar '" 0"'; ir a (herejía) /* ¡! */
} ++p
fin si
siguiente
tomar si ( es impar(p), " -1", " 1" )
fin si

/* ¡Dios! ¡Purifica esta mierda! ----+ */
/* | */
herejía: /* <----------------------+ */
retornar
</syntaxhighlight>
{{out}}
<pre>
Mobius numbers from 1..199
1 -1 -1 0 -1 1 -1 0 0 1 -1 0 -1 1 1 0 -1 0 -1
0 1 1 -1 0 0 1 0 0 -1 -1 -1 0 1 1 1 0 -1 1 1
0 -1 -1 -1 0 0 1 -1 0 0 0 1 0 -1 0 1 0 1 1 -1
0 -1 1 0 0 1 -1 -1 0 1 -1 -1 0 -1 1 0 0 1 -1 -1
0 0 1 -1 0 1 1 1 0 -1 0 1 0 1 1 1 0 -1 0 0
0 -1 -1 -1 0 -1 1 -1 0 -1 -1 1 0 -1 -1 1 0 0 1 1
0 0 1 1 0 0 0 -1 0 1 -1 -1 0 1 1 0 0 -1 -1 -1
0 1 1 1 0 1 1 0 0 -1 0 -1 0 0 -1 1 0 -1 1 1
0 1 0 -1 0 -1 1 -1 0 0 -1 0 0 -1 -1 0 0 1 1 -1
0 -1 -1 1 0 1 -1 1 0 0 -1 -1 0 -1 1 -1 0 -1 0 -1
</pre>
</pre>


=={{header|Arturo}}==
=={{header|Arturo}}==


<lang rebol>mobius: function [n][
<syntaxhighlight lang="rebol">mobius: function [n][
if n=0 -> return ""
if n=0 -> return ""
if n=1 -> return 1
if n=1 -> return 1
Line 87: Line 188:


loop split.every:20 map 0..199 => mobius 'a ->
loop split.every:20 map 0..199 => mobius 'a ->
print map a => [pad to :string & 3]</lang>
print map a => [pad to :string & 3]</syntaxhighlight>


{{out}}
{{out}}
Line 101: Line 202:
0 1 0 -1 0 -1 1 -1 0 0 -1 0 0 -1 -1 0 0 1 1 -1
0 1 0 -1 0 -1 1 -1 0 0 -1 0 0 -1 -1 0 0 1 1 -1
0 -1 -1 1 0 1 -1 1 0 0 -1 -1 0 -1 1 -1 0 -1 0 -1</pre>
0 -1 -1 1 0 1 -1 1 0 0 -1 -1 0 -1 1 -1 0 -1 0 -1</pre>

=={{header|AutoHotkey}}==
<syntaxhighlight lang="autohotkey">loop 100
result .= SubStr(" " Möbius(A_Index), -1) . (Mod(A_Index, 10) ? " " : "`n")
MsgBox, 262144, , % result
return

Möbius(n){
if n=1
return 1
x := prime_factors(n)
c := x.Count()
sq := []
for i, v in x
if sq[v]
return 0
else
sq[v] := 1
return (c/2 = floor(c/2)) ? 1 : -1
}

prime_factors(n) {
if (n <= 3)
return [n]
ans := [], done := false
while !done {
if !Mod(n, 2)
ans.push(2), n /= 2
else if !Mod(n, 3)
ans.push(3), n /= 3
else if (n = 1)
return ans
else {
sr := sqrt(n), done := true, i := 6
while (i <= sr+6) {
if !Mod(n, i-1) { ; is n divisible by i-1?
ans.push(i-1), n /= i-1, done := false
break
}
if !Mod(n, i+1) { ; is n divisible by i+1?
ans.push(i+1), n /= i+1, done := false
break
}
i += 6
}}}
ans.push(Format("{:d}", n))
return ans
}</syntaxhighlight>
{{out}}
<pre> 1 -1 -1 0 -1 1 -1 0 0 1
-1 0 -1 1 1 0 -1 0 -1 0
1 1 -1 0 0 1 0 0 -1 -1
-1 0 1 1 1 0 -1 1 1 0
-1 -1 -1 0 0 1 -1 0 0 0
1 0 -1 0 1 0 1 1 -1 0
-1 1 0 0 1 -1 -1 0 1 -1
-1 0 -1 1 0 0 1 -1 -1 0
0 1 -1 0 1 1 1 0 -1 0
1 0 1 1 1 0 -1 0 0 0</pre>


=={{header|AWK}}==
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f MOBIUS_FUNCTION.AWK
# syntax: GAWK -f MOBIUS_FUNCTION.AWK
# converted from Java
# converted from Java
Line 150: Line 310:
return(MU[n])
return(MU[n])
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 166: Line 326:
</pre>
</pre>


=={{header|BASIC}}==
==={{header|Applesoft BASIC}}===
<syntaxhighlight lang="qbasic">10 HOME
20 FOR t = 0 TO 9
30 FOR u = 1 TO 10
40 n = 10*t+u
50 GOSUB 130
60 IF STR$(m) = "0" THEN PRINT " 0";
70 IF STR$(m) = "1" THEN PRINT " 1";
80 IF STR$(m) = "-1" THEN PRINT " -1";
90 NEXT u
100 PRINT
110 NEXT t
120 END
130 IF n = 1 THEN m = 1 : RETURN
140 m = 1 : f = 2
150 IF (n-INT(n/(f*f))*(f*f)) = 0 THEN m = 0 : RETURN
160 IF (n-INT(n/(f))*(f)) = 0 THEN GOSUB 200
170 f = f+1
180 IF f <= n THEN GOTO 150
190 RETURN
200 m = -m
210 n = n/f
220 RETURN
230 END</syntaxhighlight>
{{out}}
<pre>Same as GW-BASIC entry.</pre>


=={{header|BASIC256}}==
==={{header|BASIC256}}===
{{trans|FreeBASIC}}
{{trans|FreeBASIC}}
<lang BASIC256>function mobius(n)
<syntaxhighlight lang="basic256">function mobius(n)
if n = 1 then return 1
if n = 1 then return 1
for d = 2 to int(sqr(n))
for d = 2 to int(sqr(n))
Line 189: Line 376:
end if
end if
next i
next i
end</lang>
end</syntaxhighlight>
{{out}}
<pre>Igual que la entrada de FreeBASIC.</pre>

==={{header|Chipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
{{works with|GW-BASIC}}
{{works with|QBasic}}
{{trans|GW-BASIC}}
<syntaxhighlight lang="qbasic">10 CLS
20 FOR t = 0 TO 9
30 FOR u = 1 TO 10
40 n = 10 * t + u
50 GOSUB 110
60 PRINT USING "## "; m;
70 NEXT u
80 PRINT
90 NEXT t
100 END
110 IF n = 1 THEN m = 1: RETURN
120 m = 1: f = 2
130 IF n MOD (f * f) = 0 THEN m = 0: RETURN
140 IF n MOD f = 0 THEN GOSUB 180
150 f = f + 1
160 IF f <= n THEN GOTO 130
170 RETURN
180 m = -m
190 n = n / f
200 RETURN
210 END</syntaxhighlight>
{{out}}
<pre>Same as GW-BASIC entry.</pre>

==={{header|FreeBASIC}}===
<syntaxhighlight lang="freebasic">function mobius( n as uinteger ) as integer
if n = 1 then return 1
for d as uinteger = 2 to int(sqr(n))
if n mod d = 0 then
if n mod (d*d) = 0 then return 0
return -mobius(n/d)
end if
next d
return -1
end function

dim as string outstr = " . "
for i as uinteger = 1 to 200
if mobius(i)>=0 then outstr += " "
outstr += str(mobius(i))+" "
if i mod 10 = 9 then
print outstr
outstr = ""
end if
next i</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
. 1 -1 -1 0 -1 1 -1 0 0
Igual que la entrada de FreeBASIC.
1 -1 0 -1 1 1 0 -1 0 -1
0 1 1 -1 0 0 1 0 0 -1
-1 -1 0 1 1 1 0 -1 1 1
0 -1 -1 -1 0 0 1 -1 0 0
0 1 0 -1 0 1 0 1 1 -1
0 -1 1 0 0 1 -1 -1 0 1
-1 -1 0 -1 1 0 0 1 -1 -1
0 0 1 -1 0 1 1 1 0 -1
0 1 0 1 1 1 0 -1 0 0
0 -1 -1 -1 0 -1 1 -1 0 -1
-1 1 0 -1 -1 1 0 0 1 1
0 0 1 1 0 0 0 -1 0 1
-1 -1 0 1 1 0 0 -1 -1 -1
0 1 1 1 0 1 1 0 0 -1
0 -1 0 0 -1 1 0 -1 1 1
0 1 0 -1 0 -1 1 -1 0 0
-1 0 0 -1 -1 0 0 1 1 -1
0 -1 -1 1 0 1 -1 1 0 0
-1 -1 0 -1 1 -1 0 -1 0 -1</pre>

==={{header|FutureBasic}}===
<syntaxhighlight lang="futurebasic">local fn IsPrime( n as long ) as BOOL
BOOL result = YES
long i
if ( n < 2 ) then result = NO : exit fn
for i = 2 to n + 1
if ( i * i <= n ) and ( n mod i == 0 )
result = NO : exit fn
end if
next
end fn = result

local fn Mobius( n as long ) as long
long i, p = 0, result = 0
if ( n == 1 ) then result = 1 : exit fn
for i = 1 to n + 1
if ( n mod i == 0 ) and ( fn IsPrime( i ) == YES )
if ( n mod ( i * i ) == 0 )
result = 0 : exit fn
else
p++
end if
end if
next
if( p mod 2 != 0 )
result = -1
else
result = 1
end if
end fn = result

window 1, @"Möbius function", (0,0,600,300)

printf @"First 100 terms of Mobius sequence:"

long i
for i = 1 to 100
printf @"%2ld\t", fn Mobius(i)
if ( i mod 20 == 0 ) then print
next

HandleEvents</syntaxhighlight>
{{output}}
<pre>
First 100 terms of Mobius sequence:
1 -1 -1 0 -1 1 -1 0 0 1 -1 0 -1 1 1 0 -1 0 -1 0
1 1 -1 0 0 1 0 0 -1 -1 -1 0 1 1 1 0 -1 1 1 0
-1 -1 -1 0 0 1 -1 0 0 0 1 0 -1 0 1 0 1 1 -1 0
-1 1 0 0 1 -1 -1 0 1 -1 -1 0 -1 1 0 0 1 -1 -1 0
0 1 -1 0 1 1 1 0 -1 0 1 0 1 1 1 0 -1 0 0 0
</pre>
</pre>


==={{header|Gambas}}===
{{trans|FreeBASIC}}
{{works with|Windows}}
<syntaxhighlight lang="vbnet">Public Sub Main()
Dim outstr As String = " . "

For i As Integer = 1 To 200
If mobius(i) >= 0 Then outstr &= " "
outstr &= Str(mobius(i)) & " "
If i Mod 10 = 9 Then
Print outstr
outstr = ""
End If
Next
End

Function mobius(n As Integer) As Integer

If n = 1 Then Return 1
For d As Integer = 2 To Int(Sqr(n))
If n Mod d = 0 Then
If n Mod (d * d) = 0 Then Return 0
Return -mobius(n / d)
End If
Next
Return -1

End Function</syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>

==={{header|GW-BASIC}}===
{{works with|BASICA}}
<syntaxhighlight lang="gwbasic">10 FOR T = 0 TO 9
20 FOR U = 1 TO 10
30 N = 10*T + U
40 GOSUB 100
50 PRINT USING "## ";M;
60 NEXT U
70 PRINT
80 NEXT T
90 END
100 IF N = 1 THEN M = 1 : RETURN
110 M = 1 : F = 2
120 IF N MOD (F*F) = 0 THEN M = 0 : RETURN
130 IF N MOD F = 0 THEN GOSUB 170
140 F = F + 1
150 IF F <= N THEN GOTO 120
160 RETURN
170 M = -M
180 N = N/F
190 RETURN</syntaxhighlight>
{{out}}
<pre>
1 -1 -1 0 -1 1 -1 0 0 1
-1 0 -1 1 1 0 -1 0 -1 0
1 1 -1 0 0 1 0 0 -1 -1
-1 0 1 1 1 0 -1 1 1 0
-1 -1 -1 0 0 1 -1 0 0 0
1 0 -1 0 1 0 1 1 -1 0
-1 1 0 0 1 -1 -1 0 1 -1
-1 0 -1 1 0 0 1 -1 -1 0
0 1 -1 0 1 1 1 0 -1 0
1 0 1 1 1 0 -1 0 0 0
</pre>

==={{header|Minimal BASIC}}===
{{trans|GW-BASIC}}
{{works with|Applesoft BASIC}}
{{works with|Chipmunk Basic|3.6.4}}
{{works with|Commodore BASIC|3.5}}
{{works with|Nascom ROM BASIC|4.7}}
<syntaxhighlight lang="basic">10 REM Moebius function
20 FOR T = 0 TO 9
30 FOR U = 1 TO 10
40 LET N = 10*T+U
50 GOSUB 110
60 PRINT M;" ";
70 NEXT U
80 PRINT
90 NEXT T
100 END

110 LET M = 1
120 IF N = 1 THEN 230
130 LET F = 2
140 LET F2 = F*F
150 IF INT(N/F2)*F2 <> N THEN 180
160 LET M = 0
170 GOTO 230
180 IF INT(N/F)*F <> N THEN 210
190 LET M = -M
200 LET N = N/F
210 LET F = F+1
220 IF F <= N THEN 140
230 RETURN
</syntaxhighlight>

==={{header|MSX Basic}}===
{{works with|MSX BASIC|any}}
The [[#GW-BASIC|GW-BASIC]] solution works without any changes.

==={{header|PureBasic}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="purebasic">Procedure.i mobius(n)
If n = 1:
ProcedureReturn 1
EndIf
For d = 2 To Int(Sqr(n))
If Mod(n, d) = 0:
If Mod(n, d * d) = 0:
ProcedureReturn 0
EndIf
ProcedureReturn -mobius(n / d)
EndIf
Next d
ProcedureReturn -1
EndProcedure

OpenConsole()
outstr$ = " . "
For i = 1 To 200
If mobius(i) >= 0:
outstr$ = outstr$ + " "
EndIf
outstr$ = outstr$ + Str(mobius(i)) + " "
If Mod(i, 10) = 9:
PrintN(outstr$)
outstr$ = ""
EndIf
Next i

PrintN(#CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()</syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>

==={{header|Tiny BASIC}}===
Tiny BASIC is not suited for printing tables, so this is limited to prompting for a single number and calculating its Mobius number.
<syntaxhighlight lang="tinybasic"> PRINT "Enter an integer"
INPUT N
IF N < 0 THEN LET N = -N
IF N < 2 THEN GOTO 100 + N
LET C = 1
LET F = 2
10 IF ((N/F)/F)*F*F = N THEN GOTO 100
IF (N/F)*F = N THEN GOTO 30
20 LET F = F + 1
IF F<=N THEN GOTO 10
GOTO 100 + C
30 LET N = N / F
LET C = -C
GOTO 20
99 PRINT "-1"
END
100 PRINT "0"
END
101 PRINT "1"
END</syntaxhighlight>

==={{header|XBasic}}===
{{works with|Windows XBasic}}
{{trans|FreeBASIC}}
<syntaxhighlight lang="qbasic">PROGRAM "Möbius function"
VERSION "0.0000"
IMPORT "xma"


DECLARE FUNCTION Entry ()
DECLARE FUNCTION mobius (n)

FUNCTION Entry ()
outstr$ = " . "
FOR i = 1 TO 200
IF mobius(i) >= 0 THEN outstr$ = outstr$
outstr$ = outstr$ + STR$(mobius(i)) + " "
IF i MOD 10 = 9 THEN
PRINT outstr$
outstr$ = ""
END IF
NEXT i
END FUNCTION

FUNCTION mobius (n)
IF n = 1 THEN RETURN 1
FOR d = 2 TO INT(SQRT(n))
IF n MOD d = 0 THEN
IF n MOD (d*d) = 0 THEN RETURN 0
RETURN -mobius(n/d)
END IF
NEXT d
RETURN -1
END FUNCTION
END PROGRAM</syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>

==={{header|Yabasic}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="yabasic">outstr$ = " . "
for i = 1 to 200
if mobius(i) >= 0 then outstr$ = outstr$ + " " : fi
outstr$ = outstr$ + str$(mobius(i)) + " "
if mod(i, 10) = 9 then
print outstr$
outstr$ = ""
end if
next i
end

sub mobius(n)
if n = 1 then return 1 : fi
for d = 2 to int(sqr(n))
if mod(n, d) = 0 then
if mod(n, (d*d)) = 0 then return 0 : fi
return -mobius(n/d)
end if
next d
return -1
end sub</syntaxhighlight>


=={{header|C}}==
=={{header|C}}==
{{trans|Java}}
{{trans|Java}}
<lang c>#include <math.h>
<syntaxhighlight lang="c">#include <math.h>
#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
Line 252: Line 786:
free(mu);
free(mu);
return 0;
return 0;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>First 199 terms of the m÷bius function are as follows:
<pre>First 199 terms of the m÷bius function are as follows:
Line 268: Line 802:
=={{header|C++}}==
=={{header|C++}}==
{{trans|Java}}
{{trans|Java}}
<lang cpp>#include <iomanip>
<syntaxhighlight lang="cpp">#include <iomanip>
#include <iostream>
#include <iostream>
#include <vector>
#include <vector>
Line 322: Line 856:


return 0;
return 0;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>First 199 terms of the m÷bius function are as follows:
<pre>First 199 terms of the m÷bius function are as follows:
Line 338: Line 872:
=={{header|D}}==
=={{header|D}}==
{{trans|C++}}
{{trans|C++}}
<lang d>import std.math;
<syntaxhighlight lang="d">import std.math;
import std.stdio;
import std.stdio;


Line 393: Line 927:
}
}
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>First 199 terms of the m├╢bius function are as follows:
<pre>First 199 terms of the m├╢bius function are as follows:
Line 406: Line 940:
0 1 0 -1 0 -1 1 -1 0 0 -1 0 0 -1 -1 0 0 1 1 -1
0 1 0 -1 0 -1 1 -1 0 0 -1 0 0 -1 -1 0 0 1 1 -1
0 -1 -1 1 0 1 -1 1 0 0 -1 -1 0 -1 1 -1 0 -1 0 -1</pre>
0 -1 -1 1 0 1 -1 1 0 0 -1 -1 0 -1 1 -1 0 -1 0 -1</pre>

=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
Rather than being clever and trying to perform the task in the smallest number of lines possible, this solution breaks the problem down into its fundamental pieces and solves each one in a separate subroutine. This programming style makes the code easier understand, debug and enhance the code. While the technique is not necessary on simple problems like this, it is essential for larger and more complex programs.

<syntaxhighlight lang="Delphi">
function IsPrime(N: int64): boolean;
{Fast, optimised prime test}
var I,Stop: int64;
begin
if (N = 2) or (N=3) then Result:=true
else if (n <= 1) or ((n mod 2) = 0) or ((n mod 3) = 0) then Result:= false
else
begin
I:=5;
Stop:=Trunc(sqrt(N+0.0));
Result:=False;
while I<=Stop do
begin
if ((N mod I) = 0) or ((N mod (I + 2)) = 0) then exit;
Inc(I,6);
end;
Result:=True;
end;
end;



function GetNextPrime(var Start: integer): integer;
{Get the next prime number after Start}
{Start is passed by "reference," so the
{original variable is incremented}
begin
repeat Inc(Start)
until IsPrime(Start);
Result:=Start;
end;


type TIntArray = array of integer;


procedure StoreNumber(N: integer; var IA: TIntArray);
{Expand and store number in array}
begin
SetLength(IA,Length(IA)+1);
IA[High(IA)]:=N;
end;


procedure GetPrimeFactors(N: integer; var Facts: TIntArray);
{Get all the prime factors of a number}
var I: integer;
begin
I:=2;
repeat
begin
if (N mod I) = 0 then
begin
StoreNumber(I,Facts);
N:=N div I;
end
else GetNextPrime(I);
end
until N=1;
end;



function HasDuplicates(IA: TIntArray): boolean;
{Look for duplicates factors in array}
var I: integer;
begin
Result:=True;
for I:=0 to Length(IA)-1 do
if IA[I]=IA[I+1] then exit;
Result:=False;
end;


function Moebius(N: integer): integer;
{Get moebius function of number}
var I: integer;
var Factors: TIntArray;
var Even,Square: boolean;
begin
{Collect all prime factors}
SetLength(Factors,0);
GetPrimeFactors(N,Factors);
{Are there an even number of factors?}
Even:=(Length(Factors) and 1)=0;
{If there are duplicates, there are perfect squares}
Square:=HasDuplicates(Factors);
{Return the Moebius function value}
if Square then Result:=0
else if Even then Result:=1
else Result:=-1;
end;

procedure TestMoebiusFactors(Memo: TMemo);
{Test Moebius function for 1..200-1}
var N,M: integer;
var S: string;
begin
S:='';
for N:=1 to 199 do
begin
M:=Moebius(N);
S:=S+Format('%3d',[M]);
if (N mod 20)=19 then S:=S+#$0D#$0A
end;
Memo.Text:=S;
end;


</syntaxhighlight>
{{out}}
<pre>
1 -1 -1 0 -1 1 -1 0 0 1 -1 0 -1 1 1 0 -1 0 -1
0 1 1 -1 0 0 1 0 0 -1 -1 -1 0 1 1 1 0 -1 1 1
0 -1 -1 -1 0 0 1 -1 0 0 0 1 0 -1 0 1 0 1 1 -1
0 -1 1 0 0 1 -1 -1 0 1 -1 -1 0 -1 1 0 0 1 -1 -1
0 0 1 -1 0 1 1 1 0 -1 0 1 0 1 1 1 0 -1 0 0
0 -1 -1 -1 0 -1 1 -1 0 -1 -1 1 0 -1 -1 1 0 0 1 1
0 0 1 1 0 0 0 -1 0 1 -1 -1 0 1 1 0 0 -1 -1 -1
0 1 1 1 0 1 1 0 0 -1 0 -1 0 0 -1 1 0 -1 1 1
0 1 0 -1 0 -1 1 -1 0 0 -1 0 0 -1 -1 0 0 1 1 -1
0 -1 -1 1 0 1 -1 1 0 0 -1 -1 0 -1 1 -1 0 -1 0 -1
</pre>

=={{header|EasyLang}}==
{{trans|C}}
<syntaxhighlight lang=easylang>
mu_max = 100000
sqroot = floor sqrt mu_max
#
for i to mu_max
mu[] &= 1
.
for i = 2 to sqroot
if mu[i] = 1
for j = i step i to mu_max
mu[j] *= -i
.
for j = i * i step i * i to mu_max
mu[j] = 0
.
.
.
for i = 2 to mu_max
if mu[i] = i
mu[i] = 1
elif mu[i] = -i
mu[i] = -1
elif mu[i] < 0
mu[i] = 1
elif mu[i] > 0
mu[i] = -1
.
.
numfmt 0 3
for i = 1 to 100
write mu[i]
if i mod 10 = 0
print ""
.
.
</syntaxhighlight>


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
This task uses [[Extensible_prime_generator#The_functions|Extensible Prime Generator (F#)]]
This task uses [[Extensible_prime_generator#The_functions|Extensible Prime Generator (F#)]]
<lang fsharp>
<syntaxhighlight lang="fsharp">
// Möbius function. Nigel Galloway: January 31st., 2021
// Möbius function. Nigel Galloway: January 31st., 2021
let fN g=let n=primes32()
let fN g=let n=primes32()
Line 419: Line 1,122:
let mobius=seq{yield 1; yield! Seq.initInfinite((+)2>>fN)}
let mobius=seq{yield 1; yield! Seq.initInfinite((+)2>>fN)}
mobius|>Seq.take 500|>Seq.chunkBySize 25|>Seq.iter(fun n->Array.iter(printf "%3d") n;printfn "")
mobius|>Seq.take 500|>Seq.chunkBySize 25|>Seq.iter(fun n->Array.iter(printf "%3d") n;printfn "")
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 447: Line 1,150:
The <code>mobius</code> word exists in the <code>math.extras</code> vocabulary. See the implementation [https://docs.factorcode.org/content/word-mobius%2Cmath.extras.html here].
The <code>mobius</code> word exists in the <code>math.extras</code> vocabulary. See the implementation [https://docs.factorcode.org/content/word-mobius%2Cmath.extras.html here].
{{works with|Factor|0.99 2020-01-23}}
{{works with|Factor|0.99 2020-01-23}}
<lang factor>USING: formatting grouping io math.extras math.ranges sequences ;
<syntaxhighlight lang="factor">USING: formatting grouping io math.extras math.ranges sequences ;


"First 199 terms of the Möbius sequence:" print
"First 199 terms of the Möbius sequence:" print
199 [1,b] [ mobius ] map " " prefix 20 group
199 [1,b] [ mobius ] map " " prefix 20 group
[ [ "%3s" printf ] each nl ] each</lang>
[ [ "%3s" printf ] each nl ] each</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 469: Line 1,172:
=={{header|Fortran}}==
=={{header|Fortran}}==
{{Trans|C}}
{{Trans|C}}
<lang fortran>
<syntaxhighlight lang="fortran">
program moebius
program moebius
use iso_fortran_env, only: output_unit
use iso_fortran_env, only: output_unit
Line 511: Line 1,214:
end do
end do
end program moebius
end program moebius
</syntaxhighlight>
</lang>

{{out}}
{{out}}
<pre>
<pre>
Line 526: Line 1,228:
0 1 0 -1 0 -1 1 -1 0 0 -1 0 0 -1 -1 0 0 1 1 -1
0 1 0 -1 0 -1 1 -1 0 0 -1 0 0 -1 -1 0 0 1 1 -1
0 -1 -1 1 0 1 -1 1 0 0 -1 -1 0 -1 1 -1 0 -1 0 -1
0 -1 -1 1 0 1 -1 1 0 0 -1 -1 0 -1 1 -1 0 -1 0 -1
</pre>

=={{header|FreeBASIC}}==
<lang freebasic>function mobius( n as uinteger ) as integer
if n = 1 then return 1
for d as uinteger = 2 to int(sqr(n))
if n mod d = 0 then
if n mod (d*d) = 0 then return 0
return -mobius(n/d)
end if
next d
return -1
end function

dim as string outstr = " . "
for i as uinteger = 1 to 200
if mobius(i)>=0 then outstr += " "
outstr += str(mobius(i))+" "
if i mod 10 = 9 then
print outstr
outstr = ""
end if
next i</lang>
{{out}}
<pre>
. 1 -1 -1 0 -1 1 -1 0 0
1 -1 0 -1 1 1 0 -1 0 -1
0 1 1 -1 0 0 1 0 0 -1
-1 -1 0 1 1 1 0 -1 1 1
0 -1 -1 -1 0 0 1 -1 0 0
0 1 0 -1 0 1 0 1 1 -1
0 -1 1 0 0 1 -1 -1 0 1
-1 -1 0 -1 1 0 0 1 -1 -1
0 0 1 -1 0 1 1 1 0 -1
0 1 0 1 1 1 0 -1 0 0
0 -1 -1 -1 0 -1 1 -1 0 -1
-1 1 0 -1 -1 1 0 0 1 1
0 0 1 1 0 0 0 -1 0 1
-1 -1 0 1 1 0 0 -1 -1 -1
0 1 1 1 0 1 1 0 0 -1
0 -1 0 0 -1 1 0 -1 1 1
0 1 0 -1 0 -1 1 -1 0 0
-1 0 0 -1 -1 0 0 1 1 -1
0 -1 -1 1 0 1 -1 1 0 0
-1 -1 0 -1 1 -1 0 -1 0 -1</pre>


=={{header|FutureBasic}}==
<lang futurebasic>local fn IsPrime( n as long ) as Boolean
long i, result
if ( n < 2 ) then result = NO : exit fn
for i = 2 to n + 1
if ( i * i <= n ) and ( n mod i == 0 )
result = NO : exit fn
end if
next
result = YES
end fn = result

local fn Mobius( n as long ) as long
long i, p = 0, result = 0
if ( n == 1 ) then result = 1 : exit fn
for i = 1 to n + 1
if ( n mod i == 0 ) and ( fn IsPrime( i ) == YES )
if ( n mod ( i * i ) == 0 )
result = 0 : exit fn
else
p++
end if
end if
next
if( p mod 2 != 0 )
result = -1
else
result = 1
end if
end fn = result

window 1, @"Möbius function", (0,0,600,300)

printf @"First 100 terms of Mobius sequence:"

long i
for i = 1 to 100
printf @"%2ld\t", fn Mobius(i)
if ( i mod 20 == 0 ) then print
next

HandleEvents</lang>
{{output}}
<pre>
First 100 terms of Mobius sequence:
1 -1 -1 0 -1 1 -1 0 0 1 -1 0 -1 1 1 0 -1 0 -1 0
1 1 -1 0 0 1 0 0 -1 -1 -1 0 1 1 1 0 -1 1 1 0
-1 -1 -1 0 0 1 -1 0 0 0 1 0 -1 0 1 0 1 1 -1 0
-1 1 0 0 1 -1 -1 0 1 -1 -1 0 -1 1 0 0 1 -1 -1 0
0 1 -1 0 1 1 1 0 -1 0 1 0 1 1 1 0 -1 0 0 0
</pre>
</pre>


=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<syntaxhighlight lang="go">package main


import "fmt"
import "fmt"
Line 686: Line 1,286:
fmt.Printf(" % d", mobs[i])
fmt.Printf(" % d", mobs[i])
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 702: Line 1,302:
0 -1 -1 1 0 1 -1 1 0 0 -1 -1 0 -1 1 -1 0 -1 0 -1
0 -1 -1 1 0 1 -1 1 0 0 -1 -1 0 -1 1 -1 0 -1 0 -1
</pre>
</pre>

=={{header|GW-BASIC}}==
<lang gwbasic>10 FOR T = 0 TO 9
20 FOR U = 1 TO 10
30 N = 10*T + U
40 GOSUB 100
50 PRINT USING "## ";M;
60 NEXT U
70 PRINT
80 NEXT T
90 END
100 IF N = 1 THEN M = 1 : RETURN
110 M = 1 : F = 2
120 IF N MOD (F*F) = 0 THEN M = 0 : RETURN
130 IF N MOD F = 0 THEN GOSUB 170
140 F = F + 1
150 IF F <= N THEN GOTO 120
160 RETURN
170 M = -M
180 N = N/F
190 RETURN</lang>


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang haskell>import Data.List (intercalate)
<syntaxhighlight lang="haskell">import Data.List (intercalate)
import Data.List.Split (chunksOf)
import Data.List.Split (chunksOf)
import Data.Vector.Unboxed (toList)
import Data.Vector.Unboxed (toList)
Line 753: Line 1,332:
putStrLn ("μ(n) for 1 ≤ n ≤ " ++ show n ++ ":\n") >>
putStrLn ("μ(n) for 1 ≤ n ≤ " ++ show n ++ ":\n") >>
putStrLn (showMoebiusBlock cols $ moebiusBlock n)
putStrLn (showMoebiusBlock cols $ moebiusBlock n)
_ -> hPutStrLn stderr $ "Usage: " ++ prog ++ " num-columns maximum-number"</lang>
_ -> hPutStrLn stderr $ "Usage: " ++ prog ++ " num-columns maximum-number"</syntaxhighlight>


{{out}}
{{out}}
Line 772: Line 1,351:


=={{header|J}}==
=={{header|J}}==
Implementation:
<syntaxhighlight lang="j">mu=: */@:-@~:@q:</syntaxhighlight>


Explanation: <code>q: n</code> gives the list of prime factors of n. (This is an empty list for the number 1, is <code>2 2 5 5</code> for the number 100, and is <code>2 2 2 3 5</code> for the number 120.)
Implementation:


In this context <code>~:</code> replaces each prime factor either by 1, if it is its first occurrence, or by 0, if it is a repetition (e.g. <code>2 2 5 5</code> → <code>1 0 1 0</code>). Then, <code>-</code> simply negates this list (e.g. <code>1 0 1 0</code> → <code>_1 0 _1 0</code>), and finally <code>*/</code> multiplies all list elements to get the desired result.
<lang J>mu=: ({{*/1-y>1}} * _1 ^ 2|+/)@q:~&_</lang>

Explanation: _ q: n gives the list of exponents of prime factors of n. (This is an empty list for the number 1, is 2 0 2 for the number 100 and is 3 1 1 for the number 120.)

In this context +/ is the sum of that list, 2 | +/ is 1 if the sum is odd and 0 if the sum is even. _1^0 is 1 and _1^1 is _1. And, {{*/1-y>1}} returns zero if any exponent is at least 2 in magnitude.


Task example:
Task example:
<syntaxhighlight lang="j"> mu >: i. 10 20

<lang J> mu 1+i.10 20
1 _1 _1 0 _1 1 _1 0 0 1 _1 0 _1 1 1 0 _1 0 _1 0
1 _1 _1 0 _1 1 _1 0 0 1 _1 0 _1 1 1 0 _1 0 _1 0
1 1 _1 0 0 1 0 0 _1 _1 _1 0 1 1 1 0 _1 1 1 0
1 1 _1 0 0 1 0 0 _1 _1 _1 0 1 1 1 0 _1 1 1 0
Line 793: Line 1,369:
1 1 1 0 1 1 0 0 _1 0 _1 0 0 _1 1 0 _1 1 1 0
1 1 1 0 1 1 0 0 _1 0 _1 0 0 _1 1 0 _1 1 1 0
1 0 _1 0 _1 1 _1 0 0 _1 0 0 _1 _1 0 0 1 1 _1 0
1 0 _1 0 _1 1 _1 0 0 _1 0 0 _1 _1 0 0 1 1 _1 0
_1 _1 1 0 1 _1 1 0 0 _1 _1 0 _1 1 _1 0 _1 0 _1 0</lang>
_1 _1 1 0 1 _1 1 0 0 _1 _1 0 _1 1 _1 0 _1 0 _1 0</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
<lang java>
<syntaxhighlight lang="java">
public class MöbiusFunction {
public class MöbiusFunction {


Line 856: Line 1,432:


}
}
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 880: Line 1,456:
====Using a Sieve====
====Using a Sieve====
'''Adapted from [[#C|C]]'''
'''Adapted from [[#C|C]]'''
<lang jq># Input: a non-negative integer, $n
<syntaxhighlight lang="jq"># Input: a non-negative integer, $n
# Output: an array of size $n + 1 such that the nth-mobius number is .[$n]
# Output: an array of size $n + 1 such that the nth-mobius number is .[$n]
# i.e. $n|mobius_array[-1]
# i.e. $n|mobius_array[-1]
Line 904: Line 1,480:


# For one-off computations:
# For one-off computations:
def mu($n): $n | mobius_array[-1];</lang>
def mu($n): $n | mobius_array[-1];</syntaxhighlight>
'''The Task'''
'''The Task'''
<lang jq>def nwise($n):
<syntaxhighlight lang="jq">def nwise($n):
def n: if length <= $n then . else .[0:$n] , (.[$n:] | n) end;
def n: if length <= $n then . else .[0:$n] , (.[$n:] | n) end;
n;
n;
Line 918: Line 1,494:
| join(" ") ) ;
| join(" ") ) ;


task</lang>
task</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 936: Line 1,512:
Note that the following solution to the task at hand (computing a range of Mobius numbers is inefficient as it does not cache the primes array.
Note that the following solution to the task at hand (computing a range of Mobius numbers is inefficient as it does not cache the primes array.
'''Preliminaries'''
'''Preliminaries'''
<lang jq># relatively_prime(previous) tests whether the input integer is prime
<syntaxhighlight lang="jq"># relatively_prime(previous) tests whether the input integer is prime
# relative to the primes in the array "previous":
# relative to the primes in the array "previous":
def relatively_prime(previous):
def relatively_prime(previous):
Line 989: Line 1,565:
else . as $in
else . as $in
| pf( [ primes( (1+$in) | sqrt | floor) ] )
| pf( [ primes( (1+$in) | sqrt | floor) ] )
end;</lang>
end;</syntaxhighlight>
'''Mu'''
'''Mu'''
<lang jq>def isSquareFree:
<syntaxhighlight lang="jq">def isSquareFree:
. as $n
. as $n
| 2
| 2
Line 1,011: Line 1,587:
else 0
else 0
end
end
end;</lang>
end;</syntaxhighlight>
'''The Task'''
'''The Task'''
<lang jq>def nwise($n):
<syntaxhighlight lang="jq">def nwise($n):
def n: if length <= $n then . else .[0:$n] , (.[$n:] | n) end;
def n: if length <= $n then . else .[0:$n] , (.[$n:] | n) end;
n;
n;
Line 1,024: Line 1,600:
| join(" ") ) ;
| join(" ") ) ;


task</lang>
task</syntaxhighlight>
{{out}}
{{out}}
As above.
As above.


=={{header|Julia}}==
=={{header|Julia}}==
<lang julia>using Primes
<syntaxhighlight lang="julia">using Primes


# modified from reinermartin's PR at https://github.com/JuliaMath/Primes.jl/pull/70/files
# modified from reinermartin's PR at https://github.com/JuliaMath/Primes.jl/pull/70/files
Line 1,043: Line 1,619:
print(lpad(μ(n), 3), n % 20 == 19 ? "\n" : "")
print(lpad(μ(n), 3), n % 20 == 19 ? "\n" : "")
end
end
</lang>{{out}}
</syntaxhighlight>{{out}}
<pre>
<pre>
First 199 terms of the Möbius sequence:
First 199 terms of the Möbius sequence:
Line 1,060: Line 1,636:
=={{header|Kotlin}}==
=={{header|Kotlin}}==
{{trans|Java}}
{{trans|Java}}
<lang scala>import kotlin.math.sqrt
<syntaxhighlight lang="scala">import kotlin.math.sqrt


fun main() {
fun main() {
Line 1,117: Line 1,693:
}
}
return MU!![n]
return MU!![n]
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>First 199 terms of the möbius function are as follows:
<pre>First 199 terms of the möbius function are as follows:
Line 1,133: Line 1,709:
=={{header|Lua}}==
=={{header|Lua}}==
{{trans|C}}
{{trans|C}}
<lang lua>function buildArray(size, value)
<syntaxhighlight lang="lua">function buildArray(size, value)
local tbl = {}
local tbl = {}
for i=1, size do
for i=1, size do
Line 1,177: Line 1,753:
print()
print()
end
end
end</lang>
end</syntaxhighlight>
{{out}}
{{out}}
<pre>First 199 terms of the mobius function are as follows:
<pre>First 199 terms of the mobius function are as follows:
Line 1,192: Line 1,768:


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<lang Mathematica>Grid[Partition[MoebiusMu[Range[99]], UpTo[10]]]</lang>
<syntaxhighlight lang="mathematica">Grid[Partition[MoebiusMu[Range[99]], UpTo[10]]]</syntaxhighlight>
{{out}}
{{out}}
<pre>1 -1 -1 0 -1 1 -1 0 0 1
<pre>1 -1 -1 0 -1 1 -1 0 0 1
Line 1,208: Line 1,784:
Uses the prime decomposition method from https://rosettacode.org/wiki/Prime_decomposition#Nim
Uses the prime decomposition method from https://rosettacode.org/wiki/Prime_decomposition#Nim


<lang Nim>import std/[math, sequtils, strformat]
<syntaxhighlight lang="nim">import std/[math, sequtils, strformat]


func getStep(n: int): int {.inline.} =
func getStep(n: int): int {.inline.} =
Line 1,261: Line 1,837:
if i mod 20 == 0:
if i mod 20 == 0:
echo "" # print newline
echo "" # print newline
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>The first 199 möbius numbers are:
<pre>The first 199 möbius numbers are:
Line 1,274: Line 1,850:
1 0 -1 0 -1 1 -1 0 0 -1 0 0 -1 -1 0 0 1 1 -1 0
1 0 -1 0 -1 1 -1 0 0 -1 0 0 -1 -1 0 0 1 1 -1 0
-1 -1 1 0 1 -1 1 0 0 -1 -1 0 -1 1 -1 0 -1 0 -1 0</pre>
-1 -1 1 0 1 -1 1 0 0 -1 -1 0 -1 1 -1 0 -1 0 -1 0</pre>


=={{header|PARI/GP}}==
{{trans|Julia}}
<syntaxhighlight lang="PARI/GP">
{
for(i = 1, 99,
print1(moebius(i) " ");
if(i % 10 == 0, print("\n"););
);
}
</syntaxhighlight>
{{out}}
<pre>
1 -1 -1 0 -1 1 -1 0 0 1

-1 0 -1 1 1 0 -1 0 -1 0

1 1 -1 0 0 1 0 0 -1 -1

-1 0 1 1 1 0 -1 1 1 0

-1 -1 -1 0 0 1 -1 0 0 0

1 0 -1 0 1 0 1 1 -1 0

-1 1 0 0 1 -1 -1 0 1 -1

-1 0 -1 1 0 0 1 -1 -1 0

0 1 -1 0 1 1 1 0 -1 0

1 0 1 1 1 0 -1 0 0
</pre>



=={{header|Pascal}}==
=={{header|Pascal}}==
Line 1,279: Line 1,890:


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>use utf8;
<syntaxhighlight lang="perl">use utf8;
use strict;
use strict;
use warnings;
use warnings;
Line 1,302: Line 1,913:


say "Möbius sequence - First $upto terms:\n" .
say "Möbius sequence - First $upto terms:\n" .
(' 'x4 . sprintf "@{['%4d' x $upto]}", @möebius) =~ s/((.){80})/$1\n/gr;</lang>
(' 'x4 . sprintf "@{['%4d' x $upto]}", @möebius) =~ s/((.){80})/$1\n/gr;</syntaxhighlight>
{{out}}
{{out}}
<pre>Möbius sequence - First 199 terms:
<pre>Möbius sequence - First 199 terms:
Line 1,317: Line 1,928:


=={{header|Phix}}==
=={{header|Phix}}==
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">Moebius</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">Moebius</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
Line 1,331: Line 1,942:
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">199</span> <span style="color: #008080;">do</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"%3d"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">Moebius</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)))</span> <span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">199</span> <span style="color: #008080;">do</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"%3d"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">Moebius</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)))</span> <span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">join_by</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">20</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" "</span><span style="color: #0000FF;">))</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">join_by</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">20</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" "</span><span style="color: #0000FF;">))</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 1,356: Line 1,967:


<lang python>
<syntaxhighlight lang="python">
# Python Program to evaluate
# Python Program to evaluate
# Mobius def M(N) = 1 if N = 1
# Mobius def M(N) = 1 if N = 1
Line 1,424: Line 2,035:
if i % 20 == 0: print()
if i % 20 == 0: print()
# This code is contributed by
# This code is contributed by
# Manish Shaw(manishshaw1)</lang>
# Manish Shaw(manishshaw1)</syntaxhighlight>
{{out}}
{{out}}
<pre>Mobius numbers from 1..99:
<pre>Mobius numbers from 1..99:
Line 1,435: Line 2,046:


The idea is based on efficient program to print all prime factors of a given number. The interesting thing is, we do not need inner while loop here because if a number divides more than once, we can immediately return 0.
The idea is based on efficient program to print all prime factors of a given number. The interesting thing is, we do not need inner while loop here because if a number divides more than once, we can immediately return 0.

# BUGS ! mu(1): computes -1, correct 1
# BUGS ! mu(2): computes 1, correct -1
# BUGS ! mu(105): computes 1, correct -1
# BUGS ! ...
# Some other programs say: "Translation of Python", probably of this one.
<lang Python># Python Program to evaluate
<syntaxhighlight lang="python"># Python Program to evaluate
# Mobius def M(N) = 1 if N = 1
# Mobius def M(N) = 1 if N = 1
# M(N) = 0 if any prime factor
# M(N) = 0 if any prime factor
Line 1,499: Line 2,116:
print(f"{mobius(i):>4}", end = '')
print(f"{mobius(i):>4}", end = '')
# This code is contributed by
# This code is contributed by
# Manish Shaw(manishshaw1)</lang>
# Manish Shaw(manishshaw1)</syntaxhighlight>
{{out}}
{{out}}
<pre>Mobius numbers from 1..99:
<pre>Mobius numbers from 1..99:
Line 1,507: Line 2,124:
-1 1 0 0 1 -1 -1 0 1 -1 -1 0 -1 1 0 0 1 -1 -1 0
-1 1 0 0 1 -1 -1 0 1 -1 -1 0 -1 1 0 0 1 -1 -1 0
0 1 -1 0 1 1 1 0 -1 0 1 0 1 1 1 0 -1 0 0</pre>
0 1 -1 0 1 1 1 0 -1 0 1 0 1 1 1 0 -1 0 0</pre>

=={{header|Quackery}}==

<code>primefactors</code> is defined at [[Prime decomposition#Quackery]].

<syntaxhighlight lang="Quackery"> [ false swap
behead swap
[ witheach
[ tuck != if
done
dip not
conclude ] ]
drop ] is square ( [ --> b )

[ 1 & ] is odd ( n --> b )

[ dup 1 = if done
primefactors
dup square iff
[ drop 0 ] done
size odd iff
-1 else 1 ] is mobius ( n --> n )

say "First 199 terms:" cr
say " "
199 times
[ i^ 1+ mobius
dup -1 > if sp
echo
i^ 1+ 20 mod
19 = iff cr
else [ sp sp ] ]</syntaxhighlight>

{{out}}

<pre>First 199 terms:
1 -1 -1 0 -1 1 -1 0 0 1 -1 0 -1 1 1 0 -1 0 -1
0 1 1 -1 0 0 1 0 0 -1 -1 -1 0 1 1 1 0 -1 1 1
0 -1 -1 -1 0 0 1 -1 0 0 0 1 0 -1 0 1 0 1 1 -1
0 -1 1 0 0 1 -1 -1 0 1 -1 -1 0 -1 1 0 0 1 -1 -1
0 0 1 -1 0 1 1 1 0 -1 0 1 0 1 1 1 0 -1 0 0
0 -1 -1 -1 0 -1 1 -1 0 -1 -1 1 0 -1 -1 1 0 0 1 1
0 0 1 1 0 0 0 -1 0 1 -1 -1 0 1 1 0 0 -1 -1 -1
0 1 1 1 0 1 1 0 0 -1 0 -1 0 0 -1 1 0 -1 1 1
0 1 0 -1 0 -1 1 -1 0 0 -1 0 0 -1 -1 0 0 1 1 -1
0 -1 -1 1 0 1 -1 1 0 0 -1 -1 0 -1 1 -1 0 -1 0 -1</pre>


=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)
{{works with|Rakudo|2019.11}}
{{works with|Rakudo|2022.12}}


Möbius number is not defined for n == 0. Raku arrays are indexed from 0 so store a blank value at position zero to keep n and μ(n) aligned.
Möbius number is not defined for n == 0. Raku arrays are indexed from 0 so store a blank value at position zero to keep n and μ(n) aligned.


<lang perl6>use Prime::Factor;
<syntaxhighlight lang="raku" line>use Prime::Factor;


sub μ (Int \n) {
sub μ (Int \n) {
return 0 if n %% 4 or n %% 9 or n %% 25 or n %% 49 or n %% 121;
return 0 if n %% (4|9|25|49|121);
my @p = prime-factors(n);
my @p = prime-factors(n);
+@p == +@p.unique ?? +@p %% 2 ?? 1 !! -1 !! 0
+@p == +@p.unique ?? +@p %% 2 ?? 1 !! -1 !! 0
}
}


my @möbius = lazy flat '', 1, (2..*).hyper.map: -> \n { μ(n) };
my @möbius = lazy flat '', 1, (2..*).hyper.map: &μ;


# The Task
# The Task
put "Möbius sequence - First 199 terms:\n",
put "Möbius sequence - First 199 terms:\n",
@möbius[^200]».fmt('%3s').batch(20).join: "\n";</lang>
@möbius[^200]».fmt('%3s').batch(20).join: "\n";</syntaxhighlight>
{{out}}
{{out}}
<pre>Möbius sequence - First 199 terms:
<pre>Möbius sequence - First 199 terms:
Line 1,551: Line 2,214:


The function to computer some prime numbers is a bit of an overkill, but the goal was to keep it general &nbsp;(in case of larger/higher ranges for a Möbius sequence).
The function to computer some prime numbers is a bit of an overkill, but the goal was to keep it general &nbsp;(in case of larger/higher ranges for a Möbius sequence).
<lang rexx>/*REXX pgm computes & shows a value grid of the Möbius function for a range of integers.*/
<syntaxhighlight lang="rexx">/*REXX pgm computes & shows a value grid of the Möbius function for a range of integers.*/
parse arg LO HI grp . /*obtain optional arguments from the CL*/
parse arg LO HI grp . /*obtain optional arguments from the CL*/
if LO=='' | LO=="," then LO= 0 /*Not specified? Then use the default.*/
if LO=='' | LO=="," then LO= 0 /*Not specified? Then use the default.*/
Line 1,596: Line 2,259:
end /*k*/ /* [↓] a prime (J) has been found. */
end /*k*/ /* [↓] a prime (J) has been found. */
nP= nP+1; if nP<=HI then @.nP= j /*bump prime count; assign prime to @.*/
nP= nP+1; if nP<=HI then @.nP= j /*bump prime count; assign prime to @.*/
end /*j*/; return</lang>
end /*j*/; return</syntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
{{out|output|text=&nbsp; when using the default inputs:}}


Line 1,616: Line 2,279:
=={{header|Ring}}==
=={{header|Ring}}==
{{Trans|FreeBASIC}}
{{Trans|FreeBASIC}}
<lang ring>
<syntaxhighlight lang="ring">
mobStr = " . "
mobStr = " . "


Line 1,647: Line 2,310:
next
next
return -1
return -1
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 1,671: Line 2,334:
-1 -1 0 -1 1 -1 0 -1 0 -1
-1 -1 0 -1 1 -1 0 -1 0 -1
</pre>
</pre>

=={{header|RPL}}==
{{trans|FreeBASIC}}
RPL does not allow that a function returns something whilst in the middle of a branch, so we have to play here with index saturation and flag use to mimic the short returns that many other languages accept.
{{works with|Halcyon Calc|4.2.7}}
{| class="wikitable"
! RPL code
! Comment
|-
|
'''IF''' DUP 1 ≠ '''THEN''' → n
≪ -1
2 n √ '''FOR''' d
'''IF''' n d MOD NOT '''THEN'''
1 CF '''IF''' n d SQ MOD NOT '''THEN'''
n 'd' STO DROP 0 1 SF '''END'''
'''IF''' 1 FC? '''THEN'''
DROP n d / n 'd' STO '''MU''' NEG '''END'''
'''END'''
'''NEXT'''
≫ '''END'''
≫ '<span style="color:blue">MU</span>' STO
|
<span style="color:blue">MU</span> ''( n -- µ(n) )''
if n = 1 then return 1
// default return value put in stack
for d as uinteger = 2 to int(sqr(n))
if n mod d = 0 then
if n mod (d*d) = 0 then
return 0 // and set flag
// if flag not set,
return -mobius(n/d)
end if
next d
|}

≪ 1 100 '''FOR''' li "" li DUP 19 + '''FOR''' j "-0+" j <span style="color:blue">MU</span> 2 + DUP SUB + '''NEXT''' 20 '''STEP''' ≫ EVAL

{{out}}
<pre>
5: "+--0-+-00+-0-++0-0-0"
4: "++-00+00---0+++0-++0"
3: "---00+-000+0-0+0++-0"
2: "-+00+--0+--0-+00+--0"
1: "0+-0+++0-0+0+++0-000"
</pre>
{{works with|HP|49/50}}
Improvement of an implementation found on the [https://www.hpmuseum.org/forum/thread-10330-post-93200.html#pid93200 MoHPC forum]
« '''CASE'''
DUP 1 ≤ '''THEN END'''
FACTOR DUP TYPE 9 ≠ '''THEN''' DROP -1 '''END'''
DUP →STR "^" POS '''THEN''' DROP 0 '''END'''
SIZE 1 + 2 / 1 SWAP 2 MOD { NEG } IFT
'''END'''
» '<span style="color:blue">MU</span>' STO
« 1 100 '''FOR''' j
j 20 MOD 1 == "" IFT
"-0+" j <span style="color:blue">MU</span> 2 + DUP SUB +
'''NEXT'''
» '<span style="color:blue">TASK</span>' STO
Same output.


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby>require 'prime'
<syntaxhighlight lang="ruby">require 'prime'


def μ(n)
def μ(n)
Line 1,683: Line 2,411:
([" "] + (1..199).map{|n|"%2s" % μ(n)}).each_slice(20){|line| puts line.join(" ") }
([" "] + (1..199).map{|n|"%2s" % μ(n)}).each_slice(20){|line| puts line.join(" ") }


</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,696: Line 2,424:
0 1 0 -1 0 -1 1 -1 0 0 -1 0 0 -1 -1 0 0 1 1 -1
0 1 0 -1 0 -1 1 -1 0 0 -1 0 0 -1 -1 0 0 1 1 -1
0 -1 -1 1 0 1 -1 1 0 0 -1 -1 0 -1 1 -1 0 -1 0 -1
0 -1 -1 1 0 1 -1 1 0 0 -1 -1 0 -1 1 -1 0 -1 0 -1
</pre>

=={{header|Rust}}==
<syntaxhighlight lang="rust">
fn moebius(mut x: u64) -> i8 {
let mut prime_count = 0;

// If x is divisible by the given factor this macro counts the factor and divides it out.
// It then returns zero if x is still divisible by the factor.
macro_rules! divide_x_by {
($factor:expr) => {
if x % $factor == 0 {
x /= $factor;
prime_count += 1;
if x % $factor == 0 {
return 0;
}
}
};
}

// Handle 2 and 3 separately,
divide_x_by!(2);
divide_x_by!(3);

// then use a wheel sieve to check the remaining factors <= √x.
for i in (5..=isqrt(x)).step_by(6) {
divide_x_by!(i);
divide_x_by!(i + 2);
}

// There can exist one prime factor larger than √x,
// in that case we can check if x is still larger than one, and then count it.
if x > 1 {
prime_count += 1;
}

if prime_count % 2 == 0 {
1
} else {
-1
}
}

/// Returns the largest integer smaller than or equal to `√n`
const fn isqrt(n: u64) -> u64 {
if n <= 1 {
n
} else {
let mut x0 = u64::pow(2, n.ilog2() / 2 + 1);
let mut x1 = (x0 + n / x0) / 2;
while x1 < x0 {
x0 = x1;
x1 = (x0 + n / x0) / 2;
}
x0
}
}

fn main() {
const ROWS: u64 = 10;
const COLS: u64 = 20;
println!(
"Values of the Möbius function, μ(x), for x between 0 and {}:",
COLS * ROWS
);
for i in 0..ROWS {
for j in 0..=COLS {
let x = COLS * i + j;
let μ = moebius(x);
if μ >= 0 {
// Print an extra space if there's no minus sign in front of the output
// in order to align the numbers in a nice grid.
print!(" ");
}
print!("{μ} ");
}
println!();
}
let x = u64::MAX;
println!("\nμ({x}) = {}", moebius(x));
}
</syntaxhighlight>
{{out}}
<pre>
Values of the Möbius function, μ(x), for x between 0 and 200:
0 1 -1 -1 0 -1 1 -1 0 0 1 -1 0 -1 1 1 0 -1 0 -1 0
0 1 1 -1 0 0 1 0 0 -1 -1 -1 0 1 1 1 0 -1 1 1 0
0 -1 -1 -1 0 0 1 -1 0 0 0 1 0 -1 0 1 0 1 1 -1 0
0 -1 1 0 0 1 -1 -1 0 1 -1 -1 0 -1 1 0 0 1 -1 -1 0
0 0 1 -1 0 1 1 1 0 -1 0 1 0 1 1 1 0 -1 0 0 0
0 -1 -1 -1 0 -1 1 -1 0 -1 -1 1 0 -1 -1 1 0 0 1 1 0
0 0 1 1 0 0 0 -1 0 1 -1 -1 0 1 1 0 0 -1 -1 -1 0
0 1 1 1 0 1 1 0 0 -1 0 -1 0 0 -1 1 0 -1 1 1 0
0 1 0 -1 0 -1 1 -1 0 0 -1 0 0 -1 -1 0 0 1 1 -1 0
0 -1 -1 1 0 1 -1 1 0 0 -1 -1 0 -1 1 -1 0 -1 0 -1 0

μ(18446744073709551615) = -1
</pre>
</pre>


Line 1,701: Line 2,527:
Built-in:
Built-in:


<lang ruby>say moebius(53) #=> -1
<syntaxhighlight lang="ruby">say moebius(53) #=> -1
say moebius(54) #=> 0
say moebius(54) #=> 0
say moebius(55) #=> 1</lang>
say moebius(55) #=> 1</syntaxhighlight>


Simple implementation:
Simple implementation:
<lang ruby>func μ(n) {
<syntaxhighlight lang="ruby">func μ(n) {
var f = n.factor_exp.map { .tail }
var f = n.factor_exp.map { .tail }
f.any { _ > 1 } ? 0 : ((-1)**f.sum)
f.any { _ > 1 } ? 0 : ((-1)**f.sum)
Line 1,716: Line 2,542:
say line.map { '%2s' % _ }.join(' ')
say line.map { '%2s' % _ }.join(' ')
})
})
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,731: Line 2,557:
0 -1 -1 1 0 1 -1 1 0 0 -1 -1 0 -1 1 -1 0 -1 0 -1
0 -1 -1 1 0 1 -1 1 0 0 -1 -1 0 -1 1 -1 0 -1 0 -1
</pre>
</pre>

=={{header|Tiny BASIC}}==
Tiny BASIC is not suited for printing tables, so this is limited to prompting for a single number and calculating its Mobius number.

<lang tinybasic> PRINT "Enter an integer"
INPUT N
IF N < 0 THEN LET N = -N
IF N < 2 THEN GOTO 100 + N
LET C = 1
LET F = 2
10 IF ((N/F)/F)*F*F = N THEN GOTO 100
IF (N/F)*F = N THEN GOTO 30
20 LET F = F + 1
IF F<=N THEN GOTO 10
GOTO 100 + C
30 LET N = N / F
LET C = -C
GOTO 20
99 PRINT "-1"
END
100 PRINT "0"
END
101 PRINT "1"
END</lang>


=={{header|Wren}}==
=={{header|Wren}}==
{{libheader|Wren-fmt}}
{{libheader|Wren-fmt}}
{{libheader|Wren-math}}
{{libheader|Wren-math}}
<lang ecmascript>import "/fmt" for Fmt
<syntaxhighlight lang="wren">import "./fmt" for Fmt
import "/math" for Int
import "./math" for Int


var isSquareFree = Fn.new { |n|
var isSquareFree = Fn.new { |n|
Line 1,787: Line 2,589:
System.write(" ")
System.write(" ")
} else {
} else {
System.write("%(Fmt.dm(3, mu.call(i*20 + j))) ")
Fmt.write("$ 3d ", mu.call(i*20 + j))
}
}
}
}
System.print()
System.print()
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,809: Line 2,611:


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>func Mobius(N);
<syntaxhighlight lang="xpl0">func Mobius(N);
int N, Cnt, F, K;
int N, Cnt, F, K;
[Cnt:= 0;
[Cnt:= 0;
Line 1,831: Line 2,633:
if rem(N/20) = 19 then CrLf(0);
if rem(N/20) = 19 then CrLf(0);
];
];
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 1,846: Line 2,648:
0 -1 -1 1 0 1 -1 1 0 0 -1 -1 0 -1 1 -1 0 -1 0 -1
0 -1 -1 1 0 1 -1 1 0 0 -1 -1 0 -1 1 -1 0 -1 0 -1
</pre>
</pre>

=={{header|Yabasic}}==
{{trans|FreeBASIC}}
<lang yabasic>outstr$ = " . "
for i = 1 to 200
if mobius(i) >= 0 then outstr$ = outstr$ + " " : fi
outstr$ = outstr$ + str$(mobius(i)) + " "
if mod(i, 10) = 9 then
print outstr$
outstr$ = ""
end if
next i
end

sub mobius(n)
if n = 1 then return 1 : fi
for d = 2 to int(sqr(n))
if mod(n, d) = 0 then
if mod(n, (d*d)) = 0 then return 0 : fi
return -mobius(n/d)
end if
next d
return -1
end sub</lang>


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>fcn mobius(n){
<syntaxhighlight lang="zkl">fcn mobius(n){
pf:=primeFactors(n);
pf:=primeFactors(n);
sq:=pf.filter1('wrap(f){ (n % (f*f))==0 }); // False if square free
sq:=pf.filter1('wrap(f){ (n % (f*f))==0 }); // False if square free
Line 1,890: Line 2,668:
if(n!=m) acc.append(n/m); // opps, missed last factor
if(n!=m) acc.append(n/m); // opps, missed last factor
else acc;
else acc;
}</lang>
}</syntaxhighlight>
<lang zkl>[1..199].apply(mobius)
<syntaxhighlight lang="zkl">[1..199].apply(mobius)
.pump(Console.println, T(Void.Read,19,False),
.pump(Console.println, T(Void.Read,19,False),
fcn{ vm.arglist.pump(String,"%3d".fmt) });</lang>
fcn{ vm.arglist.pump(String,"%3d".fmt) });</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>

Latest revision as of 22:43, 3 May 2024

Task
Möbius function
You are encouraged to solve this task according to the task description, using any language you may know.

The classical Möbius function: μ(n) is an important multiplicative function in number theory and combinatorics.

There are several ways to implement a Möbius function.

A fairly straightforward method is to find the prime factors of a positive integer n, then define μ(n) based on the sum of the primitive factors. It has the values {−1, 0, 1} depending on the factorization of n:

  • μ(1) is defined to be 1.
  • μ(n) = 1 if n is a square-free positive integer with an even number of prime factors.
  • μ(n) = −1 if n is a square-free positive integer with an odd number of prime factors.
  • μ(n) = 0 if n has a squared prime factor.


Task
  • Write a routine (function, procedure, whatever) μ(n) to find the Möbius number for a positive integer n.
  • Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.)


See also


Related Tasks



11l

Translation of: Python
F isPrime(n)
   I n < 2
      R 0B
   L(i) 2 .. n
      I i * i <= n & n % i == 0
         R 0B
   R 1B

F mobius(n)
   I n == 1
      R 1

   V p = 0
   L(i) 1 .. n
      I n % i == 0 & isPrime(i)
         I n % (i * i) == 0
            R 0
         E
            p = p + 1

   I p % 2 != 0
      R -1
   E
      R 1

print(‘Mobius numbers from 1..99:’)

L(i) 1..99
   print(f:‘{mobius(i):4}’, end' ‘’)

   I i % 20 == 0
      print()
Output:
Mobius numbers from 1..99:
   1  -1  -1   0  -1   1  -1   0   0   1  -1   0  -1   1   1   0  -1   0  -1   0
   1   1  -1   0   0   1   0   0  -1  -1  -1   0   1   1   1   0  -1   1   1   0
  -1  -1  -1   0   0   1  -1   0   0   0   1   0  -1   0   1   0   1   1  -1   0
  -1   1   0   0   1  -1  -1   0   1  -1  -1   0  -1   1   0   0   1  -1  -1   0
   0   1  -1   0   1   1   1   0  -1   0   1   0   1   1   1   0  -1   0   0

ALGOL 68

Translation of: C
BEGIN
    # show the first 199 values of the moebius function                 #
    INT sq root = 1 000;
    INT mu max  = sq root * sq root;
    [ 1 : mu max ]INT mu;
    FOR i FROM LWB mu TO UPB mu DO mu[ i ] := 1 OD;
    FOR i FROM 2 TO sq root DO
        IF mu[ i ] = 1 THEN
            # for each factor found, swap + and -                       #
            FOR j FROM i     BY i     TO UPB mu DO mu[ j ] *:= -i OD;
            FOR j FROM i * i BY i * i TO UPB mu DO mu[ j ]  :=  0 OD
        FI
    OD;
    FOR i FROM 2 TO UPB mu DO
        IF   mu[ i ] =  i THEN mu[ i ] :=  1
        ELIF mu[ i ] = -i THEN mu[ i ] := -1
        ELIF mu[ i ] <  0 THEN mu[ i ] :=  1
        ELIF mu[ i ] >  0 THEN mu[ i ] := -1
      # ELSE mu[ i ] =  0 so no change #
        FI
    OD;
    print( ( "First 199 terms of the möbius function are as follows:", newline, "    " ) );
    FOR i TO 199 DO
        print( ( whole( mu[ i ], -4 ) ) );
        IF ( i + 1 ) MOD 20 = 0 THEN print( ( newline ) ) FI
    OD
END
Output:
First 199 terms of the möbius function are as follows:
       1  -1  -1   0  -1   1  -1   0   0   1  -1   0  -1   1   1   0  -1   0  -1
   0   1   1  -1   0   0   1   0   0  -1  -1  -1   0   1   1   1   0  -1   1   1
   0  -1  -1  -1   0   0   1  -1   0   0   0   1   0  -1   0   1   0   1   1  -1
   0  -1   1   0   0   1  -1  -1   0   1  -1  -1   0  -1   1   0   0   1  -1  -1
   0   0   1  -1   0   1   1   1   0  -1   0   1   0   1   1   1   0  -1   0   0
   0  -1  -1  -1   0  -1   1  -1   0  -1  -1   1   0  -1  -1   1   0   0   1   1
   0   0   1   1   0   0   0  -1   0   1  -1  -1   0   1   1   0   0  -1  -1  -1
   0   1   1   1   0   1   1   0   0  -1   0  -1   0   0  -1   1   0  -1   1   1
   0   1   0  -1   0  -1   1  -1   0   0  -1   0   0  -1  -1   0   0   1   1  -1
   0  -1  -1   1   0   1  -1   1   0   0  -1  -1   0  -1   1  -1   0  -1   0  -1

Amazing Hopper

Translation of: Python
#include <basico.h>

#proto cálculodeMobius(_X_)
#synon _cálculodeMobius    calcularMobius

algoritmo
   
   imprimir ("Mobius numbers from 1..199\n")
   i=0, s=1
   iterar grupo( ++i, #(i<=199), calcular Mobius (i), \
        solo si (#( iszero(s%20) ), NL;s=0 ), imprimir, ++s )
   saltar
terminar

subrutinas

cálculo de Mobius (n)
   si( #(n==0) )     ; tomar '"   "'
   sino si( #(n==1) ); tomar '"  1"'
   sino; p=0
         iterar para (i=1, #(i<=n+1), ++i)
            si ( #( iszero(n%i) && isprime(i)) )
               cuando ( #( iszero(n%(i*i)) ) ){
                  tomar '"  0"'; ir a (herejía)  /* ¡! */
               } ++p
            fin si
         siguiente
         tomar si ( es impar(p), " -1", "  1" )
   fin si

/* ¡Dios! ¡Purifica esta mierda! ----+ */
           /*                        | */
herejía:   /* <----------------------+ */
   retornar
Output:
Mobius numbers from 1..199
     1 -1 -1  0 -1  1 -1  0  0  1 -1  0 -1  1  1  0 -1  0 -1
  0  1  1 -1  0  0  1  0  0 -1 -1 -1  0  1  1  1  0 -1  1  1
  0 -1 -1 -1  0  0  1 -1  0  0  0  1  0 -1  0  1  0  1  1 -1
  0 -1  1  0  0  1 -1 -1  0  1 -1 -1  0 -1  1  0  0  1 -1 -1
  0  0  1 -1  0  1  1  1  0 -1  0  1  0  1  1  1  0 -1  0  0
  0 -1 -1 -1  0 -1  1 -1  0 -1 -1  1  0 -1 -1  1  0  0  1  1
  0  0  1  1  0  0  0 -1  0  1 -1 -1  0  1  1  0  0 -1 -1 -1
  0  1  1  1  0  1  1  0  0 -1  0 -1  0  0 -1  1  0 -1  1  1
  0  1  0 -1  0 -1  1 -1  0  0 -1  0  0 -1 -1  0  0  1  1 -1
  0 -1 -1  1  0  1 -1  1  0  0 -1 -1  0 -1  1 -1  0 -1  0 -1

Arturo

mobius: function [n][
    if n=0 -> return ""
    if n=1 -> return 1
    f: factors.prime n

    if f <> unique f -> return 0
    if? odd? size f -> return neg 1
    else -> return 1
]

loop split.every:20 map 0..199 => mobius 'a ->
    print map a => [pad to :string & 3]
Output:
      1  -1  -1   0  -1   1  -1   0   0   1  -1   0  -1   1   1   0  -1   0  -1 
  0   1   1  -1   0   0   1   0   0  -1  -1  -1   0   1   1   1   0  -1   1   1 
  0  -1  -1  -1   0   0   1  -1   0   0   0   1   0  -1   0   1   0   1   1  -1 
  0  -1   1   0   0   1  -1  -1   0   1  -1  -1   0  -1   1   0   0   1  -1  -1 
  0   0   1  -1   0   1   1   1   0  -1   0   1   0   1   1   1   0  -1   0   0 
  0  -1  -1  -1   0  -1   1  -1   0  -1  -1   1   0  -1  -1   1   0   0   1   1 
  0   0   1   1   0   0   0  -1   0   1  -1  -1   0   1   1   0   0  -1  -1  -1 
  0   1   1   1   0   1   1   0   0  -1   0  -1   0   0  -1   1   0  -1   1   1 
  0   1   0  -1   0  -1   1  -1   0   0  -1   0   0  -1  -1   0   0   1   1  -1 
  0  -1  -1   1   0   1  -1   1   0   0  -1  -1   0  -1   1  -1   0  -1   0  -1

AutoHotkey

loop 100
    result .= SubStr("  " Möbius(A_Index), -1) . (Mod(A_Index, 10) ? "  " : "`n")
MsgBox, 262144, , % result
return

Möbius(n){
    if n=1
        return 1
    x := prime_factors(n)
    c := x.Count()
    sq := []
    for i, v in x
        if sq[v]
            return 0
        else
            sq[v] := 1
    return (c/2 = floor(c/2)) ? 1 : -1
}

prime_factors(n) {
    if (n <= 3)
        return [n]
    ans := [], done := false
    while !done {
        if !Mod(n, 2)
            ans.push(2), n /= 2
        else if !Mod(n, 3)
            ans.push(3), n /= 3
        else if (n = 1)
            return ans
        else {
            sr := sqrt(n), done := true, i := 6
            while (i <= sr+6) {
                if !Mod(n, i-1) { ; is n divisible by i-1?
                    ans.push(i-1), n /= i-1, done := false
                    break
                }
                if !Mod(n, i+1) { ; is n divisible by i+1?
                    ans.push(i+1), n /= i+1, done := false
                    break
                }
                i += 6
    }}}
    ans.push(Format("{:d}", n))
    return ans
}
Output:
 1  -1  -1   0  -1   1  -1   0   0   1
-1   0  -1   1   1   0  -1   0  -1   0
 1   1  -1   0   0   1   0   0  -1  -1
-1   0   1   1   1   0  -1   1   1   0
-1  -1  -1   0   0   1  -1   0   0   0
 1   0  -1   0   1   0   1   1  -1   0
-1   1   0   0   1  -1  -1   0   1  -1
-1   0  -1   1   0   0   1  -1  -1   0
 0   1  -1   0   1   1   1   0  -1   0
 1   0   1   1   1   0  -1   0   0   0

AWK

# syntax: GAWK -f MOBIUS_FUNCTION.AWK
# converted from Java
BEGIN {
    printf("first 199 terms of the mobius sequence:\n   ")
    for (n=1; n<200; n++) {
      printf("%3d",mobius(n))
      if ((n+1) % 20 == 0) {
        printf("\n")
      }
    }
    exit(0)
}
function mobius(n,  i,j,mu_max) {
    if (n in MU) {
      return(MU[n])
    }
    mu_max = 1000000
    for (i=0; i<mu_max; i++) { # populate array
      MU[i] = 1
    }
    for (i=2; i<=int(sqrt(mu_max)); i++ ) {
      if (MU[i] == 1) {
        for (j=i; j<=mu_max; j+=i) { # for each factor found, swap + and -
          MU[j] *= -i
        }
        for (j=i*i; j<=mu_max; j+=i*i) { # square factor = 0
          MU[j] = 0
        }
      }
    }
    for (i=2; i<=mu_max; i++) {
      if (MU[i] == i) {
        MU[i] = 1
      }
      else if (MU[i] == -i) {
        MU[i] = -1
      }
      else if (MU[i] < 0) {
        MU[i] = 1
      }
      else if (MU[i] > 0) {
        MU[i] = -1
      }
    }
    return(MU[n])
}
Output:
first 199 terms of the mobius sequence:
     1 -1 -1  0 -1  1 -1  0  0  1 -1  0 -1  1  1  0 -1  0 -1
  0  1  1 -1  0  0  1  0  0 -1 -1 -1  0  1  1  1  0 -1  1  1
  0 -1 -1 -1  0  0  1 -1  0  0  0  1  0 -1  0  1  0  1  1 -1
  0 -1  1  0  0  1 -1 -1  0  1 -1 -1  0 -1  1  0  0  1 -1 -1
  0  0  1 -1  0  1  1  1  0 -1  0  1  0  1  1  1  0 -1  0  0
  0 -1 -1 -1  0 -1  1 -1  0 -1 -1  1  0 -1 -1  1  0  0  1  1
  0  0  1  1  0  0  0 -1  0  1 -1 -1  0  1  1  0  0 -1 -1 -1
  0  1  1  1  0  1  1  0  0 -1  0 -1  0  0 -1  1  0 -1  1  1
  0  1  0 -1  0 -1  1 -1  0  0 -1  0  0 -1 -1  0  0  1  1 -1
  0 -1 -1  1  0  1 -1  1  0  0 -1 -1  0 -1  1 -1  0 -1  0 -1

BASIC

Applesoft BASIC

10 HOME
20 FOR t = 0 TO 9
30 FOR u = 1 TO 10
40   n = 10*t+u
50   GOSUB 130
60   IF STR$(m) = "0" THEN PRINT "  0";
70   IF STR$(m) = "1" THEN PRINT "  1";
80   IF STR$(m) = "-1" THEN PRINT " -1";
90 NEXT u
100 PRINT
110 NEXT t
120 END
130 IF n = 1 THEN m = 1 : RETURN
140 m = 1 : f = 2
150 IF (n-INT(n/(f*f))*(f*f)) = 0 THEN m = 0 : RETURN
160 IF (n-INT(n/(f))*(f)) = 0 THEN GOSUB 200
170 f = f+1
180 IF f <= n THEN GOTO 150
190 RETURN
200 m = -m
210 n = n/f
220 RETURN
230 END
Output:
Same as GW-BASIC entry.

BASIC256

Translation of: FreeBASIC
function mobius(n)
	if n = 1 then return 1
	for d = 2 to int(sqr(n))
		if n mod d = 0 then
			if n mod (d*d) = 0 then return 0
			return -mobius(n/d)
		end if
	next d
	return -1
end function

outstr$ = " .   "
for i = 1 to 200
	if mobius(i) >= 0 then outstr$ += " "
	outstr$ += string(mobius(i)) + "   "
	if i mod 10 = 9 then
		print outstr$
		outstr$ = ""
	end if
next i
end
Output:
Igual que la entrada de FreeBASIC.

Chipmunk Basic

Works with: Chipmunk Basic version 3.6.4
Works with: GW-BASIC
Works with: QBasic
Translation of: GW-BASIC
10 CLS
20 FOR t = 0 TO 9
30 FOR u = 1 TO 10
40   n = 10 * t + u
50   GOSUB 110
60   PRINT USING "##  "; m;
70   NEXT u
80   PRINT
90 NEXT t
100 END
110 IF n = 1 THEN m = 1: RETURN
120 m = 1: f = 2
130 IF n MOD (f * f) = 0 THEN m = 0: RETURN
140 IF n MOD f = 0 THEN GOSUB 180
150 f = f + 1
160 IF f <= n THEN GOTO 130
170 RETURN
180 m = -m
190 n = n / f
200 RETURN
210 END
Output:
Same as GW-BASIC entry.

FreeBASIC

function mobius( n as uinteger ) as integer
    if n = 1 then return 1
    for d as uinteger = 2 to int(sqr(n))
        if n mod d = 0 then 
            if n mod (d*d) = 0 then return 0
            return -mobius(n/d)
        end if
    next d
    return -1
end function

dim as string outstr = " .     "
for i as uinteger = 1 to 200
    if mobius(i)>=0 then outstr += " "
    outstr += str(mobius(i))+"     "
    if i mod 10 = 9 then 
        print outstr
        outstr = ""
    end if
next i
Output:
 .      1     -1     -1      0     -1      1     -1      0      0     
 1     -1      0     -1      1      1      0     -1      0     -1     
 0      1      1     -1      0      0      1      0      0     -1     
-1     -1      0      1      1      1      0     -1      1      1     
 0     -1     -1     -1      0      0      1     -1      0      0     
 0      1      0     -1      0      1      0      1      1     -1     
 0     -1      1      0      0      1     -1     -1      0      1     
-1     -1      0     -1      1      0      0      1     -1     -1     
 0      0      1     -1      0      1      1      1      0     -1     
 0      1      0      1      1      1      0     -1      0      0     
 0     -1     -1     -1      0     -1      1     -1      0     -1     
-1      1      0     -1     -1      1      0      0      1      1     
 0      0      1      1      0      0      0     -1      0      1     
-1     -1      0      1      1      0      0     -1     -1     -1     
 0      1      1      1      0      1      1      0      0     -1     
 0     -1      0      0     -1      1      0     -1      1      1     
 0      1      0     -1      0     -1      1     -1      0      0     
-1      0      0     -1     -1      0      0      1      1     -1     
 0     -1     -1      1      0      1     -1      1      0      0     
-1     -1      0     -1      1     -1      0     -1      0     -1

FutureBasic

local fn IsPrime( n as long ) as BOOL
  BOOL result = YES
  long i
  
  if ( n < 2 ) then result = NO : exit fn  
  for i = 2 to n + 1
    if ( i * i <= n ) and ( n mod i == 0 )
      result = NO : exit fn
    end if
  next
end fn = result

local fn Mobius( n as long ) as long
  long i, p = 0, result = 0
  
  if ( n == 1 ) then result = 1 : exit fn
  for i = 1 to n + 1
    if ( n mod i == 0 ) and ( fn IsPrime( i ) == YES )
      if ( n mod ( i * i ) == 0 )
        result = 0 : exit fn
      else
        p++
      end if
    end if
  next
  if( p mod 2 != 0 )
    result = -1
  else
    result = 1
  end if
end fn = result

window 1, @"Möbius function", (0,0,600,300)

printf @"First 100 terms of Mobius sequence:"

long i
for i = 1 to 100
  printf @"%2ld\t", fn Mobius(i)
  if ( i mod 20 == 0 ) then print
next

HandleEvents
Output:
First 100 terms of Mobius sequence:
   1  -1  -1   0  -1   1  -1   0   0   1  -1   0  -1   1   1   0  -1   0  -1   0
   1   1  -1   0   0   1   0   0  -1  -1  -1   0   1   1   1   0  -1   1   1   0
  -1  -1  -1   0   0   1  -1   0   0   0   1   0  -1   0   1   0   1   1  -1   0
  -1   1   0   0   1  -1  -1   0   1  -1  -1   0  -1   1   0   0   1  -1  -1   0
   0   1  -1   0   1   1   1   0  -1   0   1   0   1   1   1   0  -1   0   0   0

Gambas

Translation of: FreeBASIC
Works with: Windows
Public Sub Main()  
  
  Dim outstr As String = " .     " 

  For i As Integer = 1 To 200 
    If mobius(i) >= 0 Then outstr &= " " 
    outstr &= Str(mobius(i)) & "     " 
    If i Mod 10 = 9 Then  
      Print outstr 
      outstr = "" 
    End If 
  Next
  
End

Function mobius(n As Integer) As Integer 

  If n = 1 Then Return 1 
  For d As Integer = 2 To Int(Sqr(n)) 
    If n Mod d = 0 Then  
      If n Mod (d * d) = 0 Then Return 0 
      Return -mobius(n / d) 
    End If 
  Next 
  Return -1 

End Function
Output:
Same as FreeBASIC entry.

GW-BASIC

Works with: BASICA
10 FOR T = 0 TO 9
20 FOR U = 1 TO 10
30 N = 10*T + U
40 GOSUB 100
50 PRINT USING "##  ";M;
60 NEXT U
70 PRINT
80 NEXT T
90 END
100 IF N = 1 THEN M = 1 : RETURN
110 M = 1 : F = 2
120 IF N MOD (F*F) = 0 THEN M = 0 : RETURN
130 IF N MOD F = 0 THEN GOSUB 170
140 F = F + 1
150 IF F <= N THEN GOTO 120
160 RETURN
170 M = -M
180 N = N/F
190 RETURN
Output:
 1  -1  -1   0  -1   1  -1   0   0   1
-1   0  -1   1   1   0  -1   0  -1   0
 1   1  -1   0   0   1   0   0  -1  -1
-1   0   1   1   1   0  -1   1   1   0
-1  -1  -1   0   0   1  -1   0   0   0
 1   0  -1   0   1   0   1   1  -1   0
-1   1   0   0   1  -1  -1   0   1  -1
-1   0  -1   1   0   0   1  -1  -1   0
 0   1  -1   0   1   1   1   0  -1   0
 1   0   1   1   1   0  -1   0   0   0

Minimal BASIC

Translation of: GW-BASIC
Works with: Applesoft BASIC
Works with: Chipmunk Basic version 3.6.4
Works with: Commodore BASIC version 3.5
Works with: Nascom ROM BASIC version 4.7
10 REM Moebius function
20 FOR T = 0 TO 9
30 FOR U = 1 TO 10
40 LET N = 10*T+U
50 GOSUB 110
60 PRINT M;" ";
70 NEXT U
80 PRINT
90 NEXT T
100 END

110 LET M = 1
120 IF N = 1 THEN 230
130 LET F = 2
140 LET F2 = F*F
150 IF INT(N/F2)*F2 <> N THEN 180
160 LET M = 0
170 GOTO 230
180 IF INT(N/F)*F <> N THEN 210
190 LET M = -M
200 LET N = N/F
210 LET F = F+1
220 IF F <= N THEN 140
230 RETURN

MSX Basic

Works with: MSX BASIC version any

The GW-BASIC solution works without any changes.

PureBasic

Translation of: FreeBASIC
Procedure.i mobius(n)
  If n = 1: 
    ProcedureReturn 1
  EndIf
  For d = 2 To Int(Sqr(n))
    If Mod(n, d) = 0:
      If Mod(n, d * d) = 0:
        ProcedureReturn 0
      EndIf
      ProcedureReturn -mobius(n / d)
    EndIf
  Next d
  ProcedureReturn -1
EndProcedure

OpenConsole()
outstr$ = " .   "
For i = 1 To 200
  If mobius(i) >= 0:
    outstr$ = outstr$ + " "
  EndIf
  outstr$ = outstr$ + Str(mobius(i)) + "   "
  If Mod(i, 10) = 9:
    PrintN(outstr$)
    outstr$ = ""
  EndIf
Next i

PrintN(#CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
Output:
Same as FreeBASIC entry.

Tiny BASIC

Tiny BASIC is not suited for printing tables, so this is limited to prompting for a single number and calculating its Mobius number.

    PRINT "Enter an integer"
    INPUT N
    IF N < 0 THEN LET N = -N
    IF N < 2 THEN GOTO 100 + N
    LET C = 1
    LET F = 2
 10 IF ((N/F)/F)*F*F = N THEN GOTO 100
    IF (N/F)*F = N THEN GOTO 30
 20 LET F = F + 1
    IF F<=N THEN GOTO 10
    GOTO 100 + C
 30 LET N = N / F
    LET C = -C
    GOTO 20
 99 PRINT "-1"
    END
100 PRINT "0"
    END
101 PRINT "1"
    END

XBasic

Works with: Windows XBasic
Translation of: FreeBASIC
PROGRAM	"Möbius function"
VERSION	"0.0000"
IMPORT	"xma"


DECLARE FUNCTION Entry ()
DECLARE FUNCTION mobius (n)

FUNCTION Entry ()
    outstr$ = "  .  "
    FOR i = 1 TO 200
        IF mobius(i) >= 0 THEN outstr$ = outstr$
        outstr$ = outstr$ + STR$(mobius(i)) + "   "
        IF i MOD 10 = 9 THEN
            PRINT outstr$
            outstr$ = ""
        END IF
    NEXT i
END FUNCTION

FUNCTION mobius (n)
	IF n = 1 THEN RETURN 1
	FOR d = 2 TO INT(SQRT(n))
		IF n MOD d = 0 THEN
			IF n MOD (d*d) = 0 THEN RETURN 0
			RETURN -mobius(n/d)
		END IF
	NEXT d
	RETURN -1
END FUNCTION
END PROGRAM
Output:
Same as FreeBASIC entry.

Yabasic

Translation of: FreeBASIC
outstr$ = " .  "
for i = 1 to 200
    if mobius(i) >= 0 then outstr$ = outstr$ + " " : fi
    outstr$ = outstr$ + str$(mobius(i)) + "  "
    if mod(i, 10) = 9 then 
        print outstr$
        outstr$ = ""
    end if
next i
end

sub mobius(n)
    if n = 1 then return 1 : fi
    for d = 2 to int(sqr(n))
        if mod(n, d) = 0 then 
            if mod(n, (d*d)) = 0 then return 0 : fi
            return -mobius(n/d)
        end if
    next d
    return -1
end sub

C

Translation of: Java
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
    const int MU_MAX = 1000000;
    int i, j;
    int *mu;
    int sqroot;

    sqroot = (int)sqrt(MU_MAX);

    mu = malloc((MU_MAX + 1) * sizeof(int));

    for (i = 0; i < MU_MAX;i++) {
        mu[i] = 1;
    }

    for (i = 2; i <= sqroot; i++) {
        if (mu[i] == 1) {
            // for each factor found, swap + and -
            for (j = i; j <= MU_MAX; j += i) {
                mu[j] *= -i;
            }
            // square factor = 0
            for (j = i * i; j <= MU_MAX; j += i * i) {
                mu[j] = 0;
            }
        }
    }

    for (i = 2; i <= MU_MAX; i++) {
        if (mu[i] == i) {
            mu[i] = 1;
        } else if (mu[i] == -i) {
            mu[i] = -1;
        } else if (mu[i] < 0) {
            mu[i] = 1;
        } else if (mu[i] > 0) {
            mu[i] = -1;
        }
    }

    printf("First 199 terms of the möbius function are as follows:\n    ");
    for (i = 1; i < 200; i++) {
        printf("%2d  ", mu[i]);
        if ((i + 1) % 20 == 0) {
            printf("\n");
        }
    }

    free(mu);
    return 0;
}
Output:
First 199 terms of the m÷bius function are as follows:
     1  -1  -1   0  -1   1  -1   0   0   1  -1   0  -1   1   1   0  -1   0  -1
 0   1   1  -1   0   0   1   0   0  -1  -1  -1   0   1   1   1   0  -1   1   1
 0  -1  -1  -1   0   0   1  -1   0   0   0   1   0  -1   0   1   0   1   1  -1
 0  -1   1   0   0   1  -1  -1   0   1  -1  -1   0  -1   1   0   0   1  -1  -1
 0   0   1  -1   0   1   1   1   0  -1   0   1   0   1   1   1   0  -1   0   0
 0  -1  -1  -1   0  -1   1  -1   0  -1  -1   1   0  -1  -1   1   0   0   1   1
 0   0   1   1   0   0   0  -1   0   1  -1  -1   0   1   1   0   0  -1  -1  -1
 0   1   1   1   0   1   1   0   0  -1   0  -1   0   0  -1   1   0  -1   1   1
 0   1   0  -1   0  -1   1  -1   0   0  -1   0   0  -1  -1   0   0   1   1  -1
 0  -1  -1   1   0   1  -1   1   0   0  -1  -1   0  -1   1  -1   0  -1   0  -1

C++

Translation of: Java
#include <iomanip>
#include <iostream>
#include <vector>

constexpr int MU_MAX = 1'000'000;
std::vector<int> MU;

int mobiusFunction(int n) {
    if (!MU.empty()) {
        return MU[n];
    }

    // Populate array
    MU.resize(MU_MAX + 1, 1);
    int root = sqrt(MU_MAX);

    for (int i = 2; i <= root; i++) {
        if (MU[i] == 1) {
            // for each factor found, swap + and -
            for (int j = i; j <= MU_MAX; j += i) {
                MU[j] *= -i;
            }
            // square factor = 0
            for (int j = i * i; j <= MU_MAX; j += i * i) {
                MU[j] = 0;
            }
        }
    }

    for (int i = 2; i <= MU_MAX; i++) {
        if (MU[i] == i) {
            MU[i] = 1;
        } else if (MU[i] == -i) {
            MU[i] = -1;
        } else if (MU[i] < 0) {
            MU[i] = 1;
        } else if (MU[i] > 0) {
            MU[i] = -1;
        }
    }

    return MU[n];
}

int main() {
    std::cout << "First 199 terms of the möbius function are as follows:\n    ";
    for (int n = 1; n < 200; n++) {
        std::cout << std::setw(2) << mobiusFunction(n) << "  ";
        if ((n + 1) % 20 == 0) {
            std::cout << '\n';
        }
    }

    return 0;
}
Output:
First 199 terms of the m÷bius function are as follows:
     1  -1  -1   0  -1   1  -1   0   0   1  -1   0  -1   1   1   0  -1   0  -1
 0   1   1  -1   0   0   1   0   0  -1  -1  -1   0   1   1   1   0  -1   1   1
 0  -1  -1  -1   0   0   1  -1   0   0   0   1   0  -1   0   1   0   1   1  -1
 0  -1   1   0   0   1  -1  -1   0   1  -1  -1   0  -1   1   0   0   1  -1  -1
 0   0   1  -1   0   1   1   1   0  -1   0   1   0   1   1   1   0  -1   0   0
 0  -1  -1  -1   0  -1   1  -1   0  -1  -1   1   0  -1  -1   1   0   0   1   1
 0   0   1   1   0   0   0  -1   0   1  -1  -1   0   1   1   0   0  -1  -1  -1
 0   1   1   1   0   1   1   0   0  -1   0  -1   0   0  -1   1   0  -1   1   1
 0   1   0  -1   0  -1   1  -1   0   0  -1   0   0  -1  -1   0   0   1   1  -1
 0  -1  -1   1   0   1  -1   1   0   0  -1  -1   0  -1   1  -1   0  -1   0  -1

D

Translation of: C++
import std.math;
import std.stdio;

immutable MU_MAX = 1_000_000;

int mobiusFunction(int n) {
    static initialized = false;
    static int[MU_MAX + 1] MU;

    if (initialized) {
        return MU[n];
    }

    // populate array
    MU[] = 1;
    int root = cast(int) sqrt(cast(real) MU_MAX);

    for (int i = 2; i <= root; i++) {
        if (MU[i] == 1) {
            // for each factor found, swap + and -
            for (int j = i; j <= MU_MAX; j += i) {
                MU[j] *= -i;
            }
            // square factor = 0
            for (int j = i * i; j <= MU_MAX; j += i * i) {
                MU[j] = 0;
            }
        }
    }

    for (int i = 2; i <= MU_MAX; i++) {
        if (MU[i] == i) {
            MU[i] = 1;
        } else if (MU[i] == -i) {
            MU[i] = -1;
        } else if (MU[i] < 0) {
            MU[i] = 1;
        } else if (MU[i] > 0) {
            MU[i] = -1;
        }
    }

    initialized = true;
    return MU[n];
}

void main() {
    writeln("First 199 terms of the möbius function are as follows:");
    write("    ");
    for (int n = 1; n < 200; n++) {
        writef("%2d  ", mobiusFunction(n));
        if ((n + 1) % 20 == 0) {
            writeln;
        }
    }
}
Output:
First 199 terms of the m├╢bius function are as follows:
     1  -1  -1   0  -1   1  -1   0   0   1  -1   0  -1   1   1   0  -1   0  -1
 0   1   1  -1   0   0   1   0   0  -1  -1  -1   0   1   1   1   0  -1   1   1
 0  -1  -1  -1   0   0   1  -1   0   0   0   1   0  -1   0   1   0   1   1  -1
 0  -1   1   0   0   1  -1  -1   0   1  -1  -1   0  -1   1   0   0   1  -1  -1
 0   0   1  -1   0   1   1   1   0  -1   0   1   0   1   1   1   0  -1   0   0
 0  -1  -1  -1   0  -1   1  -1   0  -1  -1   1   0  -1  -1   1   0   0   1   1
 0   0   1   1   0   0   0  -1   0   1  -1  -1   0   1   1   0   0  -1  -1  -1
 0   1   1   1   0   1   1   0   0  -1   0  -1   0   0  -1   1   0  -1   1   1
 0   1   0  -1   0  -1   1  -1   0   0  -1   0   0  -1  -1   0   0   1   1  -1
 0  -1  -1   1   0   1  -1   1   0   0  -1  -1   0  -1   1  -1   0  -1   0  -1

Delphi

Works with: Delphi version 6.0

Rather than being clever and trying to perform the task in the smallest number of lines possible, this solution breaks the problem down into its fundamental pieces and solves each one in a separate subroutine. This programming style makes the code easier understand, debug and enhance the code. While the technique is not necessary on simple problems like this, it is essential for larger and more complex programs.

function IsPrime(N: int64): boolean;
{Fast, optimised prime test}
var I,Stop: int64;
begin
if (N = 2) or (N=3) then Result:=true
else if (n <= 1) or ((n mod 2) = 0) or ((n mod 3) = 0) then Result:= false
else
     begin
     I:=5;
     Stop:=Trunc(sqrt(N+0.0));
     Result:=False;
     while I<=Stop do
           begin
           if ((N mod I) = 0) or ((N mod (I + 2)) = 0) then exit;
           Inc(I,6);
           end;
     Result:=True;
     end;
end;



function GetNextPrime(var Start: integer): integer;
{Get the next prime number after Start}
{Start is passed by "reference," so the
{original variable is incremented}
begin
repeat Inc(Start)
until IsPrime(Start);
Result:=Start;
end;


type TIntArray = array of integer;


procedure StoreNumber(N: integer; var IA: TIntArray);
{Expand and store number in array}
begin
SetLength(IA,Length(IA)+1);
IA[High(IA)]:=N;
end;


procedure GetPrimeFactors(N: integer; var Facts: TIntArray);
{Get all the prime factors of a number}
var I: integer;
begin
I:=2;
repeat
	begin
	if (N mod I) = 0 then
		begin
		StoreNumber(I,Facts);
		N:=N div I;
		end
	else GetNextPrime(I);
	end
until N=1;
end;



function HasDuplicates(IA: TIntArray): boolean;
{Look for duplicates factors in array}
var I: integer;
begin
Result:=True;
for I:=0 to Length(IA)-1 do
 if IA[I]=IA[I+1] then exit;
Result:=False;
end;


function Moebius(N: integer): integer;
{Get moebius function of number}
var I: integer;
var Factors: TIntArray;
var Even,Square: boolean;
begin
{Collect all prime factors}
SetLength(Factors,0);
GetPrimeFactors(N,Factors);
{Are there an even number of factors?}
Even:=(Length(Factors) and 1)=0;
{If there are duplicates, there are perfect squares}
Square:=HasDuplicates(Factors);
{Return the Moebius function value}
if Square then Result:=0
else if Even then Result:=1
else Result:=-1;
end;

procedure TestMoebiusFactors(Memo: TMemo);
{Test Moebius function for 1..200-1}
var N,M: integer;
var S: string;
begin
S:='';
for N:=1 to 199 do
	begin
	M:=Moebius(N);
	S:=S+Format('%3d',[M]);
	if (N mod 20)=19 then S:=S+#$0D#$0A
	end;
Memo.Text:=S;
end;
Output:
  1 -1 -1  0 -1  1 -1  0  0  1 -1  0 -1  1  1  0 -1  0 -1
  0  1  1 -1  0  0  1  0  0 -1 -1 -1  0  1  1  1  0 -1  1  1
  0 -1 -1 -1  0  0  1 -1  0  0  0  1  0 -1  0  1  0  1  1 -1
  0 -1  1  0  0  1 -1 -1  0  1 -1 -1  0 -1  1  0  0  1 -1 -1
  0  0  1 -1  0  1  1  1  0 -1  0  1  0  1  1  1  0 -1  0  0
  0 -1 -1 -1  0 -1  1 -1  0 -1 -1  1  0 -1 -1  1  0  0  1  1
  0  0  1  1  0  0  0 -1  0  1 -1 -1  0  1  1  0  0 -1 -1 -1
  0  1  1  1  0  1  1  0  0 -1  0 -1  0  0 -1  1  0 -1  1  1
  0  1  0 -1  0 -1  1 -1  0  0 -1  0  0 -1 -1  0  0  1  1 -1
  0 -1 -1  1  0  1 -1  1  0  0 -1 -1  0 -1  1 -1  0 -1  0 -1

EasyLang

Translation of: C
mu_max = 100000
sqroot = floor sqrt mu_max
# 
for i to mu_max
   mu[] &= 1
.
for i = 2 to sqroot
   if mu[i] = 1
      for j = i step i to mu_max
         mu[j] *= -i
      .
      for j = i * i step i * i to mu_max
         mu[j] = 0
      .
   .
.
for i = 2 to mu_max
   if mu[i] = i
      mu[i] = 1
   elif mu[i] = -i
      mu[i] = -1
   elif mu[i] < 0
      mu[i] = 1
   elif mu[i] > 0
      mu[i] = -1
   .
.
numfmt 0 3
for i = 1 to 100
   write mu[i]
   if i mod 10 = 0
      print ""
   .
.

F#

This task uses Extensible Prime Generator (F#)

// Möbius function. Nigel Galloway: January 31st., 2021
let fN g=let n=primes32()
         let rec fN i g e l=match (l/g,l%g,e) with (1,0,false)->i
                                                  |(n,0,false)->fN (0-i) g true n
                                                  |(_,0,true) ->0
                                                  |_          ->fN i (Seq.head n) false l
         fN -1 (Seq.head n) false g
let mobius=seq{yield 1; yield! Seq.initInfinite((+)2>>fN)}
mobius|>Seq.take 500|>Seq.chunkBySize 25|>Seq.iter(fun n->Array.iter(printf "%3d") n;printfn "")
Output:
  1 -1 -1  0 -1  1 -1  0  0  1 -1  0 -1  1  1  0 -1  0 -1  0  1  1 -1  0  0
  1  0  0 -1 -1 -1  0  1  1  1  0 -1  1  1  0 -1 -1 -1  0  0  1 -1  0  0  0
  1  0 -1  0  1  0  1  1 -1  0 -1  1  0  0  1 -1 -1  0  1 -1 -1  0 -1  1  0
  0  1 -1 -1  0  0  1 -1  0  1  1  1  0 -1  0  1  0  1  1  1  0 -1  0  0  0
 -1 -1 -1  0 -1  1 -1  0 -1 -1  1  0 -1 -1  1  0  0  1  1  0  0  1  1  0  0
  0 -1  0  1 -1 -1  0  1  1  0  0 -1 -1 -1  0  1  1  1  0  1  1  0  0 -1  0
 -1  0  0 -1  1  0 -1  1  1  0  1  0 -1  0 -1  1 -1  0  0 -1  0  0 -1 -1  0
  0  1  1 -1  0 -1 -1  1  0  1 -1  1  0  0 -1 -1  0 -1  1 -1  0 -1  0 -1  0
  1  1  1  0  1  1  0  0  1  1 -1  0  1  1  1  0  1  1  1  0  1 -1 -1  0  0
  1 -1  0 -1 -1 -1  0 -1  0  1  0  1 -1 -1  0 -1  0  0  0  0 -1  1  0  1  0
 -1  0  1  1 -1  0 -1 -1  1  0  0  1 -1  0  1 -1  1  0 -1  0 -1  0 -1  1  0
  0 -1  1  0  0 -1 -1 -1  0 -1 -1  1  0  0 -1  1  0 -1  0  1  0  0  1  1  0
  1  1  1  0  1  0 -1  0  1 -1 -1  0 -1  1  0  0 -1 -1  1  0  1 -1  1  0  0
  1  1  0  1  1 -1  0  0  1  1  0 -1  0  1  0  1  0  0  0 -1  1 -1  0 -1  0
  0  0 -1 -1  1  0 -1  1 -1  0  0  1  0  0  1 -1 -1  0  0 -1  1  0 -1 -1  0
  0  1  0 -1  0  1  1 -1  0 -1  1  0  0 -1  1  1  0  1  1  1  0 -1  1 -1  0
 -1 -1  1  0  0 -1  1  0 -1 -1  1  0  1  0  1  0  1 -1 -1  0 -1  1  0  0  0
 -1  1  0 -1 -1 -1  0 -1 -1 -1  0  1 -1 -1  0  0 -1 -1  0  1  1  1  0 -1  0
  1  0  1  1 -1  0 -1  1  0  0 -1  1 -1  0 -1  1 -1  0  1 -1  1  0  1 -1  0
  0  0  1 -1  0  1  1 -1  0  1  0 -1  0  1  0 -1  0  1 -1  0  0  1 -1 -1  0

Factor

The mobius word exists in the math.extras vocabulary. See the implementation here.

Works with: Factor version 0.99 2020-01-23
USING: formatting grouping io math.extras math.ranges sequences ;

"First 199 terms of the Möbius sequence:" print
199 [1,b] [ mobius ] map " " prefix 20 group
[ [ "%3s" printf ] each nl ] each
Output:
First 199 terms of the Möbius sequence:
     1 -1 -1  0 -1  1 -1  0  0  1 -1  0 -1  1  1  0 -1  0 -1
  0  1  1 -1  0  0  1  0  0 -1 -1 -1  0  1  1  1  0 -1  1  1
  0 -1 -1 -1  0  0  1 -1  0  0  0  1  0 -1  0  1  0  1  1 -1
  0 -1  1  0  0  1 -1 -1  0  1 -1 -1  0 -1  1  0  0  1 -1 -1
  0  0  1 -1  0  1  1  1  0 -1  0  1  0  1  1  1  0 -1  0  0
  0 -1 -1 -1  0 -1  1 -1  0 -1 -1  1  0 -1 -1  1  0  0  1  1
  0  0  1  1  0  0  0 -1  0  1 -1 -1  0  1  1  0  0 -1 -1 -1
  0  1  1  1  0  1  1  0  0 -1  0 -1  0  0 -1  1  0 -1  1  1
  0  1  0 -1  0 -1  1 -1  0  0 -1  0  0 -1 -1  0  0  1  1 -1
  0 -1 -1  1  0  1 -1  1  0  0 -1 -1  0 -1  1 -1  0 -1  0 -1

Fortran

Translation of: C
program moebius
    use iso_fortran_env, only: output_unit

    integer, parameter          :: mu_max=1000000, line_break=20
    integer, parameter          :: sqroot=int(sqrt(real(mu_max)))
    integer                     :: i, j
    integer, dimension(mu_max)  :: mu

    mu = 1

    do i = 2, sqroot
        if (mu(i) == 1) then
            do j = i, mu_max, i
                mu(j) = mu(j) * (-i)
            end do

            do j = i**2, mu_max, i**2
                mu(j) = 0
            end do
        end if
    end do

    do i = 2, mu_max
        if (mu(i) == i) then
            mu(i) = 1
        else if (mu(i) == -i) then
            mu(i) = -1
        else if (mu(i) < 0) then
            mu(i) = 1
        else if (mu(i) > 0) then
            mu(i) = -1
        end if
    end do

    write(output_unit,*) "The first 199 terms of the Möbius sequence are:"
    write(output_unit,'(3x)', advance="no") ! Alignment of first number
    do i = 1, 199
        write(output_unit,'(I2,x)', advance="no") mu(i)
        if (modulo(i+1, line_break) == 0) write(output_unit,*)
    end do
end program moebius
Output:
 The first 199 terms of the Möbius sequence are:
    1 -1 -1  0 -1  1 -1  0  0  1 -1  0 -1  1  1  0 -1  0 -1 
 0  1  1 -1  0  0  1  0  0 -1 -1 -1  0  1  1  1  0 -1  1  1 
 0 -1 -1 -1  0  0  1 -1  0  0  0  1  0 -1  0  1  0  1  1 -1 
 0 -1  1  0  0  1 -1 -1  0  1 -1 -1  0 -1  1  0  0  1 -1 -1 
 0  0  1 -1  0  1  1  1  0 -1  0  1  0  1  1  1  0 -1  0  0 
 0 -1 -1 -1  0 -1  1 -1  0 -1 -1  1  0 -1 -1  1  0  0  1  1 
 0  0  1  1  0  0  0 -1  0  1 -1 -1  0  1  1  0  0 -1 -1 -1 
 0  1  1  1  0  1  1  0  0 -1  0 -1  0  0 -1  1  0 -1  1  1 
 0  1  0 -1  0 -1  1 -1  0  0 -1  0  0 -1 -1  0  0  1  1 -1 
 0 -1 -1  1  0  1 -1  1  0  0 -1 -1  0 -1  1 -1  0 -1  0 -1 

Go

package main

import "fmt"

func möbius(to int) []int {
    if to < 1 {
        to = 1
    }
    mobs := make([]int, to+1) // all zero by default
    primes := []int{2}
    for i := 1; i <= to; i++ {
        j := i
        cp := 0      // counts prime factors
        spf := false // true if there is a square prime factor
        for _, p := range primes {
            if p > j {
                break
            }
            if j%p == 0 {
                j /= p
                cp++
            }
            if j%p == 0 {
                spf = true
                break
            }
        }
        if cp == 0 && i > 2 {
            cp = 1
            primes = append(primes, i)
        }
        if !spf {
            if cp%2 == 0 {
                mobs[i] = 1
            } else {
                mobs[i] = -1
            }
        }
    }
    return mobs
}

func main() {
    mobs := möbius(199)
    fmt.Println("Möbius sequence - First 199 terms:")
    for i := 0; i < 200; i++ {
        if i == 0 {
            fmt.Print("    ")
            continue
        }
        if i%20 == 0 {
            fmt.Println()
        }
        fmt.Printf("  % d", mobs[i])
    }
}
Output:
Möbius sequence - First 199 terms:
       1  -1  -1   0  -1   1  -1   0   0   1  -1   0  -1   1   1   0  -1   0  -1
   0   1   1  -1   0   0   1   0   0  -1  -1  -1   0   1   1   1   0  -1   1   1
   0  -1  -1  -1   0   0   1  -1   0   0   0   1   0  -1   0   1   0   1   1  -1
   0  -1   1   0   0   1  -1  -1   0   1  -1  -1   0  -1   1   0   0   1  -1  -1
   0   0   1  -1   0   1   1   1   0  -1   0   1   0   1   1   1   0  -1   0   0
   0  -1  -1  -1   0  -1   1  -1   0  -1  -1   1   0  -1  -1   1   0   0   1   1
   0   0   1   1   0   0   0  -1   0   1  -1  -1   0   1   1   0   0  -1  -1  -1
   0   1   1   1   0   1   1   0   0  -1   0  -1   0   0  -1   1   0  -1   1   1
   0   1   0  -1   0  -1   1  -1   0   0  -1   0   0  -1  -1   0   0   1   1  -1
   0  -1  -1   1   0   1  -1   1   0   0  -1  -1   0  -1   1  -1   0  -1   0  -1

Haskell

import Data.List (intercalate)
import Data.List.Split (chunksOf)
import Data.Vector.Unboxed (toList)
import Math.NumberTheory.ArithmeticFunctions.Moebius (Moebius(..),
                                                      sieveBlockMoebius)
import System.Environment (getArgs, getProgName)
import System.IO (hPutStrLn, stderr)
import Text.Read (readMaybe)

-- Calculate the Möbius function, μ(n), for a sequence of values starting at 1.
moebiusBlock :: Word -> [Moebius]
moebiusBlock = toList . sieveBlockMoebius 1

showMoebiusBlock :: Word -> [Moebius] -> String
showMoebiusBlock cols = intercalate "\n" . map (concatMap showMoebius) .
                        chunksOf (fromIntegral cols)
  where showMoebius MoebiusN = " -1"
        showMoebius MoebiusZ = "  0"
        showMoebius MoebiusP = "  1"

main :: IO ()
main = do
  prog <- getProgName
  args <- map readMaybe <$> getArgs
  case args of
    [Just cols, Just n] ->
      putStrLn ("μ(n) for 1 ≤ n ≤ " ++ show n ++ ":\n") >>
      putStrLn (showMoebiusBlock cols $ moebiusBlock n)
    _ -> hPutStrLn stderr $ "Usage: " ++ prog ++ " num-columns maximum-number"
Output:
μ(n) for 1 ≤ n ≤ 200:

  1 -1 -1  0 -1  1 -1  0  0  1 -1  0 -1  1  1  0 -1  0 -1  0
  1  1 -1  0  0  1  0  0 -1 -1 -1  0  1  1  1  0 -1  1  1  0
 -1 -1 -1  0  0  1 -1  0  0  0  1  0 -1  0  1  0  1  1 -1  0
 -1  1  0  0  1 -1 -1  0  1 -1 -1  0 -1  1  0  0  1 -1 -1  0
  0  1 -1  0  1  1  1  0 -1  0  1  0  1  1  1  0 -1  0  0  0
 -1 -1 -1  0 -1  1 -1  0 -1 -1  1  0 -1 -1  1  0  0  1  1  0
  0  1  1  0  0  0 -1  0  1 -1 -1  0  1  1  0  0 -1 -1 -1  0
  1  1  1  0  1  1  0  0 -1  0 -1  0  0 -1  1  0 -1  1  1  0
  1  0 -1  0 -1  1 -1  0  0 -1  0  0 -1 -1  0  0  1  1 -1  0
 -1 -1  1  0  1 -1  1  0  0 -1 -1  0 -1  1 -1  0 -1  0 -1  0

J

Implementation:

mu=: */@:-@~:@q:

Explanation: q: n gives the list of prime factors of n. (This is an empty list for the number 1, is 2 2 5 5 for the number 100, and is 2 2 2 3 5 for the number 120.)

In this context ~: replaces each prime factor either by 1, if it is its first occurrence, or by 0, if it is a repetition (e.g. 2 2 5 51 0 1 0). Then, - simply negates this list (e.g. 1 0 1 0_1 0 _1 0), and finally */ multiplies all list elements to get the desired result.

Task example:

   mu >: i. 10 20
 1 _1 _1 0 _1  1 _1 0  0  1 _1 0 _1  1  1 0 _1  0 _1 0
 1  1 _1 0  0  1  0 0 _1 _1 _1 0  1  1  1 0 _1  1  1 0
_1 _1 _1 0  0  1 _1 0  0  0  1 0 _1  0  1 0  1  1 _1 0
_1  1  0 0  1 _1 _1 0  1 _1 _1 0 _1  1  0 0  1 _1 _1 0
 0  1 _1 0  1  1  1 0 _1  0  1 0  1  1  1 0 _1  0  0 0
_1 _1 _1 0 _1  1 _1 0 _1 _1  1 0 _1 _1  1 0  0  1  1 0
 0  1  1 0  0  0 _1 0  1 _1 _1 0  1  1  0 0 _1 _1 _1 0
 1  1  1 0  1  1  0 0 _1  0 _1 0  0 _1  1 0 _1  1  1 0
 1  0 _1 0 _1  1 _1 0  0 _1  0 0 _1 _1  0 0  1  1 _1 0
_1 _1  1 0  1 _1  1 0  0 _1 _1 0 _1  1 _1 0 _1  0 _1 0

Java

public class MöbiusFunction {

    public static void main(String[] args) {
        System.out.printf("First 199 terms of the möbius function are as follows:%n    ");
        for ( int n = 1 ; n < 200 ; n++ ) {
            System.out.printf("%2d  ", möbiusFunction(n));
            if ( (n+1) % 20 == 0 ) {
                System.out.printf("%n");
            }
        }
    }
    
    private static int MU_MAX = 1_000_000;
    private static int[] MU = null;
    
    //  Compute mobius function via sieve
    private static int möbiusFunction(int n) {
        if ( MU != null ) {
            return MU[n];
        }
        
        //  Populate array
        MU = new int[MU_MAX+1];
        int sqrt = (int) Math.sqrt(MU_MAX);
        for ( int i = 0 ; i < MU_MAX ; i++ ) {
            MU[i] = 1;
        }
        
        for ( int i = 2 ; i <= sqrt ; i++ ) {
            if ( MU[i] == 1 ) {
                //  for each factor found, swap + and -
                for ( int j = i ; j <= MU_MAX ; j += i ) {
                    MU[j] *= -i;
                }
                //  square factor = 0
                for ( int j = i*i ; j <= MU_MAX ; j += i*i ) {
                    MU[j] = 0;
                }
            }
        }
        
        for ( int i = 2 ; i <= MU_MAX ; i++ ) {
            if ( MU[i] == i ) {
                MU[i] = 1;
            }
            else if ( MU[i] == -i ) {
                MU[i] = -1;
            }
            else if ( MU[i] < 0 ) {
                MU[i] = 1;               
            }
            else if ( MU[i] > 0 ) {
                MU[i] = -1;
            }
        }
        return MU[n];
    }

}
Output:
First 199 terms of the möbius function are as follows:
     1  -1  -1   0  -1   1  -1   0   0   1  -1   0  -1   1   1   0  -1   0  -1  
 0   1   1  -1   0   0   1   0   0  -1  -1  -1   0   1   1   1   0  -1   1   1  
 0  -1  -1  -1   0   0   1  -1   0   0   0   1   0  -1   0   1   0   1   1  -1  
 0  -1   1   0   0   1  -1  -1   0   1  -1  -1   0  -1   1   0   0   1  -1  -1  
 0   0   1  -1   0   1   1   1   0  -1   0   1   0   1   1   1   0  -1   0   0  
 0  -1  -1  -1   0  -1   1  -1   0  -1  -1   1   0  -1  -1   1   0   0   1   1  
 0   0   1   1   0   0   0  -1   0   1  -1  -1   0   1   1   0   0  -1  -1  -1  
 0   1   1   1   0   1   1   0   0  -1   0  -1   0   0  -1   1   0  -1   1   1  
 0   1   0  -1   0  -1   1  -1   0   0  -1   0   0  -1  -1   0   0   1   1  -1  
 0  -1  -1   1   0   1  -1   1   0   0  -1  -1   0  -1   1  -1   0  -1   0  -1  

jq

Works with: jq

Works with gojq, the Go implementation of jq

Using a Sieve

Adapted from C

# Input: a non-negative integer, $n
# Output: an array of size $n + 1 such that the nth-mobius number is .[$n]
# i.e. $n|mobius_array[-1]
# For example, the first mobius number could be evaluated by 1|mobius_array[-1].
def mobius_array:
  . as $n
  | ($n|sqrt) as $sqrt
  | reduce range(2; 1 + $sqrt) as $i ([range(0; $n + 1) | 1];
       if .[$i] == 1
       then # for each factor found, swap + and -
         reduce range($i; $n + 1; $i) as $j (.; .[$j] *= -$i) 
         | ($i*$i) as $isq #  square factor = 0
         | reduce range($isq; $n + 1; $isq) as $j (.; .[$j] = 0 )
       else .
       end )
  | reduce range(2; 1 + $n) as $i (.;
       if   .[$i] ==  $i then .[$i] = 1
       elif .[$i] == -$i then .[$i] = -1
       elif .[$i]  <   0 then .[$i] = 1
       elif .[$i]  >   0 then .[$i] = -1
       else .[$i] = 0                   # avoid "-0"
       end);

# For one-off computations:
def mu($n): $n | mobius_array[-1];

The Task

def nwise($n):
  def n: if length <= $n then . else .[0:$n] , (.[$n:] | n) end;
  n;

def task:
  def pp: if . >=0 then " \(.)" else tostring end;
  (199 | mobius_array) as $mu
  | "The first 199 Möbius numbers are:",
    (["  ", (range(1; 200) | $mu[.] | pp )]
     | nwise(20)
     | join(" ") ) ;

task
Output:
The first 199 Möbius numbers are:
    1 -1 -1  0 -1  1 -1  0  0  1 -1  0 -1  1  1  0 -1  0 -1
 0  1  1 -1  0  0  1  0  0 -1 -1 -1  0  1  1  1  0 -1  1  1
 0 -1 -1 -1  0  0  1 -1  0  0  0  1  0 -1  0  1  0  1  1 -1
 0 -1  1  0  0  1 -1 -1  0  1 -1 -1  0 -1  1  0  0  1 -1 -1
 0  0  1 -1  0  1  1  1  0 -1  0  1  0  1  1  1  0 -1  0  0
 0 -1 -1 -1  0 -1  1 -1  0 -1 -1  1  0 -1 -1  1  0  0  1  1
 0  0  1  1  0  0  0 -1  0  1 -1 -1  0  1  1  0  0 -1 -1 -1
 0  1  1  1  0  1  1  0  0 -1  0 -1  0  0 -1  1  0 -1  1  1
 0  1  0 -1  0 -1  1 -1  0  0 -1  0  0 -1 -1  0  0  1  1 -1
 0 -1 -1  1  0  1 -1  1  0  0 -1 -1  0 -1  1 -1  0 -1  0 -1

Prime Factors

Note that the following solution to the task at hand (computing a range of Mobius numbers is inefficient as it does not cache the primes array. Preliminaries

# relatively_prime(previous) tests whether the input integer is prime
# relative to the primes in the array "previous":
def relatively_prime(previous):
  . as $in
  | (previous|length) as $plen
  # state: [found, ix]
  | [false, 0]
  | until( .[0] or .[1] >= $plen;
           [ ($in % previous[.[1]]) == 0, .[1] + 1] )
  | .[0] | not ;

# Emit a stream in increasing order of all primes (from 2 onwards)
# that are less than or equal to mx:
def primes(mx):
  # The helper function, next, has arity 0 for tail recursion optimization;
  # it expects its input to be the array of previously found primes:
  def next:
     . as $previous
     | ($previous | .[length-1]) as $last
     | if ($last >= mx) then empty
       else ((2 + $last)
       | until( relatively_prime($previous) ; . + 2)) as $nextp
       | if $nextp <= mx
         then $nextp, (( $previous + [$nextp] ) | next)
	 else empty
         end
       end;
  if mx <= 1 then empty
  elif mx == 2 then 2
  else (2, 3, ([2,3] | next))
  end ;

# Return an array of the distinct prime factors of . in increasing order
def prime_factors:

  # Return an array of prime factors of . given that "primes"
  # is an array of relevant primes:
  def pf($primes):
    if . <= 1 then []
    else . as $in
    | if ($in | relatively_prime($primes)) then [$in]
      else reduce $primes[] as $p
             ([];
              if ($in % $p) != 0 then .
 	      else . + [$p] +  (($in / $p) | pf($primes))
	      end)
      end
      | unique
    end;
    
  if . <= 1 then []
  else . as $in
  | pf( [ primes( (1+$in) | sqrt | floor)  ] )
  end;

Mu

def isSquareFree:
  . as $n
  | 2
  | until ( (. * . > $n) or . == 0;
       if ($n % (.*.) == 0) then 0 # i.e. stop
       elif . > 2 then . + 2
       else . + 1
       end  )
  | . != 0;

def mu:
  . as $n
  | if . < 1 then "Argument to mu must be a positive integer" | error
    elif . == 1 then 1
    else if isSquareFree 
         then if ((prime_factors|length) % 2 == 0) then 1 
              else -1
              end
         else 0
         end
    end;

The Task

def nwise($n):
  def n: if length <= $n then . else .[0:$n] , (.[$n:] | n) end;
  n;

def task:
  def pp: if . >=0 then " \(.)" else tostring end;
  "The first 199 Möbius numbers are:",
  (["  ", (range(1; 200) | mu | pp )]
   | nwise(20)
   | join(" ") ) ;

task
Output:

As above.

Julia

using Primes

# modified from reinermartin's PR at https://github.com/JuliaMath/Primes.jl/pull/70/files
function moebius(n::Integer)
    @assert n > 0
    m(p, e) = p == 0 ? 0 : e == 1 ? -1 : 0
    reduce(*, m(p, e) for (p, e) in factor(n) if p  0; init=1)
end
μ(n) = moebius(n)

print("First 199 terms of the Möbius sequence:\n   ")
for n in 1:199
    print(lpad(μ(n), 3), n % 20 == 19 ? "\n" : "")
end
Output:
First 199 terms of the Möbius sequence:
     1 -1 -1  0 -1  1 -1  0  0  1 -1  0 -1  1  1  0 -1  0 -1
  0  1  1 -1  0  0  1  0  0 -1 -1 -1  0  1  1  1  0 -1  1  1
  0 -1 -1 -1  0  0  1 -1  0  0  0  1  0 -1  0  1  0  1  1 -1
  0 -1  1  0  0  1 -1 -1  0  1 -1 -1  0 -1  1  0  0  1 -1 -1
  0  0  1 -1  0  1  1  1  0 -1  0  1  0  1  1  1  0 -1  0  0
  0 -1 -1 -1  0 -1  1 -1  0 -1 -1  1  0 -1 -1  1  0  0  1  1
  0  0  1  1  0  0  0 -1  0  1 -1 -1  0  1  1  0  0 -1 -1 -1
  0  1  1  1  0  1  1  0  0 -1  0 -1  0  0 -1  1  0 -1  1  1
  0  1  0 -1  0 -1  1 -1  0  0 -1  0  0 -1 -1  0  0  1  1 -1
  0 -1 -1  1  0  1 -1  1  0  0 -1 -1  0 -1  1 -1  0 -1  0 -1

Kotlin

Translation of: Java
import kotlin.math.sqrt

fun main() {
    println("First 199 terms of the möbius function are as follows:")
    print("    ")
    for (n in 1..199) {
        print("%2d  ".format(mobiusFunction(n)))
        if ((n + 1) % 20 == 0) {
            println()
        }
    }
}

private const val MU_MAX = 1000000
private var MU: IntArray? = null

//  Compute mobius function via sieve
private fun mobiusFunction(n: Int): Int {
    if (MU != null) {
        return MU!![n]
    }

    //  Populate array
    MU = IntArray(MU_MAX + 1)
    val sqrt = sqrt(MU_MAX.toDouble()).toInt()
    for (i in 0 until MU_MAX) {
        MU!![i] = 1
    }
    for (i in 2..sqrt) {
        if (MU!![i] == 1) {
            //  for each factor found, swap + and -
            for (j in i..MU_MAX step i) {
                MU!![j] *= -i
            }
            //  square factor = 0
            for (j in i * i..MU_MAX step i * i) {
                MU!![j] = 0
            }
        }
    }
    for (i in 2..MU_MAX) {
        when {
            MU!![i] == i -> {
                MU!![i] = 1
            }
            MU!![i] == -i -> {
                MU!![i] = -1
            }
            MU!![i] < 0 -> {
                MU!![i] = 1
            }
            MU!![i] > 0 -> {
                MU!![i] = -1
            }
        }
    }
    return MU!![n]
}
Output:
First 199 terms of the möbius function are as follows:
     1  -1  -1   0  -1   1  -1   0   0   1  -1   0  -1   1   1   0  -1   0  -1  
 0   1   1  -1   0   0   1   0   0  -1  -1  -1   0   1   1   1   0  -1   1   1  
 0  -1  -1  -1   0   0   1  -1   0   0   0   1   0  -1   0   1   0   1   1  -1  
 0  -1   1   0   0   1  -1  -1   0   1  -1  -1   0  -1   1   0   0   1  -1  -1  
 0   0   1  -1   0   1   1   1   0  -1   0   1   0   1   1   1   0  -1   0   0  
 0  -1  -1  -1   0  -1   1  -1   0  -1  -1   1   0  -1  -1   1   0   0   1   1  
 0   0   1   1   0   0   0  -1   0   1  -1  -1   0   1   1   0   0  -1  -1  -1  
 0   1   1   1   0   1   1   0   0  -1   0  -1   0   0  -1   1   0  -1   1   1  
 0   1   0  -1   0  -1   1  -1   0   0  -1   0   0  -1  -1   0   0   1   1  -1  
 0  -1  -1   1   0   1  -1   1   0   0  -1  -1   0  -1   1  -1   0  -1   0  -1  

Lua

Translation of: C
function buildArray(size, value)
    local tbl = {}
    for i=1, size do
        table.insert(tbl, value)
    end
    return tbl
end

MU_MAX = 1000000
sqroot = math.sqrt(MU_MAX)
mu = buildArray(MU_MAX, 1)

for i=2, sqroot do
    if mu[i] == 1 then
        -- for each factor found, swap + and -
        for j=i, MU_MAX, i do
            mu[j] = mu[j] * -i
        end
        -- square factor = 0
        for j=i*i, MU_MAX, i*i do
            mu[j] = 0
        end
    end
end

for i=2, MU_MAX do
    if mu[i] == i then
        mu[i] = 1
    elseif mu[i] == -i then
        mu[i] = -1
    elseif mu[i] < 0 then
        mu[i] = 1
    elseif mu[i] > 0 then
        mu[i] = -1
    end
end

print("First 199 terms of the mobius function are as follows:")
io.write("    ")
for i=1, 199 do
    io.write(string.format("%2d  ", mu[i]))
    if (i + 1) % 20 == 0 then
        print()
    end
end
Output:
First 199 terms of the mobius function are as follows:
     1  -1  -1   0  -1   1  -1   0   0   1  -1   0  -1   1   1   0  -1   0  -1
 0   1   1  -1   0   0   1   0   0  -1  -1  -1   0   1   1   1   0  -1   1   1
 0  -1  -1  -1   0   0   1  -1   0   0   0   1   0  -1   0   1   0   1   1  -1
 0  -1   1   0   0   1  -1  -1   0   1  -1  -1   0  -1   1   0   0   1  -1  -1
 0   0   1  -1   0   1   1   1   0  -1   0   1   0   1   1   1   0  -1   0   0
 0  -1  -1  -1   0  -1   1  -1   0  -1  -1   1   0  -1  -1   1   0   0   1   1
 0   0   1   1   0   0   0  -1   0   1  -1  -1   0   1   1   0   0  -1  -1  -1
 0   1   1   1   0   1   1   0   0  -1   0  -1   0   0  -1   1   0  -1   1   1
 0   1   0  -1   0  -1   1  -1   0   0  -1   0   0  -1  -1   0   0   1   1  -1
 0  -1  -1   1   0   1  -1   1   0   0  -1  -1   0  -1   1  -1   0  -1   0  -1

Mathematica/Wolfram Language

Grid[Partition[MoebiusMu[Range[99]], UpTo[10]]]
Output:
1	-1	-1	0	-1	1	-1	0	0	1
-1	0	-1	1	1	0	-1	0	-1	0
1	1	-1	0	0	1	0	0	-1	-1
-1	0	1	1	1	0	-1	1	1	0
-1	-1	-1	0	0	1	-1	0	0	0
1	0	-1	0	1	0	1	1	-1	0
-1	1	0	0	1	-1	-1	0	1	-1
-1	0	-1	1	0	0	1	-1	-1	0
0	1	-1	0	1	1	1	0	-1	0
1	0	1	1	1	0	-1	0	0	

Nim

Uses the prime decomposition method from https://rosettacode.org/wiki/Prime_decomposition#Nim

import std/[math, sequtils, strformat]

func getStep(n: int): int {.inline.} =
  result = 1 + n shl 2 - n shr 1 shl 1
 
func primeFac(n: int): seq[int] =
  var 
    maxq = int(sqrt(float(n)))
    d = 1
    q: int = 2 + (n and 1)   # Start with 2 or 3 according to oddity.

  while q <= maxq and n %% q != 0:
    q = getStep(d)
    inc d
  if q <= maxq:
    let q1 = primeFac(n /% q)
    let q2 = primeFac(q)
    result = concat(q2, q1, result)
  else:
    result.add(n)

func squareFree(num: int): bool = 
  let fact = primeFac num

  for i in fact:
    if fact.count(i) > 1:
      return false

  return true

func mobius(num: int): int = 
  if num == 1: return num

  let fact = primeFac num

  for i in fact: 
    ## check if it has a squared prime factor
    if fact.count(i) == 2: 
      return 0

  if num.squareFree:
    if fact.len mod 2 == 0: 
      return 1
    else:
      return -1

when isMainModule:
  echo "The first 199 möbius numbers are:" 

  for i in 1..199:
    stdout.write fmt"{mobius(i):4}"
    if i mod 20 == 0:
      echo "" # print newline
Output:
The first 199 möbius numbers are:
   1  -1  -1   0  -1   1  -1   0   0   1  -1   0  -1   1   1   0  -1   0  -1   0
   1   1  -1   0   0   1   0   0  -1  -1  -1   0   1   1   1   0  -1   1   1   0
  -1  -1  -1   0   0   1  -1   0   0   0   1   0  -1   0   1   0   1   1  -1   0
  -1   1   0   0   1  -1  -1   0   1  -1  -1   0  -1   1   0   0   1  -1  -1   0
   0   1  -1   0   1   1   1   0  -1   0   1   0   1   1   1   0  -1   0   0   0
  -1  -1  -1   0  -1   1  -1   0  -1  -1   1   0  -1  -1   1   0   0   1   1   0
   0   1   1   0   0   0  -1   0   1  -1  -1   0   1   1   0   0  -1  -1  -1   0
   1   1   1   0   1   1   0   0  -1   0  -1   0   0  -1   1   0  -1   1   1   0
   1   0  -1   0  -1   1  -1   0   0  -1   0   0  -1  -1   0   0   1   1  -1   0
  -1  -1   1   0   1  -1   1   0   0  -1  -1   0  -1   1  -1   0  -1   0  -1   0


PARI/GP

Translation of: Julia
{
    for(i = 1, 99,
        print1(moebius(i) " ");
        if(i % 10 == 0, print("\n"););
    );
}
Output:
1 -1 -1 0 -1 1 -1 0 0 1 

-1 0 -1 1 1 0 -1 0 -1 0 

1 1 -1 0 0 1 0 0 -1 -1 

-1 0 1 1 1 0 -1 1 1 0 

-1 -1 -1 0 0 1 -1 0 0 0 

1 0 -1 0 1 0 1 1 -1 0 

-1 1 0 0 1 -1 -1 0 1 -1 

-1 0 -1 1 0 0 1 -1 -1 0 

0 1 -1 0 1 1 1 0 -1 0 

1 0 1 1 1 0 -1 0 0 


Pascal

 See Mertens_function#Pascal

Perl

use utf8;
use strict;
use warnings;
use feature 'say';
use List::Util 'uniq';

sub prime_factors {
    my ($n, $d, @factors) = (shift, 1);
    while ($n > 1 and $d++) {
        $n /= $d, push @factors, $d until $n % $d;
    }
    @factors
}

sub μ {
    my @p = prime_factors(shift);
    @p == uniq(@p) ? 0 == @p%2 ? 1 : -1 : 0;
}

my @möebius;
push @möebius, μ($_) for 1 .. (my $upto = 199);

say "Möbius sequence - First $upto terms:\n" .
    (' 'x4 . sprintf "@{['%4d' x $upto]}", @möebius) =~ s/((.){80})/$1\n/gr;
Output:
Möbius sequence - First 199 terms:
       1  -1  -1   0  -1   1  -1   0   0   1  -1   0  -1   1   1   0  -1   0  -1
   0   1   1  -1   0   0   1   0   0  -1  -1  -1   0   1   1   1   0  -1   1   1
   0  -1  -1  -1   0   0   1  -1   0   0   0   1   0  -1   0   1   0   1   1  -1
   0  -1   1   0   0   1  -1  -1   0   1  -1  -1   0  -1   1   0   0   1  -1  -1
   0   0   1  -1   0   1   1   1   0  -1   0   1   0   1   1   1   0  -1   0   0
   0  -1  -1  -1   0  -1   1  -1   0  -1  -1   1   0  -1  -1   1   0   0   1   1
   0   0   1   1   0   0   0  -1   0   1  -1  -1   0   1   1   0   0  -1  -1  -1
   0   1   1   1   0   1   1   0   0  -1   0  -1   0   0  -1   1   0  -1   1   1
   0   1   0  -1   0  -1   1  -1   0   0  -1   0   0  -1  -1   0   0   1   1  -1
   0  -1  -1   1   0   1  -1   1   0   0  -1  -1   0  -1   1  -1   0  -1   0  -1

Phix

with javascript_semantics
function Moebius(integer n)
    if n=1 then return 1 end if
    sequence f = prime_factors(n,true)
    for i=2 to length(f) do
        if f[i] = f[i-1] then return 0 end if
    end for
    return iff(odd(length(f))?-1:+1)
end function

sequence s = {"  ."}
for i=1 to 199 do s = append(s,sprintf("%3d",Moebius(i))) end for
puts(1,join_by(s,1,20," "))
Output:
  .   1  -1  -1   0  -1   1  -1   0   0   1  -1   0  -1   1   1   0  -1   0  -1
  0   1   1  -1   0   0   1   0   0  -1  -1  -1   0   1   1   1   0  -1   1   1
  0  -1  -1  -1   0   0   1  -1   0   0   0   1   0  -1   0   1   0   1   1  -1
  0  -1   1   0   0   1  -1  -1   0   1  -1  -1   0  -1   1   0   0   1  -1  -1
  0   0   1  -1   0   1   1   1   0  -1   0   1   0   1   1   1   0  -1   0   0
  0  -1  -1  -1   0  -1   1  -1   0  -1  -1   1   0  -1  -1   1   0   0   1   1
  0   0   1   1   0   0   0  -1   0   1  -1  -1   0   1   1   0   0  -1  -1  -1
  0   1   1   1   0   1   1   0   0  -1   0  -1   0   0  -1   1   0  -1   1   1
  0   1   0  -1   0  -1   1  -1   0   0  -1   0   0  -1  -1   0   0   1   1  -1
  0  -1  -1   1   0   1  -1   1   0   0  -1  -1   0  -1   1  -1   0  -1   0  -1

Python

Everything verbatim from: https://www.geeksforgeeks.org/program-mobius-function/

All code by: Manish Shaw

Method 1

We iterate through all numbers i smaller than or equal to N. For every number we check if it divides N. If yes, we check if it’s also prime. If both conditions are satisfied, we check if its square also divides N. If yes, we return 0. If the square doesn’t divide, we increment count of prime factors. Finally, we return 1 if there are an even number of prime factors and return -1 if there are odd number of prime factors.


# Python Program to evaluate
# Mobius def M(N) = 1 if N = 1
# M(N) = 0 if any prime factor
# of N is contained twice
# M(N) = (-1)^(no of distinct
# prime factors)
# Python Program to
# evaluate Mobius def
# M(N) = 1 if N = 1
# M(N) = 0 if any
# prime factor of
# N is contained twice
# M(N) = (-1)^(no of
# distinct prime factors)
 
# def to check if
# n is prime or not
def isPrime(n) :
 
    if (n < 2) :
        return False
    for i in range(2, n + 1) :
        if (i * i <= n and n % i == 0) :
            return False
    return True
 
def mobius(N) :
     
    # Base Case
    if (N == 1) :
        return 1
 
    # For a prime factor i
    # check if i^2 is also
    # a factor.
    p = 0
    for i in range(1, N + 1) :
        if (N % i == 0 and
                isPrime(i)) :
 
            # Check if N is
            # divisible by i^2
            if (N % (i * i) == 0) :
                return 0
            else :
 
                # i occurs only once,
                # increase f
                p = p + 1
 
    # All prime factors are
    # contained only once
    # Return 1 if p is even
    # else -1
    if(p % 2 != 0) :
        return -1
    else :
        return 1
 
# Driver Code
print("Mobius numbers from 1..99:")
      
for i in range(1, 100):
  print(f"{mobius(i):>4}", end = '')

  if i % 20 == 0: print()
# This code is contributed by
# Manish Shaw(manishshaw1)
Output:
Mobius numbers from 1..99:
   1  -1  -1   0  -1   1  -1   0   0   1  -1   0  -1   1   1   0  -1   0  -1   0
   1   1  -1   0   0   1   0   0  -1  -1  -1   0   1   1   1   0  -1   1   1   0
  -1  -1  -1   0   0   1  -1   0   0   0   1   0  -1   0   1   0   1   1  -1   0
  -1   1   0   0   1  -1  -1   0   1  -1  -1   0  -1   1   0   0   1  -1  -1   0
   0   1  -1   0   1   1   1   0  -1   0   1   0   1   1   1   0  -1   0   0

Method 2 (Efficient)

The idea is based on efficient program to print all prime factors of a given number. The interesting thing is, we do not need inner while loop here because if a number divides more than once, we can immediately return 0.

  1. BUGS ! mu(1): computes -1, correct 1
  2. BUGS ! mu(2): computes 1, correct -1
  3. BUGS ! mu(105): computes 1, correct -1
  4. BUGS ! ...
  5. Some other programs say: "Translation of Python", probably of this one.
# Python Program to evaluate
# Mobius def M(N) = 1 if N = 1
# M(N) = 0 if any prime factor
# of N is contained twice
# M(N) = (-1)^(no of distinct
# prime factors)
import math
 
# def to check if n
# is prime or not
def isPrime(n) :
 
    if (n < 2) :
        return False
    for i in range(2, n + 1) :
        if (n % i == 0) :
            return False
        i = i * i
    return True
 
def mobius(n) :
 
    p = 0
 
    # Handling 2 separately
    if (n % 2 == 0) :
     
        n = int(n / 2)
        p = p + 1
 
        # If 2^2 also
        # divides N
        if (n % 2 == 0) :
            return 0
     
 
    # Check for all
    # other prime factors
    for i in range(3, int(math.sqrt(n)) + 1) :
     
        # If i divides n
        if (n % i == 0) :
         
            n = int(n / i)
            p = p + 1
 
            # If i^2 also
            # divides N
            if (n % i == 0) :
                return 0
        i = i + 2   
     
    if(p % 2 == 0) :
        return -1
    else :
        return 1
 
# Driver Code
print("Mobius numbers from 1..99:")
      
for i in range(1, 100):
  print(f"{mobius(i):>4}", end = '')
# This code is contributed by
# Manish Shaw(manishshaw1)
Output:
Mobius numbers from 1..99:
  -1   1  -1   0  -1   1  -1   0   0   1  -1   0  -1   1   1   0  -1   0  -1   0
   1   1  -1   0   0   1   0   0  -1  -1  -1   0   1   1   1   0  -1   1   1   0
  -1  -1  -1   0   0   1  -1   0   0   0   1   0  -1   0   1   0   1   1  -1   0
  -1   1   0   0   1  -1  -1   0   1  -1  -1   0  -1   1   0   0   1  -1  -1   0
   0   1  -1   0   1   1   1   0  -1   0   1   0   1   1   1   0  -1   0   0

Quackery

primefactors is defined at Prime decomposition#Quackery.

  [ false swap
    behead swap
      [ witheach
          [ tuck != if
              done
            dip not
            conclude ] ]
    drop ]               is square ( [ --> b )

  [ 1 & ]                is odd    ( n --> b )

  [ dup 1 = if done
    primefactors
    dup square iff
      [ drop 0 ] done
    size odd iff
      -1 else 1 ]        is mobius ( n --> n )

  say "First 199 terms:" cr
  say "    "
  199 times
    [ i^ 1+ mobius
      dup -1 > if sp
      echo
      i^ 1+ 20 mod
      19 = iff cr
      else [ sp sp ] ]
Output:
First 199 terms:
     1  -1  -1   0  -1   1  -1   0   0   1  -1   0  -1   1   1   0  -1   0  -1
 0   1   1  -1   0   0   1   0   0  -1  -1  -1   0   1   1   1   0  -1   1   1
 0  -1  -1  -1   0   0   1  -1   0   0   0   1   0  -1   0   1   0   1   1  -1
 0  -1   1   0   0   1  -1  -1   0   1  -1  -1   0  -1   1   0   0   1  -1  -1
 0   0   1  -1   0   1   1   1   0  -1   0   1   0   1   1   1   0  -1   0   0
 0  -1  -1  -1   0  -1   1  -1   0  -1  -1   1   0  -1  -1   1   0   0   1   1
 0   0   1   1   0   0   0  -1   0   1  -1  -1   0   1   1   0   0  -1  -1  -1
 0   1   1   1   0   1   1   0   0  -1   0  -1   0   0  -1   1   0  -1   1   1
 0   1   0  -1   0  -1   1  -1   0   0  -1   0   0  -1  -1   0   0   1   1  -1
 0  -1  -1   1   0   1  -1   1   0   0  -1  -1   0  -1   1  -1   0  -1   0  -1

Raku

(formerly Perl 6)

Works with: Rakudo version 2022.12

Möbius number is not defined for n == 0. Raku arrays are indexed from 0 so store a blank value at position zero to keep n and μ(n) aligned.

use Prime::Factor;

sub μ (Int \n) {
    return 0 if n %% (4|9|25|49|121);
    my @p = prime-factors(n);
    +@p == +@p.unique ?? +@p %% 2 ?? 1 !! -1 !! 0
}

my @möbius = lazy flat '', 1, (2..*).hyper.map: ;

# The Task
put "Möbius sequence - First 199 terms:\n",
    @möbius[^200]».fmt('%3s').batch(20).join: "\n";
Output:
Möbius sequence - First 199 terms:
      1  -1  -1   0  -1   1  -1   0   0   1  -1   0  -1   1   1   0  -1   0  -1
  0   1   1  -1   0   0   1   0   0  -1  -1  -1   0   1   1   1   0  -1   1   1
  0  -1  -1  -1   0   0   1  -1   0   0   0   1   0  -1   0   1   0   1   1  -1
  0  -1   1   0   0   1  -1  -1   0   1  -1  -1   0  -1   1   0   0   1  -1  -1
  0   0   1  -1   0   1   1   1   0  -1   0   1   0   1   1   1   0  -1   0   0
  0  -1  -1  -1   0  -1   1  -1   0  -1  -1   1   0  -1  -1   1   0   0   1   1
  0   0   1   1   0   0   0  -1   0   1  -1  -1   0   1   1   0   0  -1  -1  -1
  0   1   1   1   0   1   1   0   0  -1   0  -1   0   0  -1   1   0  -1   1   1
  0   1   0  -1   0  -1   1  -1   0   0  -1   0   0  -1  -1   0   0   1   1  -1
  0  -1  -1   1   0   1  -1   1   0   0  -1  -1   0  -1   1  -1   0  -1   0  -1

REXX

Note that the   Möbius   function is also spelled   Mobius   and/or   Moebius,   and it is also known as the   mu   function,   where   mu   is the Greek symbol   μ.

Programming note:   This REXX version supports the specifying of the low and high values to be generated,
as well as the group size for the grid   (it can be specified as   1   which will show a vertical list).

A null value will be shown as a bullet (•) when showing the Möbius value of for zero   (this can be changed in the 2nd line of the   mobius   function).

The above "feature" was added to make the grid to be aligned with other solutions.

The function to computer some prime numbers is a bit of an overkill, but the goal was to keep it general  (in case of larger/higher ranges for a Möbius sequence).

/*REXX pgm computes & shows a value grid of the Möbius function for a range of integers.*/
parse arg LO HI grp .                            /*obtain optional arguments from the CL*/
if  LO=='' |  LO==","  then  LO=   0             /*Not specified?  Then use the default.*/
if  HI=='' |  HI==","  then  HI= 199             /* "      "         "   "   "     "    */
if grp=='' | grp==","  then grp=  20             /* "      "         "   "   "     "    */
                                                 /*                            ______   */
call genP HI                                     /*generate primes up to the  √  HI     */
say center(' The Möbius sequence from ' LO " ──► " HI" ", max(50, grp*3), '═')   /*title*/
$=                                               /*variable holds output grid of GRP #s.*/
    do j=LO  to  HI;  $= $  right( mobius(j), 2) /*process some numbers from  LO ──► HI.*/
    if words($)==grp  then do;  say substr($, 2);  $=    /*show grid if fully populated,*/
                           end                           /*  and nullify it for more #s.*/
    end   /*j*/                                  /*for small grids, using wordCnt is OK.*/

if $\==''  then say substr($, 2)                 /*handle any residual numbers not shown*/
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
mobius: procedure expose @.;  parse arg x        /*obtain a integer to be tested for mu.*/
        if x<1  then return '∙'                  /*special? Then return symbol for null.*/
        #= 0                                     /*start with a value of zero.          */
             do k=1;  p= @.k                     /*get the  Kth  (pre─generated)  prime.*/
             if p>x  then leave                  /*prime (P)   > X?    Then we're done. */
             if p*p>x  then do;   #= #+1;  leave /*prime (P**2 > X?    Bump # and leave.*/
                            end
             if x//p==0  then do; #= #+1         /*X divisible by P?   Bump mu number.  */
                                  x= x % p       /*                    Divide by prime. */
                                  if x//p==0  then return 0  /*X÷by P?  Then return zero*/
                              end
             end   /*k*/                         /*#  (below) is almost always small, <9*/
        if #//2==0  then return  1               /*Is # even?   Then return postive  1  */
                         return -1               /* " "  odd?     "     "   negative 1. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
genP: @.1=2; @.2=3; @.3=5; @.4=7; @.5=11; @.6= 13;  nP=6  /*assign low primes; # primes.*/
                    do lim=nP  until lim*lim>=HI /*only keep primes up to the  sqrt(HI).*/
                    end   /*lim*/
       do j=@.nP+4  by 2  to HI                  /*only find odd primes from here on.   */
       parse var j '' -1 _;if _==5  then iterate /*Is last digit a "5"?   Then not prime*/
       if j// 3==0  then iterate                 /*is J divisible by  3?    "   "    "  */
       if j// 7==0  then iterate                 /* " "     "      "  7?    "   "    "  */
       if j//11==0  then iterate                 /* " "     "      " 11?    "   "    "  */
       if j//13==0  then iterate                 /* " "     "      " 13?    "   "    "  */
                 do k=7  while k*k<=j            /*divide by some generated odd primes. */
                 if j // @.k==0  then iterate j  /*Is J divisible by  P?  Then not prime*/
                 end   /*k*/                     /* [↓]  a prime  (J)  has been found.  */
       nP= nP+1;    if nP<=HI  then @.nP= j      /*bump prime count; assign prime to  @.*/
       end      /*j*/;              return
output   when using the default inputs:

Output note:   note the use of a bullet (•) to signify that a "null" is being shown (for the 0th entry).

══════════ The Möbius sequence from  0  ──►  199 ═══════════
 ∙  1 -1 -1  0 -1  1 -1  0  0  1 -1  0 -1  1  1  0 -1  0 -1
 0  1  1 -1  0  0  1  0  0 -1 -1 -1  0  1  1  1  0 -1  1  1
 0 -1 -1 -1  0  0  1 -1  0  0  0  1  0 -1  0  1  0  1  1 -1
 0 -1  1  0  0  1 -1 -1  0  1 -1 -1  0 -1  1  0  0  1 -1 -1
 0  0  1 -1  0  1  1  1  0 -1  0  1  0  1  1  1  0 -1  0  0
 0 -1 -1 -1  0 -1  1 -1  0 -1 -1  1  0 -1 -1  1  0  0  1  1
 0  0  1  1  0  0  0 -1  0  1 -1 -1  0  1  1  0  0 -1 -1 -1
 0  1  1  1  0  1  1  0  0 -1  0 -1  0  0 -1  1  0 -1  1  1
 0  1  0 -1  0 -1  1 -1  0  0 -1  0  0 -1 -1  0  0  1  1 -1
 0 -1 -1  1  0  1 -1  1  0  0 -1 -1  0 -1  1 -1  0 -1  0 -1

Ring

Translation of: FreeBASIC
mobStr = "      . "

for i = 1 to 200
    if mobius(i) >= 0
       mobStr + = " "
    ok
    temp = string(mobius(i))
    if left(temp,2) = "-0"
       temp = right(temp,len(temp)-1)
    ok
    mobStr += temp + " "
    if i % 10 = 9  
        see mobStr + nl
        mobStr = "     "
    ok
next

func mobius(n)
     if n = 1 
        return 1
     ok
     for d = 2 to ceil(sqrt(n))
         if n % d = 0  
            if n % (d*d) = 0
               return 0
            ok
            return -mobius(n/d)
         ok
     next 
     return -1

Output:

      .  1 -1 -1  0 -1  1 -1  0  0 
      1 -1  0 -1  1  1  0 -1  0 -1 
      0  1  1 -1  0  0  1  0  0 -1 
     -1 -1  0  1  1  1  0 -1  1  1 
      0 -1 -1 -1  0  0  1 -1  0  0 
      0  1  0 -1  0  1  0  1  1 -1 
      0 -1  1  0  0  1 -1 -1  0  1 
     -1 -1  0 -1  1  0  0  1 -1 -1 
      0  0  1 -1  0  1  1  1  0 -1 
      0  1  0  1  1  1  0 -1  0  0 
      0 -1 -1 -1  0 -1  1 -1  0 -1 
     -1  1  0 -1 -1  1  0  0  1  1 
      0  0  1  1  0  0  0 -1  0  1 
     -1 -1  0  1  1  0  0 -1 -1 -1 
      0  1  1  1  0  1  1  0  0 -1 
      0 -1  0  0 -1  1  0 -1  1  1 
      0  1  0 -1  0 -1  1 -1  0  0 
     -1  0  0 -1 -1  0  0  1  1 -1 
      0 -1 -1  1  0  1 -1  1  0  0 
     -1 -1  0 -1  1 -1  0 -1  0 -1 

RPL

Translation of: FreeBASIC

RPL does not allow that a function returns something whilst in the middle of a branch, so we have to play here with index saturation and flag use to mimic the short returns that many other languages accept.

Works with: Halcyon Calc version 4.2.7
RPL code Comment
IF DUP 1 ≠ THEN → n
   ≪ -1 
      2 n √ FOR d
         IF n d MOD NOT THEN
            1 CF IF n d SQ MOD NOT THEN 
               n 'd' STO DROP 0 1 SF END
            IF 1 FC? THEN
              DROP n d / n 'd' STO MU NEG END
         END
      NEXTEND
≫ 'MU' STO
MU ( n -- µ(n) )
   if n = 1 then return 1
   // default return value put in stack
   for d as uinteger = 2 to int(sqr(n))
       if n mod d = 0 then 
           if n mod (d*d) = 0 then 
               return 0 // and set flag
           // if flag not set,    
                 return -mobius(n/d)
        end if
   next d


≪ 1 100 FOR li "" li DUP 19 + FOR j "-0+" j MU 2 + DUP SUB + NEXT 20 STEP ≫ EVAL
Output:
5: "+--0-+-00+-0-++0-0-0" 
4: "++-00+00---0+++0-++0" 
3: "---00+-000+0-0+0++-0" 
2: "-+00+--0+--0-+00+--0" 
1: "0+-0+++0-0+0+++0-000" 
Works with: HP version 49/50

Improvement of an implementation found on the MoHPC forum

« CASE
    DUP 1 ≤ THEN END
    FACTOR DUP TYPE 9 ≠ THEN DROP -1 END
    DUP →STR "^" POS THEN DROP 0 END
    SIZE 1 + 2 / 1 SWAP 2 MOD { NEG } IFT
 END
» 'MU' STO

« 1 100 FOR j
     j 20 MOD 1 == "" IFT
     "-0+" j MU 2 + DUP SUB +
  NEXT
» 'TASK' STO

Same output.

Ruby

require 'prime'

def μ(n)
  pd = n.prime_division
  return 0 unless pd.map(&:last).all?(1)
  pd.size.even? ? 1 : -1
end

(["  "] + (1..199).map{|n|"%2s" % μ(n)}).each_slice(20){|line| puts line.join(" ") }
Output:
    1 -1 -1  0 -1  1 -1  0  0  1 -1  0 -1  1  1  0 -1  0 -1
 0  1  1 -1  0  0  1  0  0 -1 -1 -1  0  1  1  1  0 -1  1  1
 0 -1 -1 -1  0  0  1 -1  0  0  0  1  0 -1  0  1  0  1  1 -1
 0 -1  1  0  0  1 -1 -1  0  1 -1 -1  0 -1  1  0  0  1 -1 -1
 0  0  1 -1  0  1  1  1  0 -1  0  1  0  1  1  1  0 -1  0  0
 0 -1 -1 -1  0 -1  1 -1  0 -1 -1  1  0 -1 -1  1  0  0  1  1
 0  0  1  1  0  0  0 -1  0  1 -1 -1  0  1  1  0  0 -1 -1 -1
 0  1  1  1  0  1  1  0  0 -1  0 -1  0  0 -1  1  0 -1  1  1
 0  1  0 -1  0 -1  1 -1  0  0 -1  0  0 -1 -1  0  0  1  1 -1
 0 -1 -1  1  0  1 -1  1  0  0 -1 -1  0 -1  1 -1  0 -1  0 -1

Rust

fn moebius(mut x: u64) -> i8 {
    let mut prime_count = 0;

    // If x is divisible by the given factor this macro counts the factor and divides it out. 
    // It then returns zero if x is still divisible by the factor.
    macro_rules! divide_x_by {
        ($factor:expr) => {
            if x % $factor == 0 {
                x /= $factor;
                prime_count += 1;
                if x % $factor == 0 {
                    return 0;
                }
            }
        };
    }

    // Handle 2 and 3 separately,
    divide_x_by!(2);
    divide_x_by!(3);

    // then use a wheel sieve to check the remaining factors <= √x.
    for i in (5..=isqrt(x)).step_by(6) {
        divide_x_by!(i);
        divide_x_by!(i + 2);
    }

    // There can exist one prime factor larger than √x,
    // in that case we can check if x is still larger than one, and then count it.
    if x > 1 {
        prime_count += 1;
    }

    if prime_count % 2 == 0 {
        1
    } else {
        -1
    }
}

/// Returns the largest integer smaller than or equal to `√n`
const fn isqrt(n: u64) -> u64 {
    if n <= 1 {
        n
    } else {
        let mut x0 = u64::pow(2, n.ilog2() / 2 + 1);
        let mut x1 = (x0 + n / x0) / 2;
        while x1 < x0 {
            x0 = x1;
            x1 = (x0 + n / x0) / 2;
        }
        x0
    }
}

fn main() {
    const ROWS: u64 = 10;
    const COLS: u64 = 20;
    println!(
        "Values of the Möbius function, μ(x), for x between 0 and {}:",
        COLS * ROWS
    );
    for i in 0..ROWS {
        for j in 0..=COLS {
            let x = COLS * i + j;
            let μ = moebius(x);
            if μ >= 0 {
                // Print an extra space if there's no minus sign in front of the output
                // in order to align the numbers in a nice grid.
                print!(" ");
            }
            print!("{μ} ");
        }
        println!();
    }
    let x = u64::MAX;
    println!("\nμ({x}) = {}", moebius(x));
}
Output:
Values of the Möbius function, μ(x), for x between 0 and 200:
 0  1 -1 -1  0 -1  1 -1  0  0  1 -1  0 -1  1  1  0 -1  0 -1  0 
 0  1  1 -1  0  0  1  0  0 -1 -1 -1  0  1  1  1  0 -1  1  1  0
 0 -1 -1 -1  0  0  1 -1  0  0  0  1  0 -1  0  1  0  1  1 -1  0
 0 -1  1  0  0  1 -1 -1  0  1 -1 -1  0 -1  1  0  0  1 -1 -1  0
 0  0  1 -1  0  1  1  1  0 -1  0  1  0  1  1  1  0 -1  0  0  0
 0 -1 -1 -1  0 -1  1 -1  0 -1 -1  1  0 -1 -1  1  0  0  1  1  0
 0  0  1  1  0  0  0 -1  0  1 -1 -1  0  1  1  0  0 -1 -1 -1  0
 0  1  1  1  0  1  1  0  0 -1  0 -1  0  0 -1  1  0 -1  1  1  0
 0  1  0 -1  0 -1  1 -1  0  0 -1  0  0 -1 -1  0  0  1  1 -1  0
 0 -1 -1  1  0  1 -1  1  0  0 -1 -1  0 -1  1 -1  0 -1  0 -1  0

μ(18446744073709551615) = -1

Sidef

Built-in:

say moebius(53)    #=> -1
say moebius(54)    #=> 0
say moebius(55)    #=> 1

Simple implementation:

func μ(n) {
    var f = n.factor_exp.map { .tail }
    f.any { _ > 1 } ? 0 : ((-1)**f.sum)
}

with (199) { |n|
    say "Values of the Möbius function for numbers in the range 1..#{n}:"
    [' '] + (1..n->map(μ)) -> each_slice(20, {|*line|
        say line.map { '%2s' % _ }.join(' ')
    })
}
Output:
Values of the Möbius function for numbers in the range 1..199:
    1 -1 -1  0 -1  1 -1  0  0  1 -1  0 -1  1  1  0 -1  0 -1
 0  1  1 -1  0  0  1  0  0 -1 -1 -1  0  1  1  1  0 -1  1  1
 0 -1 -1 -1  0  0  1 -1  0  0  0  1  0 -1  0  1  0  1  1 -1
 0 -1  1  0  0  1 -1 -1  0  1 -1 -1  0 -1  1  0  0  1 -1 -1
 0  0  1 -1  0  1  1  1  0 -1  0  1  0  1  1  1  0 -1  0  0
 0 -1 -1 -1  0 -1  1 -1  0 -1 -1  1  0 -1 -1  1  0  0  1  1
 0  0  1  1  0  0  0 -1  0  1 -1 -1  0  1  1  0  0 -1 -1 -1
 0  1  1  1  0  1  1  0  0 -1  0 -1  0  0 -1  1  0 -1  1  1
 0  1  0 -1  0 -1  1 -1  0  0 -1  0  0 -1 -1  0  0  1  1 -1
 0 -1 -1  1  0  1 -1  1  0  0 -1 -1  0 -1  1 -1  0 -1  0 -1

Wren

Library: Wren-fmt
Library: Wren-math
import "./fmt" for Fmt
import "./math" for Int

var isSquareFree = Fn.new { |n|
    var i = 2
    while (i * i <= n) {
        if (n%(i*i) == 0) return false
        i = (i > 2) ? i + 2 : i + 1
    }
    return true
}

var mu = Fn.new { |n|
    if (n < 1) Fiber.abort("Argument must be a positive integer")
    if (n == 1) return 1
    var sqFree = isSquareFree.call(n)
    var factors = Int.primeFactors(n)
    if (sqFree && factors.count % 2 == 0) return 1
    if (sqFree) return -1
    return 0
}

System.print("The first 199 Möbius numbers are:")
for (i in 0..9) {
    for (j in 0..19) {
        if (i == 0 && j == 0) {
            System.write("    ")
        } else {
            Fmt.write("$ 3d ", mu.call(i*20 + j))
        }
    }
    System.print()
}
Output:
The first 199 Möbius numbers are:
      1  -1  -1   0  -1   1  -1   0   0   1  -1   0  -1   1   1   0  -1   0  -1 
  0   1   1  -1   0   0   1   0   0  -1  -1  -1   0   1   1   1   0  -1   1   1 
  0  -1  -1  -1   0   0   1  -1   0   0   0   1   0  -1   0   1   0   1   1  -1 
  0  -1   1   0   0   1  -1  -1   0   1  -1  -1   0  -1   1   0   0   1  -1  -1 
  0   0   1  -1   0   1   1   1   0  -1   0   1   0   1   1   1   0  -1   0   0 
  0  -1  -1  -1   0  -1   1  -1   0  -1  -1   1   0  -1  -1   1   0   0   1   1 
  0   0   1   1   0   0   0  -1   0   1  -1  -1   0   1   1   0   0  -1  -1  -1 
  0   1   1   1   0   1   1   0   0  -1   0  -1   0   0  -1   1   0  -1   1   1 
  0   1   0  -1   0  -1   1  -1   0   0  -1   0   0  -1  -1   0   0   1   1  -1 
  0  -1  -1   1   0   1  -1   1   0   0  -1  -1   0  -1   1  -1   0  -1   0  -1 

XPL0

func Mobius(N);
int  N, Cnt, F, K;
[Cnt:= 0;
F:= 2;  K:= 0;
repeat  if rem(N/F) = 0 then
                [Cnt:= Cnt+1;
                N:= N/F;
                K:= K+1;
                if K >= 2 then return 0;
                ]
        else    [F:= F+1;  K:= 0];
until   F > N;
return if Cnt&1 then -1 else 1;
];

int  N;
[Format(3, 0);
Text(0, "   ");
for N:= 1 to 199 do
        [RlOut(0, float(Mobius(N)));
        if rem(N/20) = 19 then CrLf(0);
        ];
]
Output:
     1 -1 -1  0 -1  1 -1  0  0  1 -1  0 -1  1  1  0 -1  0 -1
  0  1  1 -1  0  0  1  0  0 -1 -1 -1  0  1  1  1  0 -1  1  1
  0 -1 -1 -1  0  0  1 -1  0  0  0  1  0 -1  0  1  0  1  1 -1
  0 -1  1  0  0  1 -1 -1  0  1 -1 -1  0 -1  1  0  0  1 -1 -1
  0  0  1 -1  0  1  1  1  0 -1  0  1  0  1  1  1  0 -1  0  0
  0 -1 -1 -1  0 -1  1 -1  0 -1 -1  1  0 -1 -1  1  0  0  1  1
  0  0  1  1  0  0  0 -1  0  1 -1 -1  0  1  1  0  0 -1 -1 -1
  0  1  1  1  0  1  1  0  0 -1  0 -1  0  0 -1  1  0 -1  1  1
  0  1  0 -1  0 -1  1 -1  0  0 -1  0  0 -1 -1  0  0  1  1 -1
  0 -1 -1  1  0  1 -1  1  0  0 -1 -1  0 -1  1 -1  0 -1  0 -1

zkl

fcn mobius(n){
   pf:=primeFactors(n);
   sq:=pf.filter1('wrap(f){ (n % (f*f))==0 });  // False if square free
   if(sq==False){ if(pf.len().isEven) 1 else -1 }
   else 0
}
fcn primeFactors(n){  // Return a list of prime factors of n
   acc:=fcn(n,k,acc,maxD){  // k is 2,3,5,7,9,... not optimum
      if(n==1 or k>maxD) acc.close();
      else{
	 q,r:=n.divr(k);   // divr-->(quotient,remainder)
	 if(r==0) return(self.fcn(q,k,acc.write(k),q.toFloat().sqrt()));
	 return(self.fcn(n,k+1+k.isOdd,acc,maxD))  # both are tail recursion
      }
   }(n,2,Sink(List),n.toFloat().sqrt());
   m:=acc.reduce('*,1);      // mulitply factors
   if(n!=m) acc.append(n/m); // opps, missed last factor
   else acc;
}
[1..199].apply(mobius)
.pump(Console.println, T(Void.Read,19,False),
	fcn{ vm.arglist.pump(String,"%3d".fmt) });
Output:
  1 -1 -1  0 -1  1 -1  0  0  1 -1  0 -1  1  1  0 -1  0 -1  0
  1  1 -1  0  0  1  0  0 -1 -1 -1  0  1  1  1  0 -1  1  1  0
 -1 -1 -1  0  0  1 -1  0  0  0  1  0 -1  0  1  0  1  1 -1  0
 -1  1  0  0  1 -1 -1  0  1 -1 -1  0 -1  1  0  0  1 -1 -1  0
  0  1 -1  0  1  1  1  0 -1  0  1  0  1  1  1  0 -1  0  0  0
 -1 -1 -1  0 -1  1 -1  0 -1 -1  1  0 -1 -1  1  0  0  1  1  0
  0  1  1  0  0  0 -1  0  1 -1 -1  0  1  1  0  0 -1 -1 -1  0
  1  1  1  0  1  1  0  0 -1  0 -1  0  0 -1  1  0 -1  1  1  0
  1  0 -1  0 -1  1 -1  0  0 -1  0  0 -1 -1  0  0  1  1 -1  0
 -1 -1  1  0  1 -1  1  0  0 -1 -1  0 -1  1 -1  0 -1  0 -1