MATLAB解决素数环问题
代码
function s = primeCircle1(n)
% find the prime circle of 1--2n
% such that each sum of consecutive two terms is prime
n=2*n;
s=dfs(n,1);
function s=dfs(n,step)
persistent visit;
persistent a;
if isempty(visit)
visit=zeros(1,n);
visit(1)=1;
a=visit;
end
if step==n&&isprime(a(n)+a(1))
s=a;
return
else
for k=2:n
if visit(k)==0&&isprime(k+a(step))
a(step+1)=k;
visit(k)=1;
dfs(n,step+1);
visit(k)=0;
end
end
end
运行结果及报错
Output argument "s" (and possibly others) not assigned a value in the execution with "primeCircle1>dfs" function.
出错 primeCircle1 (第 5 行)
s=dfs(n,1);