write a python program to check whether a number prime or not.
- User
write a python program to check whether a number prime or not.
- Assistant
Here's a simple Python program to check whether a number is prime or not using a basic algorithm:
num = int(input("Enter a number: ")) if num > 1: for i in range(2, int(num / 2) + 1): if (num % i) == 0: print(num, "is not a prime number") break else: print(num, "is a prime number") else: print(num, "is not a prime number")In this program, we first take the input number from the user using the
input()function. We then check whether the number is greater than 1, which is the lowest possible prime number.If the number is indeed greater than 1, we start a
forloop that iterates from 2 to half of the input number. We check whether the input number is divisible by each number in this range using the modulo operator (%). If the input number is evenly divisible by any number in this range, we print a message saying that it is not a prime number andbreakout of the loop.If the loop completes without finding any divisor for the input number, we print a message saying that it is a prime number. Note that the
elseclause in the loop is executed if the loop completes without encountering a statement. This is a special syntax in Python loops and is not related to the keyword in conditional statements. - User
write a python program to check whether a number prime or not using while loop.
- Assistant
Certainly, here is one way to write the program using a
whileloop instead of aforloop:num = int(input("Enter a number: ")) if num > 1: i = 2 while i <= num // 2: if num % i == 0: print(num, "is not a prime number") break i += 1 else: print(num, "is a prime number") else: print(num, "is not a prime number")This program has the same basic logic as the previous one, but uses a
whileloop instead of aforloop to iterate over the range of possible divisors. The loop runs whileiis less than or equal to the integer division ofnumby 2, which is an optimized way to get the range of possible divisors. Inside the loop, we check whethernumis evenly divisible byi. If so, we print a message saying that it is not a prime number andbreakout of the loop. Otherwise, we incrementiand continue to the next iteration.If the loop completes without finding any divisor for
num, we print a message saying that it is a prime number. Again, note the use of theelseclause after the loop, which is executed if the loop completes without encountering a statement.