samedi 3 novembre 2018

Program to calculate the nth Prime Number Matlab

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<=)
    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));

Aucun commentaire:

Enregistrer un commentaire