Created
February 25, 2015 00:11
-
-
Save obikag/544705ff833770f3a994 to your computer and use it in GitHub Desktop.
Prime number methods done in Python. First method determines if a number is prime, while the second method print to screen the first 'n' prime numbers. View comments for more information.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
Created on Feb 24, 2015 | |
''' | |
# Method to determine if a number is a prime number | |
def isPrime(num): | |
if num <= 0 : | |
print("Number must be a positive integer greater than zero") | |
return False | |
elif (num == 1): | |
return True | |
''' | |
Prime number is divisible by itself and one, | |
so we check for other factors between the prime number and one. (1 < x < num) | |
''' | |
for x in range(num-1,1,-1): | |
if ((num % x) == 0): | |
return False | |
return True | |
# Method to print the first 'n' prime numbers | |
def printPrime(n): | |
count = 1 | |
pnum = 1 | |
while True: | |
if isPrime(pnum): | |
print(pnum) | |
pnum += 1 | |
count += 1 # count only incremented when a prime number is found | |
else: | |
pnum += 1 | |
if (count > n): break | |
#***Test Section*** | |
print(isPrime(1)) #True | |
print(isPrime(-2)) #Number must be a positive integer greater than zero; False | |
print(isPrime(51)) #False | |
print(isPrime(3037)) #True | |
printPrime(10) | |
''' | |
Output: | |
1 | |
2 | |
3 | |
5 | |
7 | |
11 | |
13 | |
17 | |
19 | |
23 | |
''' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment