0

I have the following function:

def prime(number):
    for num in range(1,number):
        if num > 1:
            for i in range (2, num):
                if (num%i == 0):
                    return("not a prime")
            else:
                return(num)

print(prime(9))

Output: 2

Please explain where I am doing a mistake or how can I get a list of all prime numbers in any input range ex:-9 or 100 or 300.

lmiguelvargasf
  • 63,191
  • 45
  • 217
  • 228
pquest
  • 303
  • 1
  • 3
  • 14

1 Answers1

4

The problem is that when you reach the return statement, the function execution terminates, so you will only get the first prime. Consider creating a list in which you will append your prime numbers as follows:

def prime(number):
    primes = []
    for num in range(1, number + 1):
        if num > 1:
            for i in range (2, num):
                if (num % i == 0):
                    break
            else:
                primes.append(num)
    return primes

This will give you the prime numbers from 2 up to number. I hope this helps you.

As suggested by @jpp, you can also use yield as follows:

def prime(number):
    for num in range(1,number):
        if num > 1:
            for i in range (2, num):
                if (num%i == 0):
                    break
            else:
                yield num

for num in prime(20):
    print(num)
lmiguelvargasf
  • 63,191
  • 45
  • 217
  • 228
  • @SameerKumarPandey, just keep in mind that this is not an efficient algorithm. – lmiguelvargasf Sep 17 '19 at 21:58
  • @SameerKumarPandey, you're welcome. I hope you can validate/upvote my answer too. – lmiguelvargasf Sep 17 '19 at 22:02
  • Why is it not an efficient algorithm..please explains? Please give the better code? – pquest Sep 17 '19 at 22:03
  • Or just replace `return` in the original code with `yield`, then use `next` on the generator. – jpp Sep 17 '19 at 22:07
  • It is not efficient because you are trying to find a number that divides your current `num` from 2 up to `num - 1`. However, you can go up to `int(number ** 0.5)`. There are other ways to generate prime numbers you can read [this](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes). – lmiguelvargasf Sep 17 '19 at 22:07
  • @jpp Could you please show how? – pquest Sep 17 '19 at 22:15
  • 1
    @SameerKumarPandey, I just updated my answer. Adding the way you could use `yield` and then using a for loop which underneath the hood calls `next` every time it is generating a number. – lmiguelvargasf Sep 17 '19 at 22:19