-1

I am trying to write a program which checks if a number is a prime number or not.

The way I already know: Check if any of the numbers, excluding the number itself and 1, gives a reminder of zero.

The way I want to try: Check if more than two numbers, including 1 and the number itself, are giving a reminder of zero:

n=10
for a in range(1,n+1):
   x=n%a
   if (x == 0):
   print x

I am getting the number of instances when the reminder is zero with code mentioned. I want to define the logic in such a way that if number of zeros is greater than 2 in the output, then the number is not prime, else the number is prime. (Expecting that the input number is greater than 1.)

cdlane
  • 40,441
  • 5
  • 32
  • 81
  • 2
    Possible duplicate of [Why do we check up to the square root of a prime number to determine if it is prime?](https://stackoverflow.com/questions/5811151/why-do-we-check-up-to-the-square-root-of-a-prime-number-to-determine-if-it-is-pr) – CMichael Jun 17 '19 at 16:39
  • Why would you want to do that? – RalfFriedl Jun 17 '19 at 17:01

1 Answers1

1

I think folks are confused and avoiding this as it's not an efficient way to check for primes. Usually, we desire to disqualify a number as quickly and easily as possible, avoiding doing any extra divisions.

However, if it's what you want, here's an implementation:

def is_prime(n):
    '''
    I want to define the logic in such that if the number 
    of zeros is greater than 2 in the output, then the number
    is not prime, else the number is prime
    '''

    return sum(n % divisor == 0 for divisor in range(1, n + 1)) <= 2

# Expecting that the input number is greater than 1
for n in range(2, 100):
    if is_prime(n):
        print(n)
cdlane
  • 40,441
  • 5
  • 32
  • 81