Reputation: 11
I am studying JavaScript and right now is Im trying to show the prime numbers. but unfortunately it doesnt display. can someone help Iam stuck with these.
This is my code:
function getPrimes(max) {
var sieve = [], i, j, primes = [];
for (i = 2; i <= max; ++i) {
if (!sieve[i]) {
primes.push(i);
for (j = i << 1; j <= max; j += i) {
sieve[j] = true;
}
}
}
return primes;
}
getPrimes(10);
and also I tried this. but still nothing shows. second code:
function findeprime(num){
var isPrime;
for (var i = 2; i < num; i++){
isPrime = true;
for (coun = 2; coun < i; coun++) {
if (i % coun == 0) isPrime = false;
}
if (isPrime) document.write(i + " is prime <br/>");
}
}
finderprime(5);
Upvotes: 1
Views: 79
Reputation: 2482
For the 1st code you have not printed variable primes
function getPrimes(max) {
var sieve = [], i, j, primes = [];
for (i = 2; i <= max; ++i) {
if (!sieve[i]) {
primes.push(i);
for (j = i << 1; j <= max; j += i) {
sieve[j] = true;
}
}
}
document.writeln(primes);
}
getPrimes(10);
For the 2nd code, You have given different names to the same function.
function findprime(num){
var isPrime;
for (var i = 2; i < num; i++){
isPrime = true;
for (coun = 2; coun < i; coun++) {
if (i % coun == 0) isPrime = false;
}
if (isPrime) document.write(i + " is prime <br/>");
}
}
var number = 5;
findprime(number);
Upvotes: 0
Reputation: 385
What exactly do you mean by "doesn't display"? This code works fine for me in a console. You just don't have any code to actually output or display the returned values.
If you're trying to output to the console, try using console.log()
.
If you're trying to make this appear on a webpage, try out document.write();
.
Upvotes: 1