Write a logical (boolean) function named isPrime(n)
that takes in an integer number n
, and finds whether it is a Prime number or not. Example output is the following,
isPrime(23)
True
isPrime(12)
False
Note that you do not need and must not use a for-loop
for this problem (we have not yet discussed loops in our class!). All of it can be done using recursive function concept.
Hint: To check if a number is a prime number, you would need to check if the number is divisible by any number smaller than itself. However, there is no need to check the divisibility for all numbers smaller than the target number. This divisibility checking can be done only up to a certain number. You may think that this checking should be done up to half the target number. But you can in fact end your search much sooner than reaching the half value. For example, consider the following checks for the number n = 100
. When we test all possible divisors up to n/2
, we will discover some factors twice. To observe this, rewrite the list of divisors as a list of products, each equal to 100:
Notice that products past $10 \times 10$ merely repeat numbers which appeared in earlier products. Use this example to find the optimal threshold in your search for primality.
Hint: You can verify the accuracy of your MATLAB script via by checking its output against MATLAB’s built-in function isprime()
.