Wednesday, April 5, 2023

Program to check Number is Prime or Not in Python

Python program that checks if a positive integer entered by the user is prime or not:

number = int(input("Enter a positive integer: "))

if number < 2:

    print("The number is not prime.")

else:

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

        if number % i == 0:

            print("The number is not prime.")

            break

    else:

        print("The number is prime.")

In this program, we first get input from the user for a positive integer using the input() function, and convert it to an int data type. We then check if the number is less than 2, since 1 and all negative integers are not prime. If the number is less than 2, we print a message to indicate that the number is not prime. Otherwise, we use a for loop to iterate over the possible factors of the number from 2 to half of the number (int(number/2)). If the number is divisible by any of these factors, we print a message to indicate that the number is not prime and break out of the loop. Otherwise, we print a message to indicate that the number is prime.

You can run this program in a Python interpreter or save it as a .py file and run it in the command line to check if different numbers are prime or not.

The output of the program would be:

Enter a positive integer: 17

The number is prime.

This means that the number 17 is a prime number.

Enter a positive integer: 10

The number is not prime.

This means that the number 10 is not a prime number, since it is divisible by 2 and 5. You can test this program with different positive integers to check if they are prime or not.

No comments:

Post a Comment

Apeejay Surrendra Park Hotels IPO: Should You Invest Today?

The Apeejay Surrendra Park Hotels (ASPH) IPO hits the market today, February 5th, 2024, offering a chance to invest in a well-established...