Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Prime number checker [duplicate]

Tags:

python

primes

I have been trying to write a program that will take an inputed number, and check and see if it is a prime number. The code that I have made so far works perfectly if the number is in fact a prime number. If the number is not a prime number it acts strange. I was wondering if anyone could tell me what the issue is with the code.

a=2 num=13 while num > a :   if num%a==0 & a!=num:     print('not prime')     a=a+1   else:     print('prime')     a=(num)+1 

the result given when 24 is inputed is: not prime not prime not prime prime

How would i fix the error with the reporting prime on every odd and not prime for every even

like image 734
Chris Avatar asked Sep 16 '13 17:09

Chris


1 Answers

You need to stop iterating once you know a number isn't prime. Add a break once you find prime to exit the while loop.

Making only minimal changes to your code to make it work:

a=2 num=13 while num > a :   if num%a==0 & a!=num:     print('not prime')     break   i += 1 else: # loop not exited via break   print('prime') 

Your algorithm is equivalent to:

for a in range(a, num):     if a % num == 0:         print('not prime')         break else: # loop not exited via break     print('prime') 

If you throw it into a function you can dispense with break and for-else:

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

Even if you are going to brute-force for prime like this you only need to iterate up to the square root of n. Also, you can skip testing the even numbers after two.

With these suggestions:

import math def is_prime(n):     if n % 2 == 0 and n > 2:          return False     for i in range(3, int(math.sqrt(n)) + 1, 2):         if n % i == 0:             return False     return True 

Note that this code does not properly handle 0, 1, and negative numbers.

We make this simpler by using all with a generator expression to replace the for-loop.

import math def is_prime(n):     if n % 2 == 0 and n > 2:          return False     return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2)) 
like image 112
Steven Rumbalski Avatar answered Sep 20 '22 11:09

Steven Rumbalski