尤拉計劃425題:質數連線

lt發表於2017-02-23

兩個正整數A和B被稱為相連的(用”A ↔ B”表示)如果以下條件之一成立:
(1)A和B的位數相同,且只有一位數字不同,例如123 ↔ 173。
(2)在A(或B)的左側加一位數字即得到B(或A),例如23 ↔ 223和123 ↔ 23。
我們稱質數P是2的親戚,如果能用相連的質陣列成的鏈連線2和P,且這些質數都不超過P。

例如,127是2的親戚。其中一種質數串如下所示: 2 ↔ 3 ↔ 13 ↔ 113 ↔ 103 ↔ 107 ↔ 127
然而,11和103不是2的親戚。
記F(N)是所有≤ N且不是2的親戚的質數和。 可以驗證F(103) = 431以及F(104) = 78728。
求F(107)。

思路:求出可能的親戚連線路徑,找出不在任何路徑中的質數
下面的sql求出路徑

with t as(select level+1 l from dual connect by level<100),
n as(select level n from dual connect by level<8)
,pr as(select l from t
minus
select a.l*b.l from t a,t b
where b.l>=a.l),
lk(c,d,t) as(
select c.l,d.l,1 tp from pr c,pr d
where c.l<d.l and length(c.l)=length(d.l) and exists(select 1
from n where n<=length(c.l) having
length(c.l)-1 =  sum(decode(substr(c.l,n,1),substr(d.l,n,1),1,0)))
union all
select c.l,d.l,2 tp from pr c,pr d
where c.l<d.l and length(c.l)=length(d.l)-1 and c.l=substr(d.l,2))
select distinct
sys_connect_by_path(c,'/')
from lk
connect by prior d=c
start with c=2
;

上述程式碼的問題是單向的,即後面的總是比前面的大,漏了123 <-> 23這種,但是把 c.ld.l後,太慢了.“且這些質數都不超過P”這個條件也沒實現,感覺從路徑中再拆分出來,求max (其餘的) 比最後一個小的,有點笨.

with t as(select level+1 l from dual connect by level<100),
n as(select level n from dual connect by level<8)
,pr as(select l from t
minus
select a.l*b.l from t a,t b
where b.l>=a.l),
lk(c,d,t) as(
select c.l,d.l,1 tp from pr c,pr d
where c.l<>d.l and length(c.l)=length(d.l) and exists(select 1
from n where n<=length(c.l) having
length(c.l)-1 =  sum(decode(substr(c.l,n,1),substr(d.l,n,1),1,0)))
union all
select c.l,d.l,2 tp from pr c,pr d
where c.l<>d.l and length(c.l)=length(d.l)-1 and c.l=substr(d.l,2)),
re(re) as(
select distinct
sys_connect_by_path(c,'/')
from lk
connect by nocycle prior d=c
start with c=2)
select l from pr where not exists(select 1 from re where instr(re||'/',   '/'||l||'/')>0); 

相關文章