Re: "Substract one and add one" algorithm

*To*: mathgroup at smc.vnet.net*Subject*: [mg59060] Re: "Substract one and add one" algorithm*From*: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>*Date*: Thu, 28 Jul 2005 02:26:04 -0400 (EDT)*Organization*: The Open University, Milton Keynes, U.K.*References*: <dc776m$k2h$1@smc.vnet.net>*Sender*: owner-wri-mathgroup at wolfram.com

Gilmar wrote: > Dear Mathematica Users Forum Friends: > > I want to build a function h[n] that does the following: > > For n even greater and equal than 4: > > Case 1: If m=n/2 is prime then h[n]={n/2,n/2}. Done. > > Case 2: If m =n/2 is not prime; let p[1]=n/2 -1 and q[1]=n/2+1. > > If both p[1], and q[1] are prime then, > h[n]={p[1],q[1]}. Done. > > If either one or both p[1] and q[1] are not prime; > let p[2] =p[1]-1, and q[2]=q[1]+1. > > If both p[2], and q[2] are prime then > h[n]={p[2],q[2]}. Done. > > If either one or both p[2] and q[3] are not prime; > let p[3] =p[2]-1, and q[3]=q[2]+1. > > etc. > > I want to test empirically that a value h[n] = {p[k],q[k]} > (for an appropriate integer k) exists. > > A few examples: > > > n=4 > n/2=2 is prime; so h[4]={2,2}. > > n=6 > n/2=3 is prime; so h[6]={3,3}. > > n=8 is not prime; so p[1]=n/2 -1 =3 is prime and q[1]=n/2+1=5 is prime; > so h[8]={3,5}. > > n=10 > n/2=5 is prime; so h[10]={5,5}. > > n=12 > n/2=6 is not prime; so p[1]=n/2-1=5 is prime and q[1]=n/2+1=7 is prime; > so h[12]={5,7}. > > > n=14 > n/2=7 is prime; so h[14]={7,7}. > > n=16 > n/2=8 is not prime; > so p[1]=n/2-1=7 is prime but, q[1]=n/2+1=9 is not prime, > so p[2]=7-1=6 is not prime, and q[2]=9+1=10 is not prime, > so p[3]=6-1=5 is prime, and q[3]=10+1=11 is prime, > so h[16]={5,11}. > > Thank you for your help! > Hi Gilmar, You could try something along the following lines: In[1]:= h[(n_)?(EvenQ[#1] && #1 >= 4 & )] := {n/2, n/2} /; PrimeQ[n/2] In[2]:= h[(n_)?(EvenQ[#1] && #1 >= 4 & )] := {n/2 - 1, n/2 + 1} /; PrimeQ[n/2 - 1] && PrimeQ[n/2 + 1] In[3]:= h[(n_)?(EvenQ[#1] && #1 >= 4 & )] := Module[{p, q}, p = n/2 - 1; q = n/2 + 1; checkpq[p, q]] In[4]:= checkpq[(p_)?Positive, q_] := {p, q} /; PrimeQ[p] && PrimeQ[q] In[5]:= checkpq[(p_)?Positive, q_] := checkpq[p - 1, q + 1] In[6]:= h[2] Out[6]= h[2] In[7]:= h[4] Out[7]= {2, 2} In[8]:= h[5] Out[8]= h[5] In[9]:= h[6] Out[9]= {3, 3} In[10]:= h[8] Out[10]= {3, 5} In[11]:= h[10] Out[11]= {5, 5} In[12]:= h[12] Out[12]= {5, 7} In[13]:= h[14] Out[13]= {7, 7} In[14]:= h[16] Out[14]= {5, 11} Best regards, /J.M.