Get factors of n! (factorial) with javascript

Home   »   Get factors of n! (factorial) with javascript

const { performance } = require("perf_hooks");

const num = Number(process.argv[2]);

if (isNaN(num)) {
    console.log("shut the fuck up");
    process.exit(1);
}

if (!Number.isInteger(num)) {
    console.log("This is not Gamma function!");
    process.exit(1);
}

if (num < 1) {
    console.log("Wut");
    process.exit(1);
}

const measureTime = performance.now();

// find prime till num
const primes = [];
for (let i = 2; i <= num; i++) {
    let isPrime = true;

    for (let j = 2; j <= Math.sqrt(i); j++) {
        if (i % j === 0) {
            isPrime = false;
            break;
        }
    }
    if (isPrime) primes.push(i);
}

let output = "";

// get expontent for each prime
primes.forEach((base) => {
    let exponent = 0;
    let i = 1;

    // Legendre's formula: v_p (n!) = [n/p] + [n/p^2] + [n/p^3] + ...

    while (true) {
        const x = Math.floor(num / base ** i);
        if (x <= 0) break;
        exponent += x;
        i++;
    }

    output += base + " ^ " + exponent + " * ";
});

const time = performance.now() - measureTime;

console.log(output);

console.log(time + "ms");

Leave a Reply

Your email address will not be published. Required fields are marked *