Advertisement
Guest User

Untitled

a guest
Jul 22nd, 2017
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MatLab 1.30 KB | None | 0 0
  1. function [prime] = isPrime( N )
  2. %ISPRIME written as a function rather than just loose code
  3.  
  4. % we will assume to start off with that the number IS prime, then check to see if it isn't
  5.  
  6. % Prime=1 is horrible.. true/false is the way forward!
  7. prime=true;
  8.  
  9. % 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)
  10. % The loop will perform all the code between "for" and "end" incrementing the value of i each time.
  11. for i=2:N/2
  12.  
  13.    % 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)!
  14.    % This is a conditional statement. The syntax "if" `condition` .... end will perform all the code in .... iff the condition is true
  15.    if mod(N,i)==0
  16.  
  17.       % N is not a prime number so set prime=false
  18.       prime=false;
  19.  
  20.       % break jumps out of the for all loop. You can delete this and the algorithm will work.. it is just an optimisation.
  21.       break
  22.  
  23.    end
  24.  
  25. % !(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}
  26. end
  27.  
  28. % if prime=true N is a prime number
  29. if prime==true
  30.    disp('Prime Number!')
  31.  
  32. % if prime=false N is NOT a prime number
  33. else
  34.    disp('Not a Prime Number!')
  35. end
  36.  
  37. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement