Monday 13 November 2023

A simple Python code for checking whether a given number is prime or not

 


def is_prime(number):

    # Check if the number is less than 2

    if number < 2:

        return False

    

    # Check for factors from 2 to the square root of the number

    for i in range(2, int(number**0.5) + 1):

        if number % i == 0:

            # If a factor is found, the number is not prime

            return False

    

    # If no factors are found, the number is prime

    return True


# Example usage

num = int(input("Enter a number: "))

if is_prime(num):

    print(f"{num} is a prime number.")

else:

    print(f"{num} is not a prime number.")


Explanation:


The is_prime function takes an integer number as an argument and returns True if the number is prime, and False otherwise.

The function first checks if the number is less than 2. If it is, the number is not prime, as prime numbers are defined as greater than 1.

It then uses a for loop to iterate over the range from 2 to the square root of the number (rounded up to the nearest integer). This is an optimization, as factors of a number larger than its square root must pair with factors smaller than its square root.

Inside the loop, it checks if the number is divisible evenly by the current value of i. If it is, then the number is not prime, and the function returns False.

If no factors are found in the loop, the function returns True, indicating that the number is prime.

Finally, an example usage of the function is shown, where the user is prompted to enter a number, and the program prints whether it is prime or not based on the result of the is_prime function.

0 Comments:

Post a Comment

Popular Posts

Categories

AI (28) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (121) C (77) C# (12) C++ (82) Course (66) Coursera (184) Cybersecurity (24) data management (11) Data Science (99) Data Strucures (7) Deep Learning (11) Django (6) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flutter (1) FPL (17) Google (19) Hadoop (3) HTML&CSS (46) IBM (25) IoT (1) IS (25) Java (92) Leet Code (4) Machine Learning (46) Meta (18) MICHIGAN (5) microsoft (4) Pandas (3) PHP (20) Projects (29) Python (791) Python Coding Challenge (268) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (2) Software (17) SQL (41) UX Research (1) web application (8)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses