num1 =input('Enter your 1st number: ');
num2 =input('Enter your 2nd number: ');
%returns an 1-by-num2 matrix of zeros
PerfectNumber= zeros(1,num2);
for pp = num1:num2 % pp = Potential Perfect number, variable for the range
if true
end
pd = 1:pp-1;
%test all potential numbers up to pp-1 because of the definition of a perfect number.
%potential divisors, named 'pd' in the code
if (sum(pd(mod(pp,pd) == 0)) == pp)
%mod(pp,pd) returns the remainder after dividing pp by pd.
%If a number is a divisor, the remainder is 0, so mod return zero.
%check if the sum of all divisors = pp
PerfectNumber(pp) = pp;
%it have found a perfect number and store this number in a variable 'output' at the pp'th position
if false
else PerfectNumber (PerfectNumber == 0) = [];
%all positions where output is 0 are replaced by the empty matrix []
fprintf ('\nThe Perfect Numbers are : %d', PerfectNumber);
%And it will print out the name line + the perfect number
end
%After this loop we have the perfect numbers at the position of the perfect numbers.
end
end
fprintf ('\nThe program ends here, Good bye %s !',un);
%to inform the user that the program has ended or when the entry is invalid it end the program.
end
And my out put would be
Enter your 1st number: 1
Enter your 2nd number: 50
The Perfect Numbers are : 6
The Perfect Numbers are : 6
The Perfect Numbers are : 28
The program ends here, Good bye !>>
What should i do to my code so that it only print the line "The Perfect Numbers are : 6" once and not double like this.

2 件のコメント

Paolo
Paolo 2018 年 5 月 31 日
Try changing:
PerfectNumber(pp) = pp;
to
PerfectNumber = pp;
Laeya
Laeya 2018 年 5 月 31 日
Thank you so much ! yours work well too !

サインインしてコメントする。

 採用された回答

Rishabh Rathore
Rishabh Rathore 2018 年 5 月 31 日
編集済み: Rishabh Rathore 2018 年 5 月 31 日

0 投票

What is happening is that you are actually printing the whole vector instead of the latest 'perfect Number'.
Make your print line look like below.
fprintf ('\nThe Perfect Numbers are : %d', PerfectNumber(end));

2 件のコメント

Laeya
Laeya 2018 年 5 月 31 日
Thank you so much for the help! been stuck on this for so long!!
Paolo
Paolo 2018 年 5 月 31 日
The question here is whether you need all the numbers in PerfectNumber in a different stage of the code. If you do not, there is no reason for you to have
PerfectNumber(pp) = pp;
as I mentioned in the comment.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeFunction Creation についてさらに検索

質問済み:

2018 年 5 月 31 日

コメント済み:

2018 年 5 月 31 日

Community Treasure Hunt

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

Start Hunting!

Translated by