not prime in matlab

To check if a number is prime in MATLAB, you can write a function that loops through all the numbers from 2 to the square root of the number you want to check, and checks if any of them divide the number evenly. If none of them do, then the number is prime. Here's an example implementation:

main.m
function isPrime = notPrime(n)
    if n < 2
        isPrime = true; % treat negative numbers and 1 as not prime
        return;
    end

    for i = 2:sqrt(n)
        if mod(n, i) == 0
            isPrime = false;
            return;
        end
    end

    isPrime = true;
end
279 chars
16 lines

This function takes in a number n and returns true if it is not prime, and false if it is prime. It first checks if the number is less than 2, since negative numbers and 1 are not prime. Then it loops through all the numbers from 2 to the square root of n, checking if any of them divide n evenly by using the modulus operator. If any of them do, then n is not prime and the function returns false. Otherwise, the function returns true.

gistlibby LogSnag