find prime numbers without isprime() in matlab

To find prime numbers in MATLAB without using the built-in isprime() function, you can create a script that uses loops, conditions, and the mod() function to determine if a number is prime or not. Here's an example code:

main.m
% Define a range of numbers to check for primes
start_num = 2;  % starting number
end_num = 100;  % ending number

% Loop through the range of numbers and print prime numbers
for num = start_num:end_num
    is_prime = true;  % assume the number is prime unless proven otherwise
    
    % Check if the number is divisible by any numbers from 2 to num-1
    for div = 2:num-1
        if mod(num, div) == 0
            is_prime = false;  % if divisible, number is not prime
            break;  % exit the loop early
        end
    end
    
    % Print the number if it is prime
    if is_prime
        fprintf('%d ', num);
    end
end
634 chars
22 lines

In this code, we first define the range of numbers to check for primes, then loop through the range one number at a time. For each number, we assume it is prime at first and then check if it is divisible by any numbers from 2 to the number itself minus 1. If we find a divisor, we set the is_prime variable to false and exit the loop early because we know that the number is not prime. If we complete the loop without finding a divisor, we know that the number is prime and we print it to the screen.

This code can be modified to store the prime numbers in a vector or other data structure if you need to use them later in your program.

gistlibby LogSnag