In: Computer Science
SOLVE USING WHILE. A perfect number is a positive integer that is equal to the sum of its positive divisors except the number itself. The first two perfect numbers are 6 and 28 since 1+2+3=6 and 1+2+ 4+7+14=28. Write a matlab computer program that finds the first n perfect number (the user must input the value of n) and show them in a vector
thanks! xo
Code Screenshot :
Executable Code:
%Prompting the use for input
n = input('Please enter the value of n: ');
%Calling the function
perfectNumbers(n)
%Function definition
function result = perfectNumbers(n)
%Declaring a vector
result = zeros(1,n);
%Iterating till n
for i = 1:n
%Finding the perfect numbers
test = 1:i-1;
if (sum(test(mod(i,test) == 0)) == i)
result(i) = i;
end
end
result(result == 0) = [];
end
Sample Output :
Please comment
below if you have any queries.
Please do give a thumbs up if you liked the answer thanks
:)