Prime Factors of Number

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore the concept of prime factorization and how it can be implemented in JavaScript using the trial division algorithm. We will learn how to find the prime factors of a given number and build a function that can handle this task. This lab will provide hands-on experience and a deeper understanding of the algorithm and its implementation.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/BasicConceptsGroup -.-> javascript/cond_stmts("`Conditional Statements`") javascript/BasicConceptsGroup -.-> javascript/loops("`Loops`") subgraph Lab Skills javascript/variables -.-> lab-28555{{"`Prime Factors of Number`"}} javascript/data_types -.-> lab-28555{{"`Prime Factors of Number`"}} javascript/arith_ops -.-> lab-28555{{"`Prime Factors of Number`"}} javascript/comp_ops -.-> lab-28555{{"`Prime Factors of Number`"}} javascript/cond_stmts -.-> lab-28555{{"`Prime Factors of Number`"}} javascript/loops -.-> lab-28555{{"`Prime Factors of Number`"}} end

How to Find Prime Factors of a Number using Trial Division Algorithm

To find prime factors of a given number using trial division algorithm, follow these steps:

  • Open the Terminal/SSH and type node to start practicing coding.
  • Use a while loop to iterate over all possible prime factors, starting with 2.
  • If the current factor, f, exactly divides n, add f to the factors array and divide n by f. Otherwise, increment f by one.
  • The function primeFactors takes a number n as input and returns an array of its prime factors.
  • To test the function, call primeFactors(147) and it will return [3, 7, 7].

Here's the JavaScript code:

const primeFactors = (n) => {
  let a = [],
    f = 2;
  while (n > 1) {
    if (n % f === 0) {
      a.push(f);
      n /= f;
    } else {
      f++;
    }
  }
  return a;
};

Remember to replace 147 with the number you want to find prime factors of.

Summary

Congratulations! You have completed the Prime Factors of Number lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like