Program to calculate the nth Prime Number
5 views (last 30 days)
Show older comments
I am attempting to write a program that accepts a user input for the value of n, and returns the nth prime number. I.e. if n = 20, the output is 71. I have currently written the following code, however it currently returns 0 when n is greater than 2, but I'm not sure why this is?
number = input('Enter a value for n: ');
if (number<0)
error('Only positive integer values are accepted!');
primes = zeros(1,number);
primes(1) = 2;
primes(2) = 3;
checkThis = 5;
i=3;
if (i<=number)
x=round(sqrt(checkThis));
checkRange=1:2:x;
disp(checkRange);
for j=1
if(mod(checkThis,checkRange(j))==0)
itIsPrime=0;
else
itIsPrime=1;
disp(itIsPrime);
j=length(checkRange);
end
end
if (itIsPrime==1)
primes(i)=checkThis;
i=i+1;
else
checkThis = checkThis + 2;
end
end
disp(primes(number));
5 Comments
Walter Roberson
on 7 Feb 2021
disp(primes(number));
is the line of code that is outputing the nth prime to the display.
Answers (2)
Walter Roberson
on 4 Nov 2018
checkRange=1:2:x;
That always starts with 1
for j=1
That is a loop with j only equal to 1.
if(mod(checkThis,checkRange(j))==0)
When j = 1, checkRange(j) is checkRange(1) which is 1, so you are taking mod(checkThis, 1) which is going to equal 0 for all integers checkThis . So you mark them all as non-prime
itIsPrime=0;
else
itIsPrime=1;
disp(itIsPrime);
j=length(checkRange);
Caution: j is the for loop control variable. If you modify a for loop control variable within the for loop, then if there were any iterations remaining, then the next iteration, the loop control variable will be set to the next loop value, as if the variable had not been modified. Setting the loop control variable to the last value it would normally have looped to, does not have the effect of exiting the loop. If you want to exit the loop early, use break
0 Comments
madhan ravi
on 4 Nov 2018
Edited: madhan ravi
on 4 Nov 2018
Do you even realise that there is an inbuilt function in Matlab to do that? as sir Walter already gave the answer?? Also don't use the variable name as primes because it's an inbuilt function of Matlab
clear all
t = primes(100);
n = input('nth value? ')
t(20)
0 Comments
See Also
Categories
Find more on Loops and Conditional Statements 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!