speeding up my for loop

조회 수: 18 (최근 30일)
Abhishek Sharma
Abhishek Sharma 2021년 2월 27일
댓글: Abhishek Sharma 2021년 2월 27일
%My challenge is to find the number of divisors for a number without using "divisors" inbuild function
%this program will work but it's taking too much time for big numbers
%I read about vectorization to reduce the time but found stucked
%help!!!
function y=divisors1(N)
sum=0;
for i=1:floor(N/2)
if lcm(N,i)==N
sum=sum+1;
end
end
y=1+sum;

채택된 답변

Bruno Luong
Bruno Luong 2021년 2월 27일
편집: Bruno Luong 2021년 2월 27일
function y=divisors2(N)
f = factor(N);
[~,~,J] = unique(f);
n = accumarray(J,1);
y = prod(n+1);
end
Test
>> N=27022021
N =
27022021
>> divisors2(N)
ans =
8

추가 답변 (1개)

Alan Stevens
Alan Stevens 2021년 2월 27일
Is this any quicker?
function y = divisors1(N)
i = 1:floor(N/2);
L = lcm(N,i);
y = sum(L==N) + 1;
end
  댓글 수: 1
Abhishek Sharma
Abhishek Sharma 2021년 2월 27일
Thanks Alan. Since the iterations haven't changed ,it still stucks for big numbers.

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

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by