IN MATLAB Prime Number Tester Write a program that asks the user for a positive
ID: 3884515 • Letter: I
Question
IN MATLAB
Prime Number Tester
Write a program that asks the user for a positive integer, N. The program then tests if the integer is prime and writes out its result. A number is prime if it cannot be divided evenly by any number other than 1 and itself. So you will need a counting loop that starts at two and attempts to divide the number for each value of the loop counter until the number is divided evenly or the limit is reached.
For the upper limit of the loop use the number divided by two. (A better upper limit would be the square root of the number). Search Internet for mod or rem matlab functions. Use only integer arithmetic. Test your program with the number 13,249 which is prime and with 13,245 which is not prime.
Explanation / Answer
% taking user input
num = input("Enter a num: ");
% by default setting it to prime
result = "It is prime";
% looping through 2 to number/2 and performing modulus and setting result if given number is divisible by any number
for i=2:(num/2)
if rem(num,i)==0
result="It is not prime";
end
end
% printing the result
fprintf("%s",result)
Sample Output
Enter a number: 13245
It is not prime
Enter a number: 13249
It is prime
% taking user input
num = input("Enter a num: ");
% by default setting it to prime
result = "It is prime";
% looping through 2 to number/2 and performing modulus and setting result if given number is divisible by any number
for i=2:(num/2)
if rem(num,i)==0
result="It is not prime";
end
end
% printing the result
fprintf("%s",result)
Sample Output
Enter a number: 13245
It is not prime
Enter a number: 13249
It is prime