find prime numbers using for loop in matlab

To find prime numbers using for loop in MATLAB, we can use the modulo operator to check if a number is divisible by any number other than 1 and itself.

Here's the code:

main.m
% Set range
n = 1000;

% Initialize vector to store prime numbers
primes = [];

% Loop through each number within the range
for i = 2:n
    % Assume each number is prime to start
    is_prime = true;
    
    % Check if number is divisible by any number other than 1 and itself
    for j = 2:(i-1)
        if mod(i,j) == 0
            % Number is not prime if it is divisible
            is_prime = false;
            break;  % Exit loop early if number is found to be not prime
        end
    end
    
    % If number is prime, add to vector
    if is_prime
        primes(end+1) = i;
    end
end

% Display prime numbers
disp(primes);
638 chars
29 lines

Here we have initialized a vector primes to store prime numbers. We loop through each number within the range from 2 to n. We assume each number is prime to start, and then we use a nested for loop to check if the number is divisible by any number other than 1 and itself using the modulo % operator. If the number is found to be not prime during the inner for loop, we break out early and move on to the next number in the outer loop. If the number is prime, we add it to the primes vector. Finally, we display the vector of prime numbers using disp().

One way to optimize this code would be to only check divisibility up to the square root of the number, since any factors beyond the square root would have already been checked. Another optimization would be to use logical indexing instead of a vector to store the prime numbers, since we don't know how many prime numbers there will be within the range beforehand.

gistlibby LogSnag