Checking prime numbers in python

how to find a prime number function in python

I started getting back to python coding and realized I couldn’t quite figure this out. I’m trying to code a prime number function. Could someone help with this? Here is my code:

def is_prime(x): a = True for n in range(2, x-1): while n < x: n+=1 if x % n == 0: a = False elif n < 2: a = False else: a = True break break return a 

If anyone has an idea on what I'm doing wrong, please let me know. A month ago I tried this and couldn't get the logic down. I think I was stumped and didn't ever ask for help. Also, how long do you think I should try to do this for before I ask for help on average?

5 Answers 5

As, it has been said, you can optimize the code by just checking the odd numbers and iterating upto the sqrt of the num

import math def isPrime(num): if(num==1): return False if(num==2): return True if(num%2==0): return False i = 3 while(i 

using your code, and focusing on code structure:

def is_prime(x): # function contents must be indented if x == 0: return False elif x == 1: return False # your base cases need to check X, not n, and move them out of the loop elif x == 2: return True for n in range(3, x-1): if x % n == 0: return False # only return true once you've checked ALL the numbers(for loop done) return True 

adding some optimizations:

def prime(number): for i in range(2,number,1): if number % i == 0: return False return True entry = int(input("Please enter the number: ")) while True: if prime(entry): print ("It's a prime number. ") continue else: print ("It's not a prime number.. ") continue 

You will entry a number then this function will give you if its a prime or not. Check the function it will solve your problem.

ALSO You can upgrade the speed of your program. You know prime numbers can not be even, so you you dont have to check even numbers like 4-6-8-26. So in the range function, which is (2,number) add "2" end of it. like (3,number,2) then program will not check even numbers.

ALSO a factor can not be bigger than that numbers square root. So you dont have to check all of numbers till your main number, its enough to check your numbers square root. like: (2,number**0.5) that means from 2 to your number square root. So double up for program speed.

def prime(number): for i in range(3,(number**0.5)+1),2): if number % i == 0: return False return True 

The first function enough for you actually. I am working with huge numbers, so I have to upgrade the speed of my program.

Источник

Python Program to Check Prime Number

To understand this example, you should have the knowledge of the following Python programming topics:

A positive integer greater than 1 which has no other factors except 1 and the number itself is called a prime number. 2, 3, 5, 7 etc. are prime numbers as they do not have any other factors. But 6 is not prime (it is composite) since, 2 x 3 = 6 .

Читайте также:  Opencv draw image in image python

Example 1: Using a flag variable

# Program to check if a number is prime or not num = 29 # To take input from the user #num = int(input("Enter a number: ")) # define a flag variable flag = False if num == 1: print(num, "is not a prime number") elif num > 1: # check for factors for i in range(2, num): if (num % i) == 0: # if factor is found, set flag to True flag = True # break out of loop break # check if flag is True if flag: print(num, "is not a prime number") else: print(num, "is a prime number")

In this program, we have checked if num is prime or not. Numbers less than or equal to 1 are not prime numbers. Hence, we only proceed if the num is greater than 1.

We check if num is exactly divisible by any number from 2 to num - 1 . If we find a factor in that range, the number is not prime, so we set flag to True and break out of the loop.

Outside the loop, we check if flag is True or False .

Note: We can improve our program by decreasing the range of numbers where we look for factors.

In the above program, our search range is from 2 to num - 1 .

