performance - Improving the code for Lemoine's conjecture -
i trying improve following code:
the code written solve following equation:
2*n + 1 = p + 2*q this equation denotes given integer number n value 2*n + 1 can represented p + 2*q p , q prime numbers. has been proved many years ago , called lemoine's conjecture.
the input code number (n>2) , output matrix including 2 columns of valid prime numbers.
n = 23; s = 2*n+1; p = primes(s); v = []; kk = 1; ii=1:length(p) jj=1:length(p) if (s == p(ii)+2*p(jj)) v(kk,:) = [p(ii) p(jj)]; kk = kk + 1; end end end the result ;
v = 13 17 37 5 41 3 43 2 and instance:
2*23+1 = 43 + 2*2 is there way rid of loops in matlab?
update:
suggested @daniel, works
n = 23; s = 2*n+1; p = primes(s); ii=1:length(p) if ismember(s - p(ii),p) v(kk,:) = [p(ii) s-p(ii)]; end end
you can replace loops vectorized solution using bsxfun -
[r,c] = find(bsxfun(@eq,p-s,-2*p(:))); v = [p(c) ; p(r)].' with n = 100000, runtimes got -
------------ loopy solution elapsed time 33.789586 seconds. ----------- bsxfun solution elapsed time 1.338330 seconds.
Comments
Post a Comment