Check For Prime In Python

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Lecture 54:-  Check For Prime In Python

To check if a number is prime in Python, you can create a function that determines whether the number has only two divisors (1 and itself). Here are two approaches to check for prime numbers:

  1. Using a Loop:

pythonCopy code

def is_prime(num):    if num <= 1:        return False    for i in range(2, int(num**0.5) + 1):        if num % i == 0:            return False    return True # Example usage: num_to_check = 17 if is_prime(num_to_check):    print(f"{num_to_check} is a prime number.") else:    print(f"{num_to_check} is not a prime number.")

Output:

csharpCopy code

17 is a prime number.

In this approach, the is_prime() function takes a positive integer num as input. If the number is less than or equal to 1, it returns False, as prime numbers are greater than 1. It then checks for divisors from 2 up to the square root of the number (inclusive). If any divisor is found, the function returns False, indicating that the number is not prime. Otherwise, it returns True.

  1. Using Recursion:

pythonCopy code

def is_prime(num, divisor=2):    if num <= 1:        return False    if divisor == num:        return True    if num % divisor == 0:        return False    return is_prime(num, divisor + 1) # Example usage: num_to_check = 17 if is_prime(num_to_check):    print(f"{num_to_check} is a prime number.") else:    print(f"{num_to_check} is not a prime number.")

The output for this example will also be:

csharpCopy code

17 is a prime number.

In this approach, the is_prime() function uses recursion to check for divisors. It has an additional parameter divisor that keeps track of the current divisor being checked. The function checks for the base cases (num <= 1 and divisor == num) and returns False or True accordingly. If the number is divisible by the current divisor, it returns False, indicating that the number is not prime. Otherwise, it calls itself with the next divisor to check.

Both approaches will correctly determine whether a given number is prime or not. You can use either of these methods based on your preference and the specific requirements of your code.

6. Loops

Comments: 0

Frequently Asked Questions (FAQs)

How do I register on Sciaku.com?
How can I enroll in a course on Sciaku.com?
Are there free courses available on Sciaku.com?
How do I purchase a paid course on Sciaku.com?
What payment methods are accepted on Sciaku.com?
How will I access the course content after purchasing a course?
How long do I have access to a purchased course on Sciaku.com?
How do I contact the admin for assistance or support?
Can I get a refund for a course I've purchased?
How does the admin grant access to a course after payment?