Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function [prime] = isPrime( N )
- %ISPRIME written as a function rather than just loose code
- % we will assume to start off with that the number IS prime, then check to see if it isn't
- % Prime=1 is horrible.. true/false is the way forward!
- prime=true;
- % This is a loop. I think the easiest way of thinking about this is that you are saying for all i in {2...n/2} (using maths notation)
- % The loop will perform all the code between "for" and "end" incrementing the value of i each time.
- for i=2:N/2
- % This checks to see if i divides N (the number we are testing for primality. If it does, we set prime to 0. Otherwise we skip to !(A)!
- % This is a conditional statement. The syntax "if" `condition` .... end will perform all the code in .... iff the condition is true
- if mod(N,i)==0
- % N is not a prime number so set prime=false
- prime=false;
- % break jumps out of the for all loop. You can delete this and the algorithm will work.. it is just an optimisation.
- break
- end
- % !(A)! If i does NOT divide N, the computer will jump here, the end will make it go to the next value of i in {2, .. ,N/2}
- end
- % if prime=true N is a prime number
- if prime==true
- disp('Prime Number!')
- % if prime=false N is NOT a prime number
- else
- disp('Not a Prime Number!')
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement