In: Computer Science
Write two scripts(must be titled “primeSumLoopS” and “primeSumCallS”) in MATLAB that prompts the user to enter an integer x that 2< x <10000, then the program calculates and displays the sum of the all the prime numbers that are smaller than or equal to x. For example, if x is 11, then the output is 28, which is 2+3+5+7+11. Use two methods: the 1st script uses nested loop and the 2nd script calls another function, primeF.
%% Matlab script to find sum of primes betwwen the given range
using loops
clear all;
clc;
close all;
x=input('Enter X value greater than 2 and less than 10000');
s=2;
if (x>2) && (x<10000)
for i=3:x
flag=1;
for p=2:i
r=mod(i,p);
if(r==0)&&(p~=i)
flag=0;
break;
else
continue;
end
end
if flag==1
s=s+i;
end
end
else
disp("Enter X value greater than 2 and less than 10000")
end
disp(s)%%displaying the final sum resultThe above picture talks about
matlab code finding sum of primes within given range using
loops.
For the given input x=11 the output should be 28 (2+3+5+11+7).Hereby below attachment of output was done.
%%Matlab script to find out sum of primes within given range using Functions
clear all;
clc;
x=input('Enter X value greater than 2 and less than 10000')
sum=2;
for i=3:x
flag= primeF(i);
%disp(i)
if(flag)
sum=sum+i;
end
end
disp(sum)%%display of final result
function out = isDivis(n1,sqrt_n1,div)
if mod(n1,div) == 0
out = false;
elseif sqrt_n1<div
out= true;
return
else
div = div + 1;
out = isDivis(n1,sqrt_n1,div);
end
end
function lg = primeF(n1)
if n1 == 3
lg=true;
return;
end
div = 2;
lg = true;
sqrt_n1 = round(sqrt(n1));
lg = isDivis(n1,sqrt_n1,div);
end
The above picture talks about matlab code finding sum of primes within given range using Functions.
For the given input x=11 the output should be 28 (2+3+5+11+7).Hereby below attachment of output was done.
I tried my level best in uploading the scripts. Unfortunatley could not way .Please let me how to upload matlab scripts in comments , BOTH CODE EXCUTES WELL Thank you!!