perfect number in matlab

A perfect number is a positive integer that is equal to the sum of its proper divisors (excluding itself). Here's a simple matlab code to determine whether a given number is a perfect number or not.

main.m
function isPerfect = perfectNumber(n)
    divisors = [];
    for i = 1:n/2
        if mod(n, i) == 0
            divisors = [divisors i];
        end
    end
    if sum(divisors) == n
        isPerfect = true;
    else
        isPerfect = false;
    end
end
258 chars
14 lines

Here, the input argument n represents the positive integer we want to check. The divisors array stores all the positive divisors of n. The for loop runs from 1 to n/2 to find all the divisors. If i is a divisor of n, then mod(n, i) will be zero, and we add it to the divisors array.

Finally, we check if the sum of divisors is equal to n, If they are equal, then the number is a perfect number and the function returns true, otherwise false.

gistlibby LogSnag