Prime.js ( using Arrays )
/* Find out all prime numbers less than or equal to n.
Input:-
Given n =10;
Output:-
[2,3,5,7]
*/
let fs = require("fs");
let data = fs.readFileSync(0, 'utf-8');
let idx = 0;
data = data.split('\n');
function readLine() {
idx++;
return data[idx - 1].trim();
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
let n = parseInt(readLine()); // 10
let ans = []; // intialising with an empty array to push all the prime no. afterwards
for (let i = 2; i <= n; i++) { // 2,3,4,5,6,7,8,9,10
let isPrime = true; // intially we are assuming that all the numbers are prime
for (let j = 2; j < i; j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime == true) {
ans.push(i);
}
}
console.log(ans);
///////////////////////////////////////////////////////////////////////////////////////////////
TERMINAl:

Comments
Post a Comment