top of page
learn_data_science.jpg

Data Scientist Program

 

Free Online Data Science Training for Complete Beginners.
 


No prior coding knowledge required!

mairajsaleem92

Finding Prime Numbers using Python

OVERVIEW:

First, what is prime number?

A prime number is a natural number greater than 1 that is not a product of two smaller natural numbers.


In this article, we will find out the prime numbers up to 1000 with two examples. First by picking any number and checking if it is prime or not and second, by generating 100 random number between 2 to 1000 and testing the number is prime.


EXPLANATION OF CODE:

First, import the numpy library and make an array that contain prime values those have squared value under 1000. The maximum prime number which have square value under 1000 is 31. Look the code below:

 import numpy as np
 prime_values = np.array([2,3,5,7,11,13,17,19,23,29,31])

Now define the function that tests if the number is prime by using if, elif and else statements and create an empty list to save all numbers in values list and prime numbers in prime list.


If statement checks the number present in the array of prime_values, If yes, it considers it as a prime number.


In elif command, check the given number is divisible by one or more values from the array of prime_values. If yes, it is considered as non-prime.


Else consider it is prime number. The code is shown below: