Python List Manipulation —Prime Numbers
How to know if a certain number is a prime or not! The prime numbers define as the natural number bigger than 1 that cannot be formed by multiplying two smaller natural numbers, So the whole range of negative number is not included. 0 and 1 are also excluded. So P=[i……n] where p % i is not equal to 0. So given a number x, write function to determine if the x is prime of not.
def is_prime(x): -----> return True if x is prime number
-----> return False if x is not prime number
Validations:
- Parameter x will always passed as integer.
- You need to validate x for negative numbers or 0.
- Consider an optimization for your solution to manage memory more effectively.
Solution:
let’s rephrase what make a certain number a “Prime Number”,
Prime = Any number between [2………n] that only accept to be divided by it’s self and the 1. So if you trying to divide it by any other number less than x it should not give you an integer without remaining.
hmmm! That is a good start. So we can start a for loop to check the result of dividing x with EVERY number less than x till we reach 2.
For our list of number that will loop through is : [2,… ,x-1]. Before we start our loop we need to construct some validation against x:
Check if x is bigger than 1 so this way we filter out any negative value of x beside the 0 and 1. Then we iterate through the the range and divide x with each element, If the remaining is equal to 0 then the number is not a prime since it’s the product of the multiplying of two digits.
The code will look like this.
Further enhancement need to make the code manage memory allocation better. The main issue here appear if x is really big number, so we have to check longer size of array. In this case we can iterate through half of the length of x len(x)/2. It’s more efficient to multiply the last number of the list by 0.50.
This will help us gain better performance with our code. If you have the 4 , 6 and 9 are not validated properly you can add them explicitly as follow:
The final code:
is_prime(9) -----> false
is_prime(2) -----> true
is_prime(-1) -----> false
is_prime(0) -----> false
is_prime(7) -----> true
is_prime(1) -----> false
Full code: https://github.com/ENGSamShamsan/spiral-shap-array
If you work the Right to left design or languages, or you know someone who do, then buying my book will be great way to gain RTL end to end knowledge and support me to keep writing book at the same time.