Mertens function: Difference between revisions
m
syntax highlighting fixup automation
Alpha bravo (talk | contribs) (Added AutoHotkey) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 36:
{{trans|Python}}
<
‘Generate Mertens numbers’
V m = [-1, 1]
Line 60:
V crosses = sum(zip(ms, ms[1..]).map((a, b) -> Int(a != 0 & b == 0)))
print(‘M(N) equals zero #. times.’.format(zeroes))
print(‘M(N) crosses zero #. times.’.format(crosses))</
{{out}}
Line 80:
=={{header|8080 Assembly}}==
<
org 100h
;;; Generate Mertens numbers
Line 278:
tms: db ' times.$'
;;; Numbers are stored page-aligned after program
MM: equ ($/256)*256+256 </
{{out}}
Line 297:
=={{header|8086 Assembly}}==
<
puts: equ 9 ; MS-DOS syscall to print a string
putch: equ 2 ; MS-DOS syscall to print a character
Line 398:
section .bss
mm: resb MAX ; Mertens numbers
M: equ mm-1 ; 1-based indexing</
{{out}}
Line 419:
Calculations on a real Atari 8-bit computer take quite long time. It is recommended to use an emulator capable with increasing speed of Atari CPU.
{{libheader|Action! Tool Kit}}
<
PROC MertensNumbers(INT ARRAY m INT count)
Line 476:
PrintF("%EM(n) is zero %I times for 1<=n<=%I.%E",zeroCnt,MAX-1)
PrintF("%EM(n) crosses zero %I times for 1<=n<=%I.%E",crossCnt,MAX-1)
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Mertens_function.png Screenshot from Atari 8-bit computer]
Line 501:
...which is...
{{Trans|Fortran}}
<
# Generate Mertens numbers #
[ 1 : 1000 ]INT m;
Line 532:
print( ( "M(N) is zero ", whole( zero, -4 ), " times.", newline ) );
print( ( "M(N) crosses zero ", whole( cross, -4 ), " times.", newline ) )
END</
{{out}}
<pre>
Line 553:
=={{header|ALGOL W}}==
{{Trans|Fortran}}
<
integer array M ( 1 :: 1000 );
integer k, zero, cross;
Line 585:
write( i_w := 2, s_w := 0, "M(N) is zero ", zero, " times." );
write( i_w := 2, s_w := 0, "M(N) crosses zero ", cross, " times." )
end.</
{{out}}
<pre>
Line 606:
=={{header|APL}}==
{{works with|Dyalog APL}}
<
step ← {⍵,-⍨/⌽1,⍵[⌊n÷1↓⍳n←1+≢⍵]}
m1000 ← step⍣999⊢,1
Line 615:
⎕←'M(N) is zero ',(⍕zero),' times.'
⎕←'M(N) crosses zero ',(⍕cross),' times.'
}</
{{out}}
Line 635:
=={{header|Arturo}}==
<
if n=0 -> return ""
if n=1 -> return 1
Line 659:
crossed: new 0
fold mertens1000 [a,b][if and? zero? b not? zero? a -> inc 'crossed, b]
print ["Times M(x) crosses zero between 1 and 1000:" crossed]</
{{out}}
Line 674:
=={{header|AutoHotkey}}==
<
loop 100
result .= SubStr(" " Mertens(A_Index), -1) . (Mod(A_Index, 10) ? " " : "`n")
Line 736:
ans.push(Format("{:d}", n))
return ans
}</
{{out}}
<pre>first 100 terms:
Line 762:
a little over 1 hour on the 8086 (using GWBASIC).
<
20 M(1)=1
30 FOR N=2 TO 1000
Line 780:
170 PRINT "M(N) is zero";Z;"times."
180 PRINT "M(N) crosses zero";C;"times."
190 END</
{{out}}
Line 799:
=={{header|Bash}}==
<
MAX=1000
Line 832:
echo "M(N) is zero $zero times."
echo "M(N) crosses zero $cross times."</
{{out}}
Line 851:
=={{header|BCPL}}==
<
manifest $( limit = 1000 $)
Line 886:
writef("M(N) is zero %N times.*N", eqz)
writef("M(N) crosses zero %N times.*N", crossz)
$)</
{{out}}
<pre>The first 99 Mertens numbers are:
Line 903:
=={{header|C}}==
<
#include <stdlib.h>
Line 955:
printf("M(n) crosses zero %d times for 1 <= n <= %d.\n", cross, max);
return 0;
}</
{{out}}
Line 975:
=={{header|C++}}==
<
#include <iostream>
#include <vector>
Line 1,017:
std::cout << "M(n) crosses zero " << cross << " times for 1 <= n <= 1000.\n";
return 0;
}</
{{out}}
Line 1,037:
=={{header|CLU}}==
<
mertens = proc (limit: int) returns (array[int])
M: array[int] := array[int]$fill(1,limit,0)
Line 1,078:
stream$putl(po, "M(N) is zero " || int$unparse(eqz) || " times.")
stream$putl(po, "M(N) crosses zero " || int$unparse(crossz) || " times.")
end start_up</
{{out}}
<pre>The first 99 Mertens numbers are:
Line 1,095:
=={{header|COBOL}}==
<
PROGRAM-ID. MERTENS.
Line 1,160:
SUBTRACT 1 FROM N GIVING K,
IF M(K) IS NOT EQUAL TO ZERO,
ADD 1 TO CROSS-ZERO.</
{{out}}
<pre>The first 99 Mertens numbers are:
Line 1,177:
=={{header|Cowgol}}==
<
const MAX := 1000;
Line 1,239:
print("M(n) is zero "); print_i8(zero); print(" times\n");
print("M(n) crosses zero "); print_i8(cross); print(" times\n");</
{{out}}
Line 1,260:
{{libheader| System.SysUtils}}
{{Trans|Go}}
<syntaxhighlight lang="delphi">
program Mertens_function;
Line 1,355:
writeln(#10'Crosses zero ', m.crosses, ' times between 1 and 1000');
{$IFNDEF UNIX} readln; {$ENDIF}
end.</
=={{header|Draco}}==
<
word n,k;
m[1] := 1;
Line 1,395:
writeln("M(N) is zero ",eqz," times.");
writeln("M(N) crosses zero ",crossz," times.")
corp</
{{out}}
<pre>The first 99 Mertens numbers are:
Line 1,415:
{{trans|Swift}}
<
let mertens = Array.Empty(max + 1, 1)
for n in 2..max {
Line 1,455:
print("M(n) is zero \(zero) times for 1 <= n <= \(max).")
print("M(n) crosses zero \(cross) times for 1 <= n <= \(max).")</
{{out}}
Line 1,475:
=={{header|F_Sharp|F#}}==
This task uses [http://www.rosettacode.org/wiki/Möbius_function#F.23 Möbius_function (F#)]
<
// Mertens function. Nigel Galloway: January 31st., 2021
let mertens=mobius|>Seq.scan((+)) 0|>Seq.tail
Line 1,483:
printfn "%d Zeroes\n####" (Seq.length (snd n.[0]))
printfn "Crosses zero %d times" (mertens|>Seq.take 1000|>Seq.pairwise|>Seq.sumBy(fun(n,g)->if n<>0 && g=0 then 1 else 0)))
</syntaxhighlight>
{{out}}
<pre>
Line 1,535:
=={{header|Factor}}==
{{works with|Factor|0.99 2020-01-23}}
<
math.ranges math.statistics prettyprint sequences ;
Line 1,552:
2 <clumps> [ first2 [ 0 = not ] [ zero? ] bi* and ] count bl
pprint bl "zero crossings." print
] bi</
{{out}}
<pre>
Line 1,573:
=={{header|Forth}}==
<
variable mertens AMOUNT cells allot
Line 1,623:
." M(N) is zero " . ." times." cr
." M(N) crosses zero " . ." times." cr
bye </
{{out}}
Line 1,642:
=={{header|Fortran}}==
<
implicit none
integer M(1000), n, k, zero, cross
Line 1,681:
50 format("M(N) crosses zero ",I2," times.")
write (*,50) cross
end program</
{{out}}
Line 1,700:
=={{header|FreeBASIC}}==
<
return wspace(i-len(str(j)))+str(j)
end function
Line 1,733:
outstr = ""
end if
next n</
{{out}}
<pre>
Line 1,752:
=={{header|Go}}==
<
import "fmt"
Line 1,817:
fmt.Println("\n\nEquals zero", zeros, "times between 1 and 1000")
fmt.Println("\nCrosses zero", crosses, "times between 1 and 1000")
}</
{{out}}
Line 1,839:
=={{header|Haskell}}==
<
import qualified Data.MemoCombinators as Memo
import Math.NumberTheory.Primes (unPrime, factorise)
Line 1,872:
mapM_ (\row -> mapM_ (printf "%3d" . mertens) row >> printf "\n") $ chunksOf 10 [10..99]
printf "\nM(n) is zero %d times for 1 <= n <= 1000.\n" $ countZeros [1..1000]
printf "M(n) crosses zero %d times for 1 <= n <= 1000.\n" $ crossesZero [1..1000]</
{{out}}
<pre>The first 99 terms for M(1..99):
Line 1,891:
=={{header|J}}==
<
M =: +/@([: mu 1:+i.)
Line 1,902:
echo 'M(N) is zero ',(":zero),' times.'
echo 'M(N) crosses zero ',(":cross),' times.'
exit''</
{{out}}
Line 1,921:
=={{header|Java}}==
<
public class MertensFunction {
Line 2,031:
}
</syntaxhighlight>
{{out}}
Line 2,110:
'''Preliminaries'''
<syntaxhighlight lang="jq">
def sum(s): reduce s as $x (null; . + $x);
Line 2,129:
end
| .prev = $a[$i] )
| .count;</
'''Mertens Numbers'''
<syntaxhighlight lang="jq">
# Input: $max >= 1
# Output: an array of size $max with $max mertenNumbers beginning with 1
Line 2,139:
.[$n-1]=1
| reduce range(2; $n+1) as $k (.;
.[$n-1] -= .[($n / $k) | floor - 1] ));</
'''The Tasks'''
<
def mertens_number:
mertensNumbers[.-1];
Line 2,164:
(1000 | (task2, task3))
</syntaxhighlight>
{{out}}
<pre>
Line 2,186:
=={{header|Julia}}==
The OEIS A002321 reference suggests the Mertens function has a negative bias, which it does below 1 million, but this bias seems to switch to a positive bias by 1 billion. There may simply be large swings in the bias overall, which get larger and longer as the sequence continues.
<
function moebius(n::Integer)
Line 2,243:
foreach(maximinM, (1000, 1_000_000, 1_000_000_000))
</
<pre>
First 99 terms of the Mertens function for positive integers:
Line 2,286:
=={{header|MAD}}==
<
DIMENSION M(1000)
Line 2,318:
PRINT FORMAT FC, CROSS
END OF PROGRAM </
{{out}}
Line 2,337:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
Mertens[n_] := Total[MoebiusMu[Range[n]]]
Grid[Partition[Mertens /@ Range[99], UpTo[10]]]
Count[Mertens /@ Range[1000], 0]
SequenceCount[Mertens /@ Range[1000], {Except[0], 0}]</
{{out}}
<pre>1 0 -1 -1 -2 -1 -2 -2 -2 -1
Line 2,357:
=={{header|Modula-2}}==
<
FROM InOut IMPORT WriteString, WriteInt, WriteCard, WriteLn;
Line 2,403:
WriteString(" times.");
WriteLn();
END Mertens.</
{{out}}
<pre>The first 99 Mertens numbers are:
Line 2,421:
=={{header|Nim}}==
{{trans|C}}
<
func mertensNumbers(max: int): seq[int] =
Line 2,454:
echo ""
echo &"M(n) is zero {zero} times for 1 ⩽ n ⩽ {Max}."
echo &"M(n) crosses zero {cross} times for 1 ⩽ n ⩽ {Max}."</
{{out}}
Line 2,475:
Nearly the same as [[Square-free_integers#Pascal]]
Instead here marking all multiples, starting at factor 2, of a prime by incrementing the factor count.<BR> runtime ~log(n)*n
<
{$IFDEF FPC}
{$MODE DELPHI}
Line 2,699:
setlength(primes,0);
setlength(sieve,0);
end.</
{{out}}
<pre>[1 to limit]
Line 2,761:
=={{header|Perl}}==
<
use strict;
use warnings;
Line 2,793:
(' 'x4 . sprintf "@{['%4d' x $show]}", @mertens[0..$show-1]) =~ s/((.){80})/$1\n/gr .
sprintf("\nEquals zero %3d times between 1 and $upto", scalar grep { ! $_ } @mertens) .
sprintf "\nCrosses zero%3d times between 1 and $upto", scalar grep { ! $mertens[$_-1] and $mertens[$_] } 1 .. @mertens;</
{{out}}
<pre>Mertens sequence - First 199 terms:
Line 2,812:
=={{header|Phix}}==
Based on the stackexchange link, short and sweet but not very fast: 1.4s just for the first 1000...
<!--<
<span style="color: #008080;">function</span> <span style="color: #000000;">Mertens</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: #004080;">integer</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
Line 2,834:
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\nMertens[1..1000] equals zero %d times and crosses zero %d times\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">zeroes</span><span style="color: #0000FF;">,</span><span style="color: #000000;">crosses</span><span style="color: #0000FF;">})</span>
<!--</
{{out}}
Matches the wp table:
Line 2,855:
=={{header|PL/I}}==
<
%replace MAX by 1000;
Line 2,889:
put skip list('Zeroes: ',isZero);
put skip list('Crossings:',crossZero);
end mertens;</
{{out}}
<pre>The first 99 Mertens numbers are:
Line 2,908:
=={{header|Prolog}}==
{{works with|SWI Prolog}}
<
mertens_number(1, 1):- !.
Line 2,965:
count_zeros(1, 1000, Z, C),
writef('M(n) is zero %t times for 1 <= n <= 1000.\n', [Z]),
writef('M(n) crosses zero %t times for 1 <= n <= 1000.\n', [C]).</
{{out}}
Line 2,985:
=={{header|PureBasic}}==
<
M(1)=1
Line 2,998:
For n=1 To 99 : Print(RSet(Str(M(n)),4)) : If n%10=9 : PrintN("") : EndIf : Next
PrintN("M(N) is zero "+Str(z)+" times.") : PrintN("M(N) crosses zero "+Str(c)+" times.")
Input()</
{{out}}
<pre>First 99 Mertens numbers:
Line 3,015:
=={{header|Python}}==
<
"""Generate Mertens numbers"""
m = [None, 1]
Line 3,040:
crosses = sum(a!=0 and b==0 for a,b in zip(ms, ms[1:]))
print("M(N) equals zero {} times.".format(zeroes))
print("M(N) crosses zero {} times.".format(crosses))</
{{out}}
Line 3,063:
Mertens number is not defined for n == 0. Raku arrays are indexed from 0 so store a blank value at position zero to keep x and M(x) aligned.
<syntaxhighlight lang="raku"
sub μ (Int \n) {
Line 3,083:
printf "%4d: M(%d)\n", -$threshold, @mertens.first: * == -$threshold, :k;
printf "%4d: M(%d)\n", $threshold, @mertens.first: * == $threshold, :k;
}</
{{out}}
<pre>Mertens sequence - First 199 terms:
Line 3,135:
The above "feature" was added to make the grid to be aligned with other solutions.
<
parse arg LO HI grp eqZ xZ . /*obtain optional arguments from the CL*/
if LO=='' | LO=="," then LO= 0 /*Not specified? Then use the default.*/
Line 3,195:
end /*k*/ /* [↓] a prime (J) has been found. */
#= #+1; @.#=j; sq.j= j*j /*bump P count; P──►@.; compute J**2*/
end /*j*/; return /*calculate the squares of some primes.*/</
{{out|output|text= when using the default inputs:}}
Line 3,218:
=={{header|Ruby}}==
<
def μ(n)
Line 3,236:
puts "\nThe Mertens function is zero #{ar.count(0)} times in the range (1..1000);"
puts "it crosses zero #{ar.each_cons(2).count{|m1, m2| m1 != 0 && m2 == 0}} times."
</syntaxhighlight>
{{out}}
<pre> 1 0 -1 -1 -2 -1 -2 -2 -2 -1 -2 -2 -3 -2 -1 -1 -2 -2 -3
Line 3,255:
=={{header|Sidef}}==
Built-in:
<
say mertens(1234567890) #=> 9163</
Algorithm for computing M(n) in sublinear time:
<
var lookup_size = (2 * n.iroot(3)**2)
Line 3,294:
cache{n} = M
}(n)
}</
Task:
<
say "Mertens function in the range 1..#{n}:"
(1..n).map { mertens(_) }.slices(20).each {|line|
Line 3,308:
say (1..n->count_by { mertens(_)==0 }, " zeros")
say (1..n->count_by { mertens(_)==0 && mertens(_-1)!=0 }, " zero crossings")
}</
{{out}}
<pre>
Line 3,330:
=={{header|Swift}}==
{{trans|C}}
<
func mertensNumbers(max: Int) -> [Int] {
Line 3,370:
}
print("M(n) is zero \(zero) times for 1 <= n <= \(max).")
print("M(n) crosses zero \(cross) times for 1 <= n <= \(max).")</
{{out}}
Line 3,391:
=={{header|Vlang}}==
{{trans|go}}
<
mut to:=t
if to < 1 {
Line 3,455:
println("\n\nEquals zero $zeros times between 1 and 1000")
println("\nCrosses zero $crosses times between 1 and 1000")
}</
{{out}}
Line 3,479:
{{libheader|Wren-fmt}}
{{libheader|Wren-math}}
<
import "/math" for Int
Line 3,531:
prev = next
}
System.print("\nThe Mertens function crosses zero %(count) times in the range [1, 1000].")</
{{out}}
Line 3,553:
=={{header|zkl}}==
<
[1..].tweak(fcn(n,pm){
pm.incN(mobius(n));
Line 3,577:
if(n!=m) acc.append(n/m); // opps, missed last factor
else acc;
}</
<
.pump(Console.println, T(Void.Read,19,False),
fcn{ vm.arglist.pump(String,"%3d".fmt) });
Line 3,586:
otm.reduce(fcn(s,m){ s + (m==0) },0) : println(_," zeros");
otm.reduce(fcn(p,m,rs){ rs.incN(m==0 and p!=0); m }.fp2( s:=Ref(0) ));
println(s.value," zero crossings");</
{{out}}
<pre>
|