Basic: Prime Numbers

Question:

Please implement a function to check whether a number is a prime number or not. A prime number is a number greater than one that can be divided (without leaving any reminder) only by one and the number itself. The function simply has one parameter (an integer) and a boolean input stating whether the input is a prime number.


Answer:

Below is a simple and straightforward solution and runs in a linear time depending on the input.

#@title Basic: Prime numbers
def is_prime(n):
  if n <= 1: 
    return False
  for i in range(2,n):
    if n % i == 0:
      return False
  return True

# call the function
print(is_prime(1))  # False
print(is_prime(2))  # True
print(is_prime(4))  # False
print(is_prime(17)) # True
print(is_prime(25)) # False

👍 Have fun while coding with Python!

👌 Please subscribe to receive notifications on future challenges.

💬 If you have any questions simply write a comment down below.

Share