-3

How to create a python function that can determine whether or not the input number by the user is prime? returning True if it is, and False otherwise. and then display the message indicating whether or not it is prime.

3 Answers3

0
def prime_numbers(input_number):

  flag = 0

  for i in range(2, input_number):
    if input_number % i == 0:
      flag = 1
      break
  if flag == 1:
    return False
  return True

n = int(input('Give any number'))
is_prime = prime_numbers(n)

if is_prime:
  print('The number is prime')

else:
  print('The number is composite')

  • You could use for/else to avoid needing the flag. Or just return mid-for. I would also recomend just checking the division by the first 10 prime numbers instead of all numbers between 2 and the input – Mateus Terra Nov 20 '21 at 13:38
0
def isprime(n):
    '''check if integer n is a prime'''
    # make sure n is a positive integer
    n = abs(int(n))
    # 0 and 1 are not primes
    if n < 2:
        return False
    # 2 is the only even prime number
    if n == 2: 
        return True    
    # all other even numbers are not primes
    if not n & 1: 
        return False
    # range starts with 3 and only needs to go up the squareroot of n
    # for all odd numbers
    for x in range(3, int(n**0.5)+1, 2):
        if n % x == 0:
            return False
    return True

Got it from here: https://www.daniweb.com/programming/software-development/code/216880/check-if-a-number-is-a-prime-number-python

clintbugs
  • 1
  • 1
  • 1
0

here is a simple script that checks if num is exactly divisible by any number from 2 to num - 1. If we find a factor in that range, the number is not prime, so we set flag to True and break out of the loop.

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

flag = False

# prime numbers are greater than 1
if num > 1:
    # check for factors
    for i in range(2, num):
        if (num % i) == 0:
            # if factor is found, set flag to True
            flag = True
            # break out of loop
            break

# check if flag is True
if flag:
    print(num, "is not a prime number")
else:
    print(num, "is a prime number")
Rdimo
  • 378
  • 2
  • 14