Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,181 questions

56,073 answers

573 users

How to find the largest prime factor of a number in JavaScript

2 Answers

0 votes
function largestPrimeFactor(n) {
    let div = 2;
    let maxPFact = -1;

    while (n !== 0) {
        if (n % div !== 0) {
            div++;
        } else {
            maxPFact = n;
            n = Math.floor(n / div); // Integer division
            if (n === 1) {
                break;
            }
        }
    }

    return maxPFact;
}

console.log(largestPrimeFactor(124));  // 2 x 2 x 31
console.log(largestPrimeFactor(288));  // 2 x 2 x 2 x 2 x 2 x 3 x 3
console.log(largestPrimeFactor(1288)); // 2 x 2 x 2 x 7 x 23
console.log(largestPrimeFactor(100000000)); // 2, 2, 2, 2, 2, 2, 2, 2, 5, 5, 5, 5, 5, 5, 5, 5

  
  
/*
run:
 
31
3
23
5

*/

 



answered Apr 16, 2025 by avibootz
0 votes
// Returns the largest prime factor of n
function largestPrimeFactor(n) {
    n = BigInt(n);
    let largest = -1n;

    // Step 1: Remove all factors of 2
    while (n % 2n === 0n) {
        largest = 2n;
        n /= 2n;
    }

    // Step 2: Try odd factors from 3 to sqrt(n)
    let i = 3n;
    while (i * i <= n) {
        while (n % i === 0n) {
            largest = i;
            n /= i;
        }
        i += 2n;
    }

    // Step 3: If n is still > 2, it is a prime number
    if (n > 2n) {
        largest = n;
    }

    return largest;
}

let n1 = 124; // 2 x 2 x 31
let n2 = 288; // 2 x 2 x 2 x 2 x 2 x 3 x 3
let n3 = 1288; // 2 x 2 x 2 x 7 x 23
let n4 = 100000000; // 2, 2, 2, 2, 2, 2, 2, 2, 5, 5, 5, 5, 5, 5, 5, 5
let n5 = 600851475143n; // 71, 893, 1471, 6857

console.log("Largest prime factor:", largestPrimeFactor(n1));
console.log("Largest prime factor:", largestPrimeFactor(n2));
console.log("Largest prime factor:", largestPrimeFactor(n3));
console.log("Largest prime factor:", largestPrimeFactor(n4));
console.log("Largest prime factor:", largestPrimeFactor(n5));



/*
run:

Largest prime factor: 31n
Largest prime factor: 3n
Largest prime factor: 23n
Largest prime factor: 5n
Largest prime factor: 6857n

*/

 



answered Apr 23 by avibootz
...