UNPKG

@algorithm.ts/sieve-totient

Version:

A linear time algorithm to sieve prime numbers and get the Euler's totient function

36 lines (32 loc) 897 B
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function sieveTotient(N) { if (N < 1) return [new Uint32Array(0), []]; if (N === 1) return [new Uint32Array(1), []]; let tot = 0; const phi = new Uint32Array(N); const primes = []; phi[1] = 1; for (let x = 2; x < N; ++x) { if (phi[x] === 0) { primes[tot++] = x; phi[x] = x - 1; } for (let i = 0; i < tot; ++i) { const target = primes[i] * x; if (target >= N) break; if (x % primes[i] === 0) { phi[target] = phi[x] * primes[i]; break; } phi[target] = phi[x] * (primes[i] - 1); } } primes.length = tot; return [phi, primes]; } exports["default"] = sieveTotient; exports.sieveTotient = sieveTotient;