find the sum of all non positive prime numbers given an input in matlab

main.m
% prompt user for input
n = input('Enter a positive integer: ');

% initialize sum
sum_nonpos_primes = 0;

% loop through numbers from -2 to -n and check if they are non-positive primes
for i = -2:-1:n
    if isprime(abs(i)) && i <= 0
        sum_nonpos_primes = sum_nonpos_primes + i;
    end
end

% display result
disp(['The sum of all non-positive prime numbers from -2 to -', num2str(n), ' is ', num2str(sum_nonpos_primes), '.']);
435 chars
16 lines

The code above prompts the user for a positive integer n, initializes a variable sum_nonpos_primes as 0, loops through the numbers from -2 to -n, and checks if each number is a non-positive prime using the isprime function and a conditional statement. If a number is a non-positive prime, it adds it to the sum sum_nonpos_primes. Finally, it displays the result of sum_nonpos_primes. Note that we use the abs function to make sure that we only check the absolute value of each number for primality.

gistlibby LogSnag