MATLAB Answers

# Create a function myPrimes that returns the first n primes as a vector, given a positive integer. For example, if the positive integer is 5, the vector returned would include 1, 2, 3, 5, 7. In your script, prompt the user for the positive integer val

29 views (last 30 days)
Olivia DeBenedictis on 8 Feb 2021
Commented: Rohit Pappu on 11 Feb 2021
clc; close all; clear all;
n=input('Prime Numbers until:');
function result = myPrimes(n)
result = [];
index = 1;
i = 0;
num = 1;
flag = 0;
i = 0;
while i < n
j = 2;
flag = 0;
if(num==1)
flag=0;
else
while(j<num)
if(mod(num,j) == 0)
flag = 1;
end
j = j + 1;
end
end
if(flag == 0)
result(index) = num;
i = i + 1;
index = index + 1;
end
num = num + 1;
end
end
This is my current code. In order for it to output the primes I have to type myPrimes(n) with the desired input for n instead of just entering a number and getting an output.
##### 1 CommentShowHide None
Walter Roberson on 8 Feb 2021
Remove the first two lines.

Sign in to comment.

### Answers (1)

Rohit Pappu on 11 Feb 2021
Edited: Rohit Pappu on 11 Feb 2021
Refactor the first two lines to
clc;
n=input('Prime Numbers until:');
output = myPrimes(n)
Edit : Addressed @Rik 's feedback
##### 2 CommentsShowHide 1 older comment
Rohit Pappu on 11 Feb 2021
Thank you for the feedback @Rik

Sign in to comment.

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!