speeding up my for loop
1 次查看(过去 30 天)
显示 更早的评论
%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 个评论
采纳的回答
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
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
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!