fueanta

Prime factors of n

Jun 22nd, 2021 (edited)
161
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const getPrimeFactors = (n: number): number[] => {
  2.     const primeFactors: number[] = [];
  3.  
  4.     if (n < 2) return primeFactors;
  5.  
  6.     let divisor = 2;
  7.  
  8.     // As long as, n is an even number
  9.     while (n % divisor === 0) {
  10.         primeFactors.push(divisor);
  11.         n = ~~(n / divisor);
  12.     }
  13.  
  14.     // by this time n must be an odd number
  15.     for (divisor = 3; divisor <= ~~Math.sqrt(n); divisor += 2) {
  16.         while (n % divisor === 0) {
  17.             primeFactors.push(divisor);
  18.             n = ~~(n / divisor);
  19.         }
  20.     }
  21.  
  22.     if (n > 2) {
  23.         primeFactors.push(n);
  24.     }
  25.  
  26.     return primeFactors;
  27. }
  28.  
RAW Paste Data