How to write an efficient script for perfect numbers
8 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
K M
am 7 Apr. 2017
Kommentiert: Walter Roberson
am 25 Sep. 2017
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 Kommentare
Akzeptierte Antwort
KSSV
am 7 Apr. 2017
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 Kommentare
Grace Lim
am 25 Sep. 2017
@KSSV, sorry to bother you but can you explain this line '
factors =D(rem(k,D)==0)
Walter Roberson
am 25 Sep. 2017
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.
Weitere Antworten (0)
Siehe auch
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!