MATLAB Answers

# speeding up my for loop

25 views (last 30 days)
Abhishek Sharma on 27 Feb 2021
Commented: Abhishek Sharma on 27 Feb 2021
%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;
##### 0 CommentsShowHide -1 older comments

Sign in to comment.

### Accepted Answer

Bruno Luong on 27 Feb 2021
Edited: Bruno Luong on 27 Feb 2021
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 CommentShowHide None
Abhishek Sharma on 27 Feb 2021
Thanks Bruno.

Sign in to comment.

### More Answers (1)

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

Sign in to comment.

### Community Treasure Hunt

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

Start Hunting!

Translated by