DEV Community

Anees Kodappana
Anees Kodappana

Posted on

3 2

Finding factors of a number, Identify Prime and Composite number

Let’s define the terms first

Prime number

A prime number is a number that has only two factors, 1 and the number itself

Composite number

A composite number is a number which is not prime, e.g 72 have 12 factors (1,2,3,4,6,8,9,12,18,24,36,72)

function findFactors(dividend) {
  var factors = [1, dividend];
  var quotient = Math.min();
  var divisor = 2;

  while(divisor < quotient) {
      quotient = dividend / divisor;
      if(Number.isInteger(quotient)) {
        factors.push(quotient, divisor);
      }
      divisor++;
  }

  return factors;
}


function isPrime(number) {
  return findFactors(number).length === 2
}

var num = 5;
var factors = findFactors(num);

console.log(factors.length + " factors found (" + factors.sort((a, b) => a-b) + ")");
console.log(isPrime(num) ? "It's a prime number" : "It's a composite number");

var num = 72;
var factors = findFactors(num);

console.log(factors.length + " factors found (" + factors.sort((a, b) => a-b) + ")");
console.log(isPrime(num) ? "It's a prime number" : "It's a composite number");

Enter fullscreen mode Exit fullscreen mode

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay