-1

I have a really small knowledge of JS And I was wondering that if someone inputted a number, if they could tell it was prime.

function prime(num) {
    for (var i = 2; i < num; i++) {
        if (num % i === 0 && i !== num) {
            break;
        } else {
            console.log("true")
        }
    }
}

My sister gave me this challenge, and I don't know how to do this... Any hints or tips, or a code I could dissect and understand how it works?

Thanks,

Simon Verhoeven
  • 1,295
  • 11
  • 23
user2562240
  • 49
  • 1
  • 3
  • I wonder if this has been asked before? Oh, it has: http://stackoverflow.com/questions/11966520/how-to-find-prime-numbers – Mulan Jul 08 '13 at 20:43
  • 2
    What's the problem with your code? – Felix Kling Jul 08 '13 at 20:43
  • Simple Google search turns up numerous answers. – Justin Chmura Jul 08 '13 at 20:45
  • @ naomik That is finding all prime numbers from 0-100 not a specific number. @ Felix it seems that everything becomes "true" Even if it isn't a prime number. – user2562240 Jul 08 '13 at 20:45
  • You can get rid of the `&& i !== num` part. That will never be true. – Jorjon Jul 08 '13 at 20:50
  • I don't see the problem with your code, but I didn't actually test it. Either way, this is definitely a duplicate question. Just because someone else asked how to find all primes between 0-100, doesn't mean you can't re-use that code to do what you're trying to do here. – Ricky Mutschlechner Jul 08 '13 at 21:02

1 Answers1

1

Find sqrt of your number after that loop number from i = 2 to sqrt(your_number) if your_number % === 0 this is end - this number is not a prime number.

Short example with number 37.

var n = 37;
var m = Math.sqrt(n);
var isPrime = true;
for (var i = 2; i <= m; i++) {
    if (n % i == 0) {
        isPrime = false;
        break;
    }
}

if (isPrime) {
    document.write(n + ' - Prime number<br/>');
} else {
    document.write(n + ' Is not prime number<br/>');
}
d.danailov
  • 9,594
  • 4
  • 51
  • 36