We could have used the range, range(2,num//2) or range(2,math.floor(math.sqrt(num)+1)) . The latter range is based on the fact that a composite number must have a factor less than or equal to the square root of that number. Otherwise, the number is prime.

You can change the value of variable num in the above source code to check whether a number is prime or not for other integers.

In Python, we can also use the for. else statement to do this task without using an additional flag variable.

Example 2: Using a for. else statement

num = 407 # To take input from the user #num = int(input("Enter a number: ")) if num == 1: print(num, "is not a prime number") elif num > 1: # check for factors for i in range(2,num): if (num % i) == 0: print(num,"is not a prime number") print(i,"times",num//i,"is",num) break else: print(num,"is a prime number") # if input number is less than # or equal to 1, it is not prime else: print(num,"is not a prime number")
407 is not a prime number 11 times 37 is 407

Here, we have used a for..else statement to check if num is prime.

It works on the logic that the else clause of the for loop runs if and only if we don't break out the for loop. That condition is met only when no factors are found, which means that the given number is prime.

So, in the else clause, we print that the number is prime.

Источник

How to Check if a Number is Prime in Python

Invicti Web Application Security Scanner – the only solution that delivers automatic verification of vulnerabilities with Proof-Based Scanning™.

This tutorial will teach you how to write a Python program to check if a number is prime or not.

If you’ve ever taken up coding tests, you’ll have come across the math question on the test for primality or to check if a number is prime. And over the next few minutes, you’ll learn to come up with the optimal solution to this question.

  • review the basics of prime numbers,
  • write Python code to check if a number is prime, and
  • optimize it further to get an O(√n) runtime algorithm.
Читайте также:  Java удаление строки массива

For all this and more, let’s get started.

What is a Prime Number?

Let’s start by reviewing the basics of prime numbers.

In number theory, a natural number n said to be prime if it has exactly two factors: 1 and the number itself (n). Recall from your school math: a number i is said to be a factor of the number n, if i divides n evenly. ✅

The following table lists down a few numbers, all their factors, and if they’re prime.

n Factors Is Prime?
1 1 No
2 1, 2 Yes
3 1, 3 Yes
4 1, 2, 4 No
7 1, 7 Yes
15 1, 3, 5, 15 No

From the above table, we can write down the following:

  • 2 is the smallest prime number.
  • 1 is a factor of every number.
  • Every number n is a factor of itself.

So 1 and n are trivial factors for any number n. And a prime number should not have any factors other than these two.

This means that when you go from 2 to n – 1, you should not be able to find a non-trivial factor that divides n without a remainder.

O(n) Algorithm to Check if a Number is Prime in Python

In this section, let us formalize the above approach into a Python function.

You can loop through all numbers from 2 to n – 1 using the range() object in Python.

In Python, range(start, stop, step) returns a range object. You can then iterate over the range object to get a sequence from start all the way up to stop -1 in steps of step .

Since we need the set of integers from 2 to n-1, we can specify range(2, n) and use it in conjunction with for loop.

Here’s what we would like to do:

  • If you find a number that divides n evenly without a remainder, you can immediately conclude that the number is not prime.
  • If you’ve looped through the entire range of numbers from 2 all the way up to n – 1 without finding a number that divides n evenly, then the number is prime.

Python Function to Check for Prime Number

Using the above, we can go ahead and define the function is_prime() as follows.

def is_prime(n): for i in range(2,n): if (n%i) == 0: return False return True

Let’s now parse the above function definition.

  • The above function is_prime() takes in a positive integer n as the argument.
  • If you find a factor in the specified range of (2, n-1), the function returns False —as the number is not prime.
  • And it returns True if you traverse the entire loop without finding a factor.

Next, let’s call the function with arguments and verify if the output is correct.

is_prime(2) # True is_prime(8) # False is_prime(9) # False is_prime(11) # True

In the output above, you see that 2 and 11 are prime (the function returns True ). And 8 and 9 are not prime (the function returns False ).

How to Optimize the Python Function is_prime()

We can do a small optimization here. Observe the list of factors in the table below.

Number Factors
6 1, 2, 3 , 6
10 1, 2, 5 , 10
18 1, 2, 3, 6, 9 , 18

Well, we can see that the only factor of n that is greater than n/2 is n itself.

So this means you don’t have to loop all the way up to n – 1. You can instead run the loop only up to n/2.

Читайте также:  Center align button

If you don’t find a non-trivial factor till n/2, you can’t find one beyond n/2 either.

Now let’s modify the function is_prime() to check for factors in the range (2, n/2)

def is_prime(n): for i in range(2,int(n/2)): if (n%i) == 0: return False return True

Let’s go ahead and verify the output through a few function calls.

is_prime(9) # False is_prime(11) # True

Even though it may seem like we have optimized, this algorithm is not more efficient than the previous one in terms of runtime complexity. In fact, both of them have O(n) runtime complexity: proportional to the value of n or linear in n.

Can we do better? Yes, we can!

▶️ Proceed to the next section to determine how to improve the time complexity for prime number testing.

O(√n) Algorithm to Check for Prime Number in Python

It happens that the factors of a number occur in pairs.

If a is a factor of the number n, then there also exists a factor b such that a x b = n, or simply, ab = n.

Let’s verify this through an example.

The table below shows the factors of the number 18 occurring in pairs. You may verify the same for a few more numbers if you like.

Also, note that √18 is approximately 4.24.

And in the factors that occur in pairs (a, b), you can see that if a is less than 4.24, then b is greater than 4.24—in this example, (2, 18) and (3, 6).

factors-on-number-line

If the number n happens to be a perfect square, you’ll have a = b = √n as one of the factors.

▶️ Look at the factors of 36 in the table below. As 36 is a perfect square, a = b = 6 is one of the factors. For all other factor pairs (a, b), a < 6 and b >6 holds.

prime-number-checking-python

Let us now increase the range to as high as 2000 and repeat the same steps as above.

import numpy as np import seaborn as sns import pandas as pd n = 2000 x = np.arange(n) y1 = np.sqrt(x) y2 = x df = pd.DataFrame() sns.set_theme() sns.lineplot(data = df) 

prime-number-checking-python

From the above plot, you can infer that O(√n) algorithm is significantly faster when you’re testing if a large number is prime.

Here’s a quick example: 2377 is a prime number—verify this!😀

While the O(n) approach will take the order of 2000 steps, the O(√n) algorithm can help arrive at the answer in just 49 steps.✅

Conclusion

⏳ And it’s time for a quick summary.

  • To check if a number is prime, the naïve approach is to loop through all numbers in the range (2, n-1). If you don’t find a factor that divides n, then n is prime.
  • As the only factor of n greater than n/2 is n itself, you may choose to run only up to n/2.
  • Both of the above approaches have a time complexity of O(n).
  • As factors of a number occur in pairs, you can run only up to √n. This algorithm is a lot faster than O(n). And the gain is appreciable when checking if a large number is prime or not.

I hope you understand how to check if a number is prime in Python. As a next step, you may check out our tutorial on Python programs on string operations—where you’ll learn to check if strings are palindromes, anagrams, and more.

See you all in another tutorial. Until then, happy coding!👩🏽‍💻

Источник

Оцените статью