4. 3323 |
A prime number can be divided, without a remainder, only by itself and by 1. Write a code segment to determine if a defined positive integer N is prime. Create a list of integers from 2 to N-1. Use a loop to determine the remainder of N when dividing by each integer in the list. Set the variable result to the number of instances the remainder equals zero. If there are none, set result=0 (the number is prime). Use the built-in MATLAB function rem to determine the remainder after division. (the remainder of N divided by P is rem(N,P)) For example N=5 % list= [2,3,4] % remainder of 5/2 is 1 % remainder of 5/3 is 2 % remainder of 5/4 is 1 result = 0 % inputted number is prime N=6 % list=[2,3,4,5] % remainder of 6/2 is 0 % remainder of 6/3 is 0 % remainder of 6/4 is 2 % remainder of 6/5 is 1 result = 2 % two integers in the list have remainder=0 |
Code to copy:
clc;
clear all;
close all;
N=input('Enter an integer:');
li=2:N-1;
result=0;
for i=li
if rem(N,i)==0
result=result+1;
end
end
result
if result==0
disp('Inputted number is prime');
else
fprintf('%d integers in the list have remainder=0\n',result);
end
Matlab code:
Output:
Get Answers For Free
Most questions answered within 1 hours.