generate prime numbers under 1000 in matlab

Here is a code to generate prime numbers under 1000 in Matlab:

main.m
% Initialize an empty array to hold the prime numbers
primes_array = [];

% Loop through numbers 2 to 1000 to check if they are prime
for num = 2:1000
    prime = true; % Assume num is prime unless proven otherwise
    
    % Loop through numbers 2 to sqrt(num) to check if num is divisible by any of them
    for divisor = 2:sqrt(num)
        if rem(num, divisor) == 0 % If num is divisible by divisor
            prime = false; % Set prime to false
            break % Exit the divisor loop early, no need to check further
        end
    end

    if prime % If num is still prime after the check
        primes_array = [primes_array, num]; % Add it to the primes_array
    end
end

% Display the prime numbers
disp(primes_array);
733 chars
23 lines

The output will be an array of prime numbers from 2 to 997. Note that 1 is not considered a prime number.

gistlibby LogSnag