So I was able to solve this problem with a little bit of help from the internet and this is what I got:

def isPrime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True

But my question really is how to do it, but WHY. I understand that 1 is not considered a "prime" number even though it is, and I understand that if it divides by ANYTHING within the range it is automatically prime thus the return False statement. but my question is what role does the squaring the "n" play here? Thank you very much for your attention

P.s. I am very inexperienced and have just been introduced to programming a month ago :S

@whytheq: No, for example 28331 has a factor higher than its square root (sqrt(28331) is approximately 168.3, while the this number has factor of 691). However for every factor higher than the square root of the number, there exists a related integer lower than the square root (in example case 41). There's no need to check for factors above square root (as it would have already found the related integer and hence determine the number is not prime). The square root itself needs to be checked as that's the special case when the tested number is a 2nd power there are two equal factors.
– desowinJan 30 '18 at 13:36

The line r = int(n**0.5) evaluates to 70 (the square root of 5003 is 70.7318881411 and int() truncates this value)

Consider the next odd number (since all even numbers other than 2 are not prime) of 5005, same thing prints:

5
False

The limit is the square root since x*y == y*x The function only has to go 1 loop to find that 5005 is divisible by 5 and therefore not prime. Since 5 X 1001 == 1001 X 5 (and both are 5005), we do not need to go all the way to 1001 in the loop to know what we know at 5!

It does not test if n is less than 2, and there are no primes less than 2;

It tests every number between 2 and n**0.5 including all even and all odd numbers. Since every number greater than 2 that is divisible by 2 is not prime, we can speed it up a little by only testing odd numbers greater than 2.

So:

def isPrime2(n):
if n==2 or n==3: return True
if n%2==0 or n<2: return False
for i in range(3, int(n**0.5)+1, 2): # only odd numbers
if n%i==0:
return False
return True

OK -- that speeds it up by about 30% (I benchmarked it...)

The algorithm I used is_prime is about 2x times faster still, since only every 6th integer is looping through the loop. (Once again, I benchmarked it.)

@minitech: How does this 'not answer the question at all'?
– dawgMar 8 '13 at 3:35

Before you edited it, it gave an alternative solution for prime testing — better, but the question wasn’t whether there was a better one. Your edits do answer the question and augment it with a better solution, so I withdrew my downvote. And added an upvote and such. Thanks for notifying ;)
– Ry-♦Mar 8 '13 at 4:13

3

All prime numbers, other than 2 & 3, are of the form 6n+/-1. All composite numbers have prime factors. This algorithm leverages those two facts to reduce the number of checks per number. Could add that to the answer.
– elssarMar 8 '13 at 7:28

1

I think the isPrime2 code you have shown has a bug: if you try to test an even number greater than 2 it will return True. Either you need to add another condition or your range has to start from 2
– RafazZMay 16 '15 at 21:43

Might i add, that using math.sqrt appears to be slightly faster than ** .5 (tested with timeit, Python 3)
– FlipTackDec 30 '16 at 14:55

Consider the number 20; the integer factors are 1, 2, 4, 5, 10, and 20. When you divide 20 by 2 and get 10, you know that it is also divisible by 10, without having to check. When you divide it by 4 and get 5, you know it is divisible by both 4 and 5, without having to check for 5.

After reaching this halfway point in the factors, you will have no more numbers to check which you haven't already recognized as factors earlier. Therefore, you only need to go halfway to see if something is prime, and this halfway point can be found by taking the number's square root.

Also, the reason 1 isn't a prime number is because prime numbers are defined as having 2 factors, 1 and itself. i.e 2 is 1*2, 3 is 1*3, 5 is 1*5. But 1 (1*1) only has 1 factor, itself. Therefore, it doesn't meet this definition.

The reason the square root is the halfway point is that every pair of divisors will fall either side of the square root, or - if they are both the same (if it's a square number) - will be the square root exactly.
– mwfearnleyApr 22 '14 at 1:21

No floating point operations are done below. This is faster and will tolerate higher arguments. The reason you must go only to the square-root is that if a number has a factor larger than its square root, it also has a factor smaller than it.

Yes. If there is a factor k with 1 < k < n, then n/k is also a factor. One of these must be less than the square root of n.
– ncmathsadistMar 8 '13 at 2:22

I fixed a small coding error in the consequent of your second if statement by commenting out the erroneous line and inserting a new correct line. Your original program incorrectly reported that 2 is not prime.
– user448810Mar 8 '13 at 2:43

@ncmathsadist Could you explain the block with the variable k? I think of it as while k(3) * k(3) <= n(9), if n(9) % k(3) == 0 (which does equal 0 here), then return false and then increment k to be k(3) = k(3) + 2 which is 5. What are you doing here? And why k = k + 2? Now that k(5) * k(5) = 25 is no longer <= n(9) then what?
– EdisonMay 17 at 7:43

Also does this reach a point in which the speed starts becoming deficient, comparitively to some of the other functions, The test that I am using this within while using list comprehension starts crying if I go into the realm of 100000, after which it starts breaking down in a speed aspect, not too sure why since it's just a list comprehension on a basic algebraic point, to look at not understand.
– L.P.Nov 5 '15 at 2:11

I'm sorry about that, but I cant explain it to you. I've found it while searching for a short solution and thought it was a nice one and wanted to share it with you :-).
– DanielNov 7 '15 at 18:21

2

You can replace the 2**Number%Number by pow(2, Number, Number), it will be more efficient for big numbers)
– ArglanirMay 16 '16 at 19:35

2

This test seems to be close to Lucas' primality test. In order to be complete, we would need to check that 2**((Number-1)/k) for all k prime factors of Number-1 are also equal to 1. The wikipedia page gives the full complete algorithm.
– ArglanirMay 16 '16 at 19:58

