在mysql中检查数字是否为素数

时间:2017-03-29 19:13:14

标签: mysql sql

我想知道使用sql检查数字是否为素数的最佳方法是什么。我能够生成从1到1000的数字序列,但我想确定哪个数字是素数。有人可以分享你对此的看法。谢谢。

   document.getElementById('btn1').onclick = function()
   {
       alert('you clicked me');
   }

2 个答案:

答案 0 :(得分:1)

非常适合SQL。但你可以这样做:

select n.*
from n
where not exists (select 1
                  from n n2
                  where n2.n <= sqrt(n.n) and n2.n > 1 and
                        n.n mod n2.n = 0
                 ) and
      n > 1;  -- 1 is deemed to not be prime

您可能需要等待一段时间才能看到数字。

我应该注意到在MySQL中,生成数字的更简单方法是:

select (@rn := @rn + 1) as i
from (select 0 as i union select 1) as i0 cross join
     (select 0 as i union select 1) as i1 cross join
     (select 0 as i union select 1) as i2 cross join
     (select 0 as i union select 1) as i3 cross join
     (select 0 as i union select 1) as i4 cross join
     (select 0 as i union select 1) as i5 cross join
     (select 0 as i union select 1) as i6 cross join
     (select 0 as i union select 1) as i7 cross join
     (select 0 as i union select 1) as i8 cross join
     (select 0 as i union select 1) as i9 cross join
     (select @rn := 0) params
having i >= 1 and i <= 1000;

这应该更快,因为没有实现中间表。另外,加1可能比算术略快,但差别在于计算可能相当小。

答案 1 :(得分:1)

您可以使用self join检查生成的数字表中的素数。 Primes有2个因素,条件检查就足够了。

select val
from (select x.val,x1.val as divisor,mod(x.val,x1.val) as remaindr
      from x
      join x x1 on x1.val <= x.val
     ) t
group by val
having sum(case when remaindr = 0 then 1 else 0 end) = 2

Sample Demo

上述优化是检查1到sqrt(数字)范围内的除数。在这种情况下,素数的唯一因子是1,并且可以相应地改变条件检查。

select val
from (select x.val,x1.val as divisor,mod(x.val,x1.val) as remaindr
      from x
      join x x1 on x.val >= pow(x1.val,2)
      where x.val > 1 --excluding 1 as it is neither prime nor composite
     ) t
group by val
having sum(case when remaindr = 0 then 1 else 0 end) = 1