getting prime numbers between 2 numbers input by the user

16 views (last 30 days)
num1 = input('Enter Number 1: '); %prompt user for first number
num2 = input('Enter Number 2: '); %prompt user for second number
for x = num1:num2 %x is numbers in between num1 and num2
y = primes(x); %y is to find the primes between the 2 number
end
fprintf('The primes between %d and %d are: \n',num1, num2); %tells the user the output
disp(y); %display the primes
this is my code and when the user input 15 and 30 for the first and second number, instead of getting prime numbers just from 15 to 30, the result is prime numbers from 1 to 30, how should i modify the code to get prime numbers just between num1 and num2? thanks!

Accepted Answer

Stephen23
Stephen23 on 20 Sep 2017
Edited: Stephen23 on 20 Sep 2017
When you read the primes documentation it describes that the function "returns a row vector containing all the prime numbers less than or equal to n." That means on each iteration of your loop y is a vector containing all primes between 1 and x. What do you want to do with all of them? Your code does nothing to handle that whole vector, and you don't make any attempt to remove the prime numbers less than num1.
You also never use indexing inside the loop, so all of those y vectors are discarded except for the last one. There does not seem to be much point to that.
I think isprime would be more useful for you, because you can then use its output to index into your vector, thus giving you all prime numbers between the two numbers:
num1 = str2double(input('Enter Number 1: ','s')); %prompt user for first number
num2 = str2double(input('Enter Number 2: ','s')); %prompt user for second number
v = num1:num2; % v is a vector of numbers inbetween num1 and num2
y = v(isprime(v)); % select the prime numbers
fprintf('The primes between %d and %d are: \n',num1, num2); %tells the user the output
disp(y); %display the primes
and tested:
Enter Number 1: 15
Enter Number 2: 30
The primes between 15 and 30 are:
17 19 23 29
Or you could use primes and remove the lower part using indexing:
v = primes(num2); % v is primes less than num2
y = v(v>=num1) % y is primes greater than num1
  1 Comment
Grace Lim
Grace Lim on 20 Sep 2017
Edited: Grace Lim on 20 Sep 2017
thank you so much! edit: i decided to go with the second one! once again, thank you so much for your help!

Sign in to comment.

More Answers (1)

Image Analyst
Image Analyst on 20 Sep 2017
One approach is to computer primes for both numbers and use setdiff():
num1Primes = primes(num1-1)
num2Primes = primes(num2)
result = setdiff(num2Primes, num1Primes)

Categories

Find more on Discrete Math in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!