Use app×
Join Bloom Tuition
One on One Online Tuition
JEE MAIN 2025 Foundation Course
NEET 2025 Foundation Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
1.7k views
in Python by (15 points)
edited by

Algorithm to check whether a number is prime or not

Please log in or register to answer this question.

1 Answer

0 votes
by (24.8k points)

Input: An integer number greater than or equal to 2.

Output: True if the number is prime, False otherwise.

Steps:
1. If the input number is less than 2, return False (since prime numbers are greater than 1).
2. If the input number is 2, return True (since 2 is the only even prime number).
3. If the input number is even (divisible by 2), return False (excluding 2).
4. Loop from i starting from 3 up to the square root of number (inclusive), with a step size of 2 (to skip even divisors).
    a. Check if number is divisible by i.
        - If it is divisible, return False, as the number is not prime.
5. If the loop completes without finding any divisors, return True, as the number is prime.

Note: In the algorithm, we only need to check divisors up to the square root of the number because if there is a divisor greater than the square root, there must be a corresponding divisor smaller than the square root.

Pseudocode:

function is_prime(number):
    if number < 2:
        return False
    if number == 2:
        return True
    if number % 2 == 0:
        return False

    for i in range(3, int(sqrt(number)) + 1, 2):
        if number % i == 0:
            return False

    return True

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...