|
原帖由 〇〇 于 10-11-3 15:52 发表 ![]()
问题4:
Find the largest palindrome made from the product of two 3-digit numbers.
求能分解为两个三位数乘积的最大回文数。
SQL> select max(a.x) from (select b.x*c.x x from
2 (select level+100 x from dual connect by level <900)b,(select level+100 x from dual connect by level <900)c
3 )a where a.x>100000 and substr(a.x,1,3)=substr(a.x,6,1)||substr(a.x,5,1)||substr(a.x,4,1);
MAX(A.X)
----------
906609
最后部分可以用reverse函数简化的
另外根据乘法交换律,完全可以认为 b.x>=c.x
而且可以从数字特征去优化算法
比如9只可能由3×3或者1×9得到,8只能是1×8或者2×4,7只能是1×7 ——略有成效
select max(a.x) from (select b.x*c.x x from
(select level+100 x from dual connect by level <900)b,(select level+100 x from dual connect by level <900)c
where b.x>=c.x and substr(b.x, -1) in(1,2,3,4,7,8,9) and substr(c.x, -1) in (1,2,3,4,7,8,9) --从2.03s降低到
and (substr(b.x, -1), substr(c.x, -1)) in ((1,7),(1,8),(1,9),(2,4),(3,3),(7,1),(8,1),(9,1),(4,2)) --1.43s
)a where a.x>100000 and substr(a.x,1,3)=reverse(substr(a.x,4));
优先搜索7、8、9为尾数的(说明首位也是7、8、9),找不到再找下面的
而首位为7的6位数,如果是由两个三位数的乘积构成的,那这个三位数一定不小于700 ——此举大大降低了无谓的劳动
select max(a.x) from (select b.x*c.x x from
(select level+700 x from dual connect by level <300)b,(select level+700 x from dual connect by level <300)c --直接降低到0.25s
where b.x>=c.x and substr(b.x, -1) in(1,2,3,4,7,8,9) and substr(c.x, -1) in (1,2,3,4,7,8,9)
and (substr(b.x, -1), substr(c.x, -1)) in ((1,7),(1,8),(1,9),(2,4),(3,3),(7,1),(8,1),(9,1),(4,2))
)a where a.x>100000 and substr(a.x,1,3)=reverse(substr(a.x,4)); |
|