Updating this! I have been trying to alert out all the prime numbers up to 100 in javascript. This is what I have so far (my computer isnt allowing me to copy and paste for some reason so I have to screencap to post)
If you could guide me in the right direction, or let me know what i'm missing, that would be amazing. Thanks!
Asked
Active
Viewed 314 times
0

user3247128
- 359
- 1
- 3
- 9
-
2Please don't post pictures of your source code. Post the text of the code itself. – Kenster Aug 19 '15 at 20:22
2 Answers
0
A nice and typical implementation, though not the most efficient of course:
function primenum(num){
if(num < 2 ) return false // 0 and 1 are not primes
for(var i=2;i*i<=num;i++){
if( num % i == 0){
return false; // if we find a divisor up to the square of the number, then its not prime and we stop checking
}
}
return true; // if we couldn´t find a divisor, then it means its a prime number
}
for(var i=0;i<100;i++){
if(primenum(i) == true) console.log(i) // if its prime, display on console
}
Edit: if you want to alert all prime numbers between 1 and 100, we can store them on a array and show them later:
primes = [];
for(var i=0;i<100;i++){
if(primenum(i) == true){
primes.push(i);
}
}
alert(primes)
As to why we check up to the square of the number: Why do we check up to sqrt
-
I appreciate the help, thanks! I have updated my code, but not sure how to alert it/what I'm doing wrong! – user3247128 Aug 19 '15 at 20:58
-
@user3247128 if you change the console.log(i) with alert(i) it will alert the prime numbers, but will give a window for each prime number, which bothers a lot. Will make an example of alerting just once storing prime numbers in array – juvian Aug 19 '15 at 21:01
0
I have included Javascript to take input from user and find prime numbers between the chosen range.
function primeNumbers(){
var min=document.getElementById("minNumber").value;
var max=document.getElementById("maxNumber").value;
var Nprime=new Array();
for(var i=min,k=0;i<=max;i++){
if(prime(i)){
Nprime[k]=i;
k++;
}
}
document.write("Prime numbers are: "+Nprime);
}
function prime(num){
if(num < 2 )
return false; // 0 and 1 are not primes
for(var j=2;j<=num/2;j++){
if( num % j === 0){
return false; //If we find a divisor, then return false
}
}
return true; // prime number found
}
<body>
<p> Finding prime numbers between </p> <input type="number" id="minNumber"> and <input type="number" id="maxNumber">.
<p><input type="button" value="Show now" onclick="primeNumbers()">
</body>