Below is a simple function to check for a prime number. The function is_prime_number()
returns False
if the number supplied is less than 2 and if the number is equally divisible with some other number different than 1 and itself. If none of the previous conditions apply the function will return True
. The below python script will let user to decide how many numbers needs to be check to see whether the number is prime number:
#!/usr/bin/env python prime_numbers = 0 def is_prime_number(x): if x >= 2: for y in range(2,x): if not ( x % y ): return False else: return False return True for i in range(int(raw_input("How many numbers you wish to check: "))): if is_prime_number(i): prime_numbers += 1 print i print "We found " + str(prime_numbers) + " prime numbers."
Save the above script into a file eg. is-prime-number.py
and make it executable:
$ chmod +x is-prime-number.py
Next, execute the is-prime-number.py
python script to search for a prime number within first 100 numbers. The output will print all prime numbers between 0 and 100.
$ ./is-prime-number.py How many numbers you wish to check: 100 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 We found 25 prime numbers.
On the below image you can see the output of a search for all prime numbers between 0 and 1 milion:
