Question: See Hahn Chapter Loops Problem 1 : The Prime Directive [ MG Also ] Filename: Function Declaration: function [ isItPrime ] = primeDirective ( numberToTest

See Hahn Chapter "Loops"
Problem 1: The Prime Directive [MG Also]
Filename:
Function Declaration:
function [isItPrime]= primeDirective(numberToTest) A number is prime if it is not an exact multiple of any other number except itself
and 1, i.e. if it has no factors except itself and 1. The easiest plan of attack then is
as follows. Suppose P is the number to be tested. See if any numbers N can be
found that divide into P without remainder. If there are none, P is prime. Which
numbers N should we try? Well, we can speed things up by restricting P to odd
numbers, so we only have to try odd divisors N . When do we stop testing? When
N=P? No, we can stop a lot sooner. In fact, we can stop once N reaches ?2P, since if
there is a factor greater than ?2P there must be a corresponding one less than ?2P,
which we would have found. And where do we start? Well, since N=1 will be a
factor of any P , we should start at N=3. The structure plan is as follows
Input P from the input parameter of the function
Initialize N to 3
Find remainder R when P is divided by N
While R0 and N?2P repeat:
Increase N by 2
Find R when P is divided by N
If R0 then
P is prime
Else
P is not prime
Stop
Return the correct value
Note that there may be no repeats
R might be zero the first time.
Note also that there are two conditions under which the loop may stop.
Consequently, an if is required after completion of the loop to determine which
condition stopped it.
Write the function. Then try it out on the following numbers: 4058879(not prime),
193707721(prime) and 2147483647(prime). Code to call your function
isNumberPrime = round(rand*100000);
primResult = primeDirective(isNumberPrime);
[By using Matlab]
See Hahn Chapter "Loops" Problem 1 : The Prime

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!