find the sum of all non prime numbers in matlab

One possible solution is to first check if a number is prime or not using a helper function. Then, use a loop to go through all the numbers between 1 and some upper limit. For each number, check if it is not prime, and if so, add it to a running sum. Finally, return the total sum.

Here's an example implementation:

main.m
function result = sumOfNonPrimes(upperLimit)
% Returns the sum of all non-prime numbers between 1 and upperLimit

% Helper function to check if a number is prime or not
function isPrime = isPrimeNumber(n)
    isPrime = true;
    for i = 2:sqrt(n)
        if mod(n, i) == 0
            isPrime = false;
            break;
        end
    end
end

% Initialize running sum
totalSum = 0;

% Iterate through all numbers between 1 and upperLimit
for num = 1:upperLimit
    % Check if number is not prime
    if ~isPrimeNumber(num)
        totalSum = totalSum + num;
    end
end

% Return final sum
result = totalSum;
end
616 chars
29 lines

You can test the function with different upper limits like this:

main.m
>> sumOfNonPrimes(10)
ans =
    20
>> sumOfNonPrimes(50)
ans =
    707
71 chars
7 lines

gistlibby LogSnag