1

This fails for all Fermat pseudoprimes oeis.org/A001567: 341, 561, 645, 1105, ... It is a pseudo-primality test based on "Fermat's Little(!) Thm.: a^p = a (mod p) if p is prime", but not "only if".
– MaxMar 13 at 22:08

Take this example just as a less efficient alternative implementation that you should not use, but instead you should use the algorithm by @ncmathsadist, which is better in terms of performance. Just to make an example. I have tried to run the same algorithm that @ncmathsadist is using in a loop from 0 to 100000 and it took 0.3 seconds (rounded), while this one took 63 seconds. You are free to use whatever you want, but this quite bad compared to the algorithm by @ncmathsadist.
– nbroJan 19 '16 at 3:11

This algorithm is very similar to this one, both in terms of performance and implementation.
– nbroJan 19 '16 at 3:14

Every code you write should be efficient.For a beginner like you the easiest way is to check the divisibility of the number 'n' from 2 to (n-1). This takes a lot of time when you consider very big numbers. The square root method helps us make the code faster by less number of comparisons. Read about complexities in Design and Analysis of Algorithms.

I don't know if I am late but I will leave this here to help someone in future.

We use the square root of (n) i.e int(n**0.5) to reduce the range of numbers your program will be forced to calculate.

For example, we can do a trial division to test the primality of 100. Let's look at all the divisors of 100:

2, 4, 5, 10, 20, 25, 50
Here we see that the largest factor is 100/2 = 50. This is true for all n: all divisors are less than or equal to n/2. If we take a closer look at the divisors, we will see that some of them are redundant. If we write the list differently:

import math
def isPrime(n):
'Returns True if n is prime, False if n is not prime. Will not work if n is 0 or 1'
# Make sure n is a positive integer
n = abs(int(n))
# Case 1: the number is 2 (prime)
if n == 2: return True
# Case 2: the number is even (not prime)
if n % 2 == 0: return False
# Case 3: the number is odd (could be prime or not)
# Check odd numbers less than the square root for possible factors
r = math.sqrt(n)
x = 3
while x <= r:
if n % x == 0: return False # A factor was found, so number is not prime
x += 2 # Increment to the next odd number
# No factors found, so number is prime
return True

To answer the original question, n**0.5 is the same as the square of root of n. You can stop checking for factors after this number because a composite number will always have a factor less than or equal to its square root. This is faster than say just checking all of the factors between 2 and n for every n, because we check fewer numbers, which saves more time as n grows.

This is the most interesting example that I found so far (because it uses recursion), except that it doesn't work. It doesn't handle, for example, the case num = 1. If you fix your algorithm, I'll remove my downvote.
– nbroJan 18 '16 at 19:56

In order to have your function working properly, you just have to add this after the if statement: elif num == 1: return False
– CCBetJan 5 '19 at 12:02

Take this example just as a less efficient alternative implementation that you should not use, but instead you should use the algorithm by @ncmathsadist, which is better in terms of performance. Just to make an example. I have tried to run the same algorithm that @ncmathsadist is using in a loop from 0 to 100000 and it took 0.3 seconds (rounded), while this one took 62 seconds. You are free to use whatever you want, but this quite bad compared to the algorithm by @ncmathsadist.
– nbroJan 19 '16 at 3:13

This algorithm is very similar to this one, both in terms of performance and implementation.
– nbroJan 19 '16 at 3:15

I have no idea if this works, but the performance of your function is quite worse than a simple not clever algorithm that uses divisions, i.e. an algorithm that checks all numbers up to n. For example, this takes roughly 0.8 seconds to check primality for all numbers from 0 to 10000, while yours took 19 seconds on my machine.
– nbroJan 19 '16 at 3:23

@nbro first, pay attention to the line in the answer that says: "If you want to come out as a real smartass". I did not claim that its performance is good, and since it uses regex - it's obviously not! Now, if you want to understand how it works, go to the link at the end of the answer and invest 10-20 minutes in reading it. It's simple yet brilliant!
– alfasinJan 19 '16 at 5:47

Yes, I will try to have a look at that article, because it might be interesting. What I wanted to point out is that suggesting an algorithm that is a lot worse than a simpler one might not be a good idea. Yours is just pretty, not good. Thanks anyway for sharing!
– nbroJan 19 '16 at 13:54

@nbro mathematics is full of such examples (beautiful things that are not useful/optimized at the moment). But sometimes, 200-300 years after something is considered only "beautiful" - we find that it's also useful. Take Fermat last theorem for example :)
– alfasinJan 19 '16 at 15:30

def is_prime(n):
n=abs(n)
if n<2: #Numbers less than 2 are not prime numbers
return "False"
elif n==2: #2 is a prime number
return "True"
else:
for i in range(2,n): # Highlights range numbers that can't be a factor of prime number n.
if n%i==0:
return "False" #if any of these numbers are factors of n, n is not a prime number
return "True" # This is to affirm that n is indeed a prime number after passing all three tests

Square root of 400 is 20:
and we can see that we only need to check the divisibility till 20 because, as 'a' reaches 20 'b' starts decreasing...
So, ultimately we are checking divisibility with the numbers less than the square root.

Because CS is not about knowing a/the programming language, but rather to know how to use the language in the most optimal way. The code you use will work just fine, but is slow. If you put just a little bit of thought into it, you can write a much better primality test with complexity of O(sqrt(n)) (like @dawg explained). Your code runs in O(n). This is a problem for primality test, partially because it uses modulus(%) operator which by definition is one of the slowest functions (unless it's %2)
– RafazZMay 17 '15 at 21:04