I was curious to see how well ChatGPT could solve a simple programming problem, so I asked:

Write a JavaScript function to return the prime factors of a number in an array.

A few seconds later, it came back with a pretty good answer:

function primeFactors(num) {
  const factors = [];
  // check if number is prime
  function isPrime(n) {
    if(n<2) return false;
    for (let i = 2; i <= Math.sqrt(n); i++) {
      if (n % i === 0) return false;
    }
    return true;
  }
  // find prime factors
  for (let i = 2; i <= num; i++) {
    while (num % i === 0) {
      if (isPrime(i)) factors.push(i);
      num /= i;
    }
  }
  return [...new Set(factors)];
}
console.log(primeFactors(100));

Well actually, that wasn’t quite the answer. I added the bit at the end to return only the unique prime factors by turning the factors array into a set.

ChatGPT also provided a little bit of commentary about the function that explained how it works and that it might not be very fast with large numbers.

Overall, very impressive but still needs a bit of the human touch. I could have asked for the unique prime factors, but a person would assume that’s what you want if you asked them to write the function. But still very impressive.