+ 1
can u help me out understanding the exit case for this recursion program??
def primecheck(a,i = 2): if a <= 1: return("Nonprime!!") elif a == 2: return("Prime") elif (a % i == 0): return("nonprime") elif (i*i > a): return("prime") return primecheck(a,i+1) #main.. num = int(input("Enter the number: ")) print(primecheck(num)) in this code can anyone make me understand how the recursion loop ends and output comes the entered number i >2 and prime??
2 Réponses
+ 1
The function primecheck(), given a number a, will check for every possible divisor i, inside the range 2 (the default second argument) and i*i (no need to go further on), incrementing i by 1 at every new recursion (can be optimized changing the increment: 1 is a lot of recursions).
Before recursing, there are 4 exit cases:
- the given number is 0 or 1: it is said not prime
- the given number is 2: prime
- found a divisor i: prime
- reached the end of possible divisors range i*i, without having found any divisor: prime
+ 1
Thanks a lot got that