DEV Community

Anees Kodappana
Anees Kodappana

Posted on

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

Discussion (0)