-3

I have to find the amount of prime numbers within a certain range in Python, and I have to use a for ... in range loop. I have been struggling with this so much these past few days and it has just been getting absolutely tiring. I have an idea how to do this, but when I put it into code, it just never works properly, no matter how hard I try. Anyways, here is my code:

def num_of_primes(n):
  count = 1
  primeNum = 0
  for count in range(2, n+1):
    if (n % count == 0 and count == n and (n % count != 0 and count != n)):
      primeNum += 1
  return primeNum

I think I know why this doesn't work, but I have no idea how to fix it so that it works properly. Oh and also, I have to do this using only ONE function (forgot to add that, sorry).

indian_trash
  • 1
  • 1
  • 3

1 Answers1

2

First of all you should research well before posting question like this. However, I think you're new into python. So, I am implementing a straight-forward solution which is computationally very inefficient. You can do something like this -

def is_prime(n):
    for i in range(2, int(n/2) + 1):
        if n%i == 0:
            return False
    return True


def num_of_primes(n):
    count = 1
    primeNum = 0
    
    for count in range(2, n+1):
        if is_prime(count):
            primeNum += 1
    return primeNum
Afif Al Mamun
  • 199
  • 1
  • 11