How to write an efficient script for perfect numbers

8 ビュー (過去 30 日間)
K M
K M 2017 年 4 月 7 日
コメント済み: Walter Roberson 2017 年 9 月 25 日
I have to display the first 4 perfect numbers but am running into a problem. The way I am trying it takes very very long to reach the last value (8128 or whatever). Figured out how to post code (there's a freaking button for it lol...)
for k = 1:9000
factors = divisors(k);
factors(end) = [];
if sum(factors) == k
disp(k)
end
  2 件のコメント
KSSV
KSSV 2017 年 4 月 7 日
You have to show code to figure out your difficulty..
K M
K M 2017 年 4 月 7 日
As I was about to comment I just saw the button for 'code' lol... Anyway here's what I have:
for k = 1:9000
factors = divisors(k);
factors(end) = [];
if sum(factors) == k
disp(k)
end

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

採用された回答

KSSV
KSSV 2017 年 4 月 7 日
Try this:
for k = 1:9000
% factors = divisors(k);
D = 1:k ;
factors =D(rem(k,D)==0) ;
factors(end) = [] ;
if sum(factors) == k
disp(k)
end
end
  3 件のコメント
Grace Lim
Grace Lim 2017 年 9 月 25 日
@KSSV, sorry to bother you but can you explain this line '
factors =D(rem(k,D)==0)
Walter Roberson
Walter Roberson 2017 年 9 月 25 日
rem(k,D) is the remainder when k is divided by D, which will be 0 when D exactly divides k. This code uses logical indexing to extract the exact divisors.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeFunctional Programming についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by