Program for Mobius Function | Set 2 | Javascript implementation of the approach ; Function to calculate least prime factor of each number ; If it is a prime number ; For all multiples which are not visited yet . ; Function to find the value of Mobius function for all the numbers from 1 to n ; To store the values of Mobius function ; If number is one ; If number has a squared prime factor ; Multiply - 1 with the previous number ; Driver code ; Function to find least prime factor ; Function to find mobius function
const N = 100005 ; let lpf = new Array ( N ) ; function least_prime_factor ( ) { for ( let i = 2 ; i < N ; i ++ ) if ( ! lpf [ i ] ) for ( let j = i ; j < N ; j += i ) if ( ! lpf [ j ] ) lpf [ j ] = i ; } function Mobius ( n ) { let mobius = new Array ( N ) ; for ( let i = 1 ; i < N ; i ++ ) { if ( i == 1 ) mobius [ i ] = 1 ; else { if ( lpf [ parseInt ( i / lpf [ i ] ) ] == lpf [ i ] ) mobius [ i ] = 0 ; else mobius [ i ] = - 1 * mobius [ parseInt ( i / lpf [ i ] ) ] ; } } for ( let i = 1 ; i <= n ; i ++ ) document . write ( mobius [ i ] + " " ) ; } let n = 5 ; least_prime_factor ( ) ; Mobius ( n ) ;