Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions Basics/prime.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// Function to check primes using the Basic Method
function basicPrimes(n) {
const primes = [];
for (let i = 2; i <= n; i++) {
let isPrime = true;
for (let j = 2; j * j <= i; j++) {
if (i % j === 0) {
isPrime = false;
break;
}
}
if (isPrime) primes.push(i);
}
return primes;
}

// Function to find primes using Sieve of Eratosthenes
function sievePrimes(n) {
const isPrime = new Array(n + 1).fill(true);
isPrime[0] = isPrime[1] = false;

for (let i = 2; i * i <= n; i++) {
if (isPrime[i]) {
for (let j = i * i; j <= n; j += i) {
isPrime[j] = false;
}
}
}

return isPrime
.map((prime, i) => (prime ? i : null))
.filter((num) => num !== null);
}

// Example usage
const n = 30;

console.log("Prime numbers up to", n, "(Basic Method):");
console.log(basicPrimes(n).join(", "));

console.log();

console.log("Prime numbers up to", n, "(Sieve Method):");
console.log(sievePrimes(n).join(", "));