-2

Hi guys can u help i want to make number list prime in python but with no for loop do or while only with recursive function

closed

Jakiroo
  • 7
  • 2
  • 9
  • 1
    Finding prime numbers is inefficient. In fact it is so inefficient that most of the security on the internet is based on its inefficiency. In addition to that you have found one of the least efficient ways to solve the problem and now you are asking to further reduce the efficiency by adding recursion. Python is great at iterations but terrible at recursions. – Klaus D. Dec 22 '20 at 09:25
  • yea im found interesting comment like this, https://stackoverflow.com/a/19379226/9201789 but thats need for to loop the number – Jakiroo Dec 22 '20 at 09:26

1 Answers1

0

Extending on your naive and inefficient approach, the simplest way to replace the outer loop by recursion is something like:

def print_primes(limit):
    if limit < 2:  # base case
        return

    print_primes(limit-1)  # recursive call: reduce problem size

    # inner loop only for the last case
    for b in range (2, int(limit**0.5)+1, 1):
        if not limit % b:
            break
    else:  # using for-else, slightly more to the point
        print(limit)

>>> print_primes(20)
2
3
5
7
11
13
17
19
user2390182
  • 72,016
  • 6
  • 67
  • 89