getting prime numbers between 2 numbers input by the user
Show older comments
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
More Answers (1)
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!