Created
August 21, 2024 09:55
-
-
Save alishahlakhani/8e4b5e6edefe7bcddfc32991447371ce to your computer and use it in GitHub Desktop.
Algorithm // Finding Prime Factors for a number // Inefficient
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function isPrime(num: number): boolean { | |
return findFactors(num).length === 2; | |
} | |
function findFactors(num1: number): Array<number> { | |
let factors: Array<number> = []; | |
for (let index = 0; index <= num1; index++) { | |
if (num1 % index == 0) { | |
factors.push(index); | |
} | |
} | |
return factors; | |
} | |
function findPrimeFactors(num1: number): Array<number> { | |
let factors: Array<number> = []; | |
const primes = getPrimes(num1); | |
for (let index = 0; index <= primes.length; index++) { | |
const primeNumber = primes[index]; | |
if (num1 % primeNumber == 0) { | |
factors.push(primeNumber); | |
} | |
} | |
return factors; | |
} | |
function getPrimes(num: number): Array<number> { | |
let primes: Array<number> = []; | |
for (let index = 0; index <= num; index++) { | |
if (isPrime(index)) { | |
primes.push(index); | |
} | |
} | |
return primes; | |
} | |
console.log("Prime Factors =", findPrimeFactors(15)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment