Mertens function: Difference between revisions

m
syntax highlighting fixup automation
(Added AutoHotkey)
m (syntax highlighting fixup automation)
Line 36:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F mertens(count)
‘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))</langsyntaxhighlight>
 
{{out}}
Line 80:
 
=={{header|8080 Assembly}}==
<langsyntaxhighlight lang="8080asm">MAX: equ 1000 ; Amount of numbers to generate
org 100h
;;; Generate Mertens numbers
Line 278:
tms: db ' times.$'
;;; Numbers are stored page-aligned after program
MM: equ ($/256)*256+256 </langsyntaxhighlight>
 
{{out}}
Line 297:
 
=={{header|8086 Assembly}}==
<langsyntaxhighlight lang="asm">MAX: equ 1000 ; Amount of Mertens numbers to generate
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</langsyntaxhighlight>
 
{{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}}
<langsyntaxhighlight Actionlang="action!">INCLUDE "D2:PRINTF.ACT" ;from the 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</langsyntaxhighlight>
{{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}}
<langsyntaxhighlight lang="algol68">BEGIN # compute values of the Mertens function #
# 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</langsyntaxhighlight>
{{out}}
<pre>
Line 553:
=={{header|ALGOL W}}==
{{Trans|Fortran}}
<langsyntaxhighlight lang="algolw">begin % compute values of the Mertens function %
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.</langsyntaxhighlight>
{{out}}
<pre>
Line 606:
=={{header|APL}}==
{{works with|Dyalog APL}}
<langsyntaxhighlight APLlang="apl">mertens←{
step ← {⍵,-⍨/⌽1,⍵[⌊n÷1↓⍳n←1+≢⍵]}
m1000 ← step⍣999⊢,1
Line 615:
⎕←'M(N) is zero ',(⍕zero),' times.'
⎕←'M(N) crosses zero ',(⍕cross),' times.'
}</langsyntaxhighlight>
 
{{out}}
Line 635:
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">mobius: function [n][
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]</langsyntaxhighlight>
 
{{out}}
Line 674:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">result := "first 100 terms:`n"
loop 100
result .= SubStr(" " Mertens(A_Index), -1) . (Mod(A_Index, 10) ? " " : "`n")
Line 736:
ans.push(Format("{:d}", n))
return ans
}</langsyntaxhighlight>
{{out}}
<pre>first 100 terms:
Line 762:
a little over 1 hour on the 8086 (using GWBASIC).
 
<langsyntaxhighlight BASIClang="basic">10 DEFINT C,Z,N,K,M: DIM M(1000)
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</langsyntaxhighlight>
 
{{out}}
Line 799:
 
=={{header|Bash}}==
<langsyntaxhighlight lang="bash">#!/bin/bash
MAX=1000
 
Line 832:
 
echo "M(N) is zero $zero times."
echo "M(N) crosses zero $cross times."</langsyntaxhighlight>
 
{{out}}
Line 851:
 
=={{header|BCPL}}==
<langsyntaxhighlight lang="bcpl">get "libhdr"
 
manifest $( limit = 1000 $)
Line 886:
writef("M(N) is zero %N times.*N", eqz)
writef("M(N) crosses zero %N times.*N", crossz)
$)</langsyntaxhighlight>
{{out}}
<pre>The first 99 Mertens numbers are:
Line 903:
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
 
Line 955:
printf("M(n) crosses zero %d times for 1 <= n <= %d.\n", cross, max);
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 975:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <iomanip>
#include <iostream>
#include <vector>
Line 1,017:
std::cout << "M(n) crosses zero " << cross << " times for 1 <= n <= 1000.\n";
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 1,037:
 
=={{header|CLU}}==
<langsyntaxhighlight lang="clu">% Generate Mertens numbers up to a given limit
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</langsyntaxhighlight>
{{out}}
<pre>The first 99 Mertens numbers are:
Line 1,095:
 
=={{header|COBOL}}==
<langsyntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
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.</langsyntaxhighlight>
{{out}}
<pre>The first 99 Mertens numbers are:
Line 1,177:
 
