I'm trying to get a fast way to determine if a number is prime using Python. Show I have two functions to do this. Both return either True or False. Function isPrime1 is very fast to return False is a number is not a prime. For example with a big number. But it is slow in testing True for big prime numbers. Function isPrime2 is faster in returning True for prime numbers. But if a number is big and it is not prime, it takes too long to return a value. First function works better with that. How can I come up with a solution that could quickly return False for a big number that is not prime and would work fast with a big number that is prime?
martineau 115k25 gold badges160 silver badges284 bronze badges asked Oct 20, 2017 at 3:24
9 Exhaustive division until the square root is about the simplest you can think of. Its worst case is for primes, as all divisions must be performed. Anyway, until a billion, there is virtually no measurable time (about 1.2 ms for
Note that this version returns the smallest divisor or Some micro-optimizations are possible (such as using a table of increments), but I don' think they can yield large gains. There are much more sophisticated and faster methods available, but I am not sure they are worth the fuss for such small answered Oct 20, 2017 at 7:42
Yves DaoustYves Daoust 55.3k8 gold badges43 silver badges99 bronze badges 0 Primality tests is a very tricky topic. Before attempting to speed up your code, try to make sure it works as intended. I suggest you start out with very simple algorithms, then build from there. Of interest, isPrime2 is flawed. It returns True for 6, 10, 12, ... lines 3 to 6 are very telling
When a factor of Working through the code with
answered Oct 20, 2017 at 3:56
Xero SmithXero Smith 1,9181 gold badge13 silver badges19 bronze badges 1 Here is what I came up with
oguz ismail 40.7k12 gold badges43 silver badges64 bronze badges answered Oct 20, 2017 at 5:48
5 How do you check if a number is prime quickly?To prove whether a number is a prime number, first try dividing it by 2, and see if you get a whole number. If you do, it can't be a prime number. If you don't get a whole number, next try dividing it by prime numbers: 3, 5, 7, 11 (9 is divisible by 3) and so on, always dividing by a prime number (see table below).
How do you check if a number is prime in Python using while loop?Show activity on this post. flag = 0 n = int(input('\nEnter whole number to check : ')) i = 2 while i <= (n/2): if (n%i) == 0: flag = 1 break if n == 1: print('1 is neither prime nor composite') elif flag == 0: print(n,' is a prime number.
|