find the sum of non positive prime in matlab

To find the sum of non-positive prime numbers in MATLAB, we need to perform the following steps:

  1. Define a function that checks whether a number is prime or not.
  2. Use a loop to iterate over all non-positive integers.
  3. If a number is prime and non-positive, add it to a running sum.
  4. Return the final sum.

Here is the MATLAB code to do this:

main.m
function sum = sumNonPosPrimes(n)
% This function finds the sum of non-positive prime numbers <= n.

sum = 0;
for i = -1:-1:n
    if isPrime(i)
        sum = sum + i;
    end
end

function flag = isPrime(n)
% This function checks if n is prime.

flag = true;
if n <= 1
    flag = false;
    return;
end
for i = 2:sqrt(n)
    if mod(n,i) == 0
        flag = false;
        return;
    end
end
392 chars
25 lines

We can test the function by calling it with a non-positive integer:

main.m
>> sumNonPosPrimes(-10)
ans =
     -17
39 chars
4 lines

In this example, the non-positive prime numbers less than or equal to -10 are -2, -3, -5, and -7, and their sum is -17.

gistlibby LogSnag