=={{header|Cowgol}}==
<langsyntaxhighlight lang="cowgol">include "cowgol.coh";
 
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");</langsyntaxhighlight>
 
{{out}}
Line 1,260:
{{libheader| System.SysUtils}}
{{Trans|Go}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Mertens_function;
 
Line 1,355:
writeln(#10'Crosses zero ', m.crosses, ' times between 1 and 1000');
{$IFNDEF UNIX} readln; {$ENDIF}
end.</langsyntaxhighlight>
 
=={{header|Draco}}==
<langsyntaxhighlight lang="draco">proc nonrec mertens([*] short m) void:
word n,k;
m[1] := 1;
Line 1,395:
writeln("M(N) is zero ",eqz," times.");
writeln("M(N) crosses zero ",crossz," times.")
corp</langsyntaxhighlight>
{{out}}
<pre>The first 99 Mertens numbers are:
Line 1,415:
{{trans|Swift}}
 
<langsyntaxhighlight lang="dyalect">func mertensNumbers(max) {
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).")</langsyntaxhighlight>
 
{{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#)]
<langsyntaxhighlight lang="fsharp">
// 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>
</lang>
{{out}}
<pre>
Line 1,535:
=={{header|Factor}}==
{{works with|Factor|0.99 2020-01-23}}
<langsyntaxhighlight lang="factor">USING: formatting grouping io kernel math math.extras
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</langsyntaxhighlight>
{{out}}
<pre>
Line 1,573:
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">: AMOUNT 1000 ;
 
variable mertens AMOUNT cells allot
Line 1,623:
." M(N) is zero " . ." times." cr
." M(N) crosses zero " . ." times." cr
bye </langsyntaxhighlight>
 
{{out}}
Line 1,642:
 
=={{header|Fortran}}==
<langsyntaxhighlight Fortranlang="fortran"> program Mertens
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</langsyntaxhighlight>
 
{{out}}
Line 1,700:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">function padto( i as ubyte, j as integer ) as string
return wspace(i-len(str(j)))+str(j)
end function
Line 1,733:
outstr = ""
end if
next n</langsyntaxhighlight>
{{out}}
<pre>
Line 1,752:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
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")
}</langsyntaxhighlight>
 
{{out}}
Line 1,839:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Data.List.Split (chunksOf)
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]</langsyntaxhighlight>
{{out}}
<pre>The first 99 terms for M(1..99):
Line 1,891:
 
=={{header|J}}==
<langsyntaxhighlight Jlang="j">mu =: 0:`(1 - 2 * 2|#@{.)@.(1: = */@{:)@(2&p:)"0
M =: +/@([: mu 1:+i.)
 
Line 1,902:
echo 'M(N) is zero ',(":zero),' times.'
echo 'M(N) crosses zero ',(":cross),' times.'
exit''</langsyntaxhighlight>
 
{{out}}
Line 1,921:
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">
public class MertensFunction {
 
Line 2,031:
 
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,110:
 
'''Preliminaries'''
<syntaxhighlight lang="jq">
<lang jq>
def sum(s): reduce s as $x (null; . + $x);
 
Line 2,129:
end
| .prev = $a[$i] )
| .count;</langsyntaxhighlight>
'''Mertens Numbers'''
<syntaxhighlight lang="jq">
<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] ));</langsyntaxhighlight>
'''The Tasks'''
<langsyntaxhighlight lang="jq"># Task 0:
def mertens_number:
mertensNumbers[.-1];
Line 2,164:
(1000 | (task2, task3))
 
</syntaxhighlight>
</lang>
{{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.
<langsyntaxhighlight lang="julia">using Primes, Formatting
 
function moebius(n::Integer)
Line 2,243:
 
foreach(maximinM, (1000, 1_000_000, 1_000_000_000))
</langsyntaxhighlight>{{out}}
<pre>
First 99 terms of the Mertens function for positive integers:
Line 2,286:
 
=={{header|MAD}}==
<langsyntaxhighlight MADlang="mad"> NORMAL MODE IS INTEGER
DIMENSION M(1000)
Line 2,318:
PRINT FORMAT FC, CROSS
END OF PROGRAM </langsyntaxhighlight>
 
{{out}}
Line 2,337:
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">ClearAll[Mertens]
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}]</langsyntaxhighlight>
{{out}}
<pre>1 0 -1 -1 -2 -1 -2 -2 -2 -1
Line 2,357:
 
=={{header|Modula-2}}==
<langsyntaxhighlight lang="modula2">MODULE Mertens;
FROM InOut IMPORT WriteString, WriteInt, WriteCard, WriteLn;
 
Line 2,403:
WriteString(" times.");
WriteLn();
END Mertens.</langsyntaxhighlight>
{{out}}
<pre>The first 99 Mertens numbers are:
Line 2,421:
=={{header|Nim}}==
{{trans|C}}
<langsyntaxhighlight Nimlang="nim">import sequtils, strformat
 
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}."</langsyntaxhighlight>
 
{{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
<langsyntaxhighlight lang="pascal">program Merten;
{$IFDEF FPC}
{$MODE DELPHI}
Line 2,699:
setlength(primes,0);
setlength(sieve,0);
end.</langsyntaxhighlight>
{{out}}
<pre>[1 to limit]
Line 2,761:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use utf8;
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;</langsyntaxhighlight>
{{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...
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<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>
<!--</langsyntaxhighlight>-->
{{out}}
Matches the wp table:
Line 2,855:
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">mertens: procedure options(main);
%replace MAX by 1000;
Line 2,889:
put skip list('Zeroes: ',isZero);
put skip list('Crossings:',crossZero);
end mertens;</langsyntaxhighlight>
{{out}}
<pre>The first 99 Mertens numbers are:
Line 2,908:
=={{header|Prolog}}==
{{works with|SWI Prolog}}
<langsyntaxhighlight lang="prolog">:- dynamic mertens_number_cache/2.
 
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]).</langsyntaxhighlight>
 
{{out}}
Line 2,985:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Dim M.i(1000)
 
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()</langsyntaxhighlight>
{{out}}
<pre>First 99 Mertens numbers:
Line 3,015:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">def mertens(count):
"""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))</langsyntaxhighlight>
 
{{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" perl6line>use Prime::Factor;
 
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;
}</langsyntaxhighlight>
{{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.
<langsyntaxhighlight lang="rexx">/*REXX pgm computes & shows a value grid of the Mertens function for a range of integers*/
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.*/</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
 
Line 3,218:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">require 'prime'
 
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>
</lang>
{{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:
<langsyntaxhighlight lang="ruby">say mertens(123456789) #=> 1170
say mertens(1234567890) #=> 9163</langsyntaxhighlight>
 
Algorithm for computing M(n) in sublinear time:
 
<langsyntaxhighlight lang="ruby">func mertens(n) is cached {
 
var lookup_size = (2 * n.iroot(3)**2)
Line 3,294:
cache{n} = M
}(n)
}</langsyntaxhighlight>
 
Task:
<langsyntaxhighlight lang="ruby">with (200) {|n|
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")
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,330:
=={{header|Swift}}==
{{trans|C}}
<langsyntaxhighlight lang="swift">import Foundation
 
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).")</langsyntaxhighlight>
 
{{out}}
Line 3,391:
=={{header|Vlang}}==
{{trans|go}}
<langsyntaxhighlight lang="vlang">fn mertens(t int) ([]int, int, int) {
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")
}</langsyntaxhighlight>
 
{{out}}
Line 3,479:
{{libheader|Wren-fmt}}
{{libheader|Wren-math}}
<langsyntaxhighlight lang="ecmascript">import "/fmt" for Fmt
import "/math" for Int
 
Line 3,531:
prev = next
}
System.print("\nThe Mertens function crosses zero %(count) times in the range [1, 1000].")</langsyntaxhighlight>
 
{{out}}
Line 3,553:
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn mertensW(n){
[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;
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">mertensW().walk(199)
.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");</langsyntaxhighlight>
{{out}}
<pre>
10,333

edits