To accept two numbers from the user and display perfect numbers between these two numbers.

1 view (last 30 days)
hi,
how do i write the code for the above? how do i continue from here. thank you very much.
clc
num1 =input('Enter num1 value ');
num2 =input('Enter num2 value ');

Answers (3)

Walter Roberson
Walter Roberson on 23 May 2015
num1 =input('Enter num1 value ');
num2 =input('Enter num2 value ');
for n = num1 : num2
if isperfectnumber(n)
disp(n);
end
end
Now you just have to write the function isperfectnumber() that returns true if its input is a perfect number.
  3 Comments
Walter Roberson
Walter Roberson on 24 May 2015
As I wrote above:
"Now you just have to write the function isperfectnumber() that returns true if its input is a perfect number."
Josaiah Ang
Josaiah Ang on 24 May 2015
Thank you Walter.
i require some help on writing the function to determine the perfect number.
I have just only started using matlab for 2 weeks. Hope you could help me. Thank you.

Sign in to comment.


Image Analyst
Image Analyst on 23 May 2015
Here's something a little more user friendly and robust:
% Ask user for two floating point numbers.
defaultValue = {'45.67', '78.91'};
titleBar = 'Enter a value';
userPrompt = {'Enter floating point number 1 : ', 'Enter floating point number 2: '};
caUserInput = inputdlg(userPrompt, titleBar, 1, defaultValue);
if isempty(caUserInput),return,end; % Bail out if they clicked Cancel.
% Convert to floating point from string.
usersValue1 = str2double(caUserInput{1})
usersValue2 = str2double(caUserInput{2})
% Check for a valid number.
if isnan(usersValue1)
% They didn't enter a number.
% They clicked Cancel, or entered a character, symbols, or something else not allowed.
% Convert the default from a string and stick that into usersValue1.
usersValue1 = str2double(defaultValue{1});
message = sprintf('I said it had to be a number.\nI will use %.2f and continue.', usersValue1);
uiwait(warndlg(message));
end
I don't of any real world uses for a perfect number, so I assume that this is homework. So you can write that algorithm, like Walter said.

Roger Stafford
Roger Stafford on 23 May 2015
As part of your procedure in identifying a perfect number you need to determine the sum of all the divisors of a given integer, n, except n itself. This will find it for you:
N = 1:n-1;
s = sum(N(mod(n,N)==0));

Categories

Find more on Programming in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!