creating a perfect number function

조회 수: 19 (최근 30일)
Fu Xiangli
Fu Xiangli 2016년 8월 30일
편집: Guillaume 2018년 9월 10일
Hi. I am currently having a prob. I need to create a function that takes in the number(n) as argument and returns true if n is a perfect number. I am not allowed to use vectors and for loop for this question. I am stuck at this few codes:
function num = perfect(n)
i=1;
sum = 0;
while i <= n/2
if rem(n,i) == 0
else
i = i +1
end
sum = sum + i;
end
if n == sum
n = true
I am a beginner in Matlab and I require assistance. Any kind soul out there to help me? Thanks!
  댓글 수: 1
John D'Errico
John D'Errico 2016년 8월 30일
Using the name sum as a variable name will create problems down the road for you. Don't name variables the same as useful functions that you will later need. Or expect to see lots of bugs in your code. Of course, you might like buggy code. Your choice.

댓글을 달려면 로그인하십시오.

채택된 답변

Guillaume
Guillaume 2016년 8월 30일
First and foremost, learn to use matlab's debugger. Step through your code, see how the variables change after each instruction, and check that the result was what you expected.
There is clearly a problem with your code. You have a while loop that essentially says:
while i is some value
if some condition
do nothing. Particularly, do not change i
else
change i
end
do something that does not change i
end
You can see that under some condition i never changes, so the loop will repeat infinitely. You need to fix that.
As per John's comment, don't use sum as a variable name, as you won't be able to use the sum function.
Also note that
if somecondition
else
do something
end
is better written as
if ~somecondition
do something
end
  댓글 수: 2
Fu Xiangli
Fu Xiangli 2016년 8월 31일
Yup I got the answer already. Apparently my initial code was rubbish. I have got the code as below:
function num = is_perfect(n)
i = 1;
factorsum = 0;
while i<= n-1
if rem(n,i) == 0
factorsum = factorsum + i;
end
i = i +1;
end
if n == factorsum
num = true;
else
num = false;
end
If there is any areas for improvement do let me know! Thank you guys!
Guillaume
Guillaume 2016년 8월 31일
Yes, that's much better.
One small improvement you can do is get rid of the final if and simply do:
num = n == factorsum;

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

alex usefi
alex usefi 2018년 9월 10일
How to get numbers like this from the code? is_perfect(6)
show result code: 1 2 3
  댓글 수: 1
Guillaume
Guillaume 2018년 9월 10일
편집: Guillaume 2018년 9월 10일
Please start your own question rather than highjacking the answer box of an another question for something that clearly is not an answer.
Note that I would expect that a function called is_perfect to return either true or false, not a vector of numbers.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by