my question is: how to move to the next loop in PARI/GP if I use multi-line nested for loops ? for example :
if I use this code :
for(K=1,10,for(i=1,5,if(isprime(2*i*prime(K)+1)==1,print(2*i"*"prime(K)))))
and since 2*(i=1)*prime(K=1)+1=5 is prime, I need my machine not to loop for i=2......i=5, I need it to move on to the next K, so:
how to do this on PARI/GP?
and I am sorry if my question is not clear or duplicated.
You need to use break. But first, let's clean up the presentation so this is more readable:
func()=
{
for(K=1,10,
for(i=1,5,
if(isprime(2*i*prime(K)+1)==1,
print(2*i"*"prime(K))
)
)
);
}
func()
You want to break out of the innermost loop, like so (just giving the function itself):
func()=
{
for(K=1,10,
for(i=1,5,
if(isprime(2*i*prime(K)+1)==1,
print(2*i"*"prime(K));
break
)
)
);
}
But while we're here, there's no need to add == 1
; if
is already branching on nonzero values.
func()=
{
for(K=1,10,
for(i=1,5,
if(isprime(2*i*prime(K)+1),
print(2*i"*"prime(K));
break
)
)
);
}
We could also store the value of prime(K) so we don't need to compute it twice. But better yet, let's use a loop directly over the primes so we don't need the prime()
function at all!
func(maxK=10)=
{
my(K=0);
forprime(p=2,prime(maxK),
K++;
for(i=1,5,
if(isprime(2*i*p+1),
print(2*i"*"p);
break
)
)
);
}
Here I have changed the function so you can call it with different maximum values other than 10 and I've kept the index in case you wanted it for some reason. But I think a better approach would be to give a bound on how high you want to go in the primes directly, and forgetting about the prime indexes entirely:
func(maxP=29)=
{
forprime(p=2,maxP,
for(i=1,5,
if(isprime(2*i*p+1),
print(2*i"*"p);
break
)
)
);
}
In both cases I added a default argument so calling func()
will do the same thing as your original function (except that it now breaks the way you want).