最近在看C#方面的书,正好看到迭代器这块,里面有个查询素数的示例我觉得还不错,于是就想到SQL也来实现一把。
其实有很多种方法,我大概列下下面。结果就只贴一个好了:
方法1: 最简单粗暴的算法
DECLARE @i INT , @j INT , @r INT SET @i = 2 WHILE @i < 100 BEGIN SET @j = 1 SET @r = 1 WHILE @j < @i BEGIN IF @i % @j = 0 AND @i <> @j AND @j <> 1 BEGIN SET @r = 0 BREAK END SET @j = @j + 1 END IF @r = 1 PRINT @i SET @i = @i + 1 END
方法二:来自叶子,用平方根计算,比方法1提升了一点效率
--定义一个表变量,用来存储找到的素数 DECLARE @t TABLE ( id INT ) DECLARE @i INT SET @i = 2 WHILE ( @i <= 100 ) BEGIN DECLARE @j INT SET @j = SQRT(@i) WHILE ( @j >= 2 ) BEGIN IF ( @i % @j = 0 ) BREAK SET @j = @j - 1 END IF ( @j = 1 ) INSERT INTO @t SELECT @i SET @i = @i + 1 END
方法三:
借助系统表 还是用平方根
DECLARE @i INT SET @i = 100 SELECT A.number FROM master..spt_values AS A WHERE type = 'p' AND number BETWEEN 2 AND @i AND NOT EXISTS ( SELECT 1 FROM master..spt_values AS B WHERE B.type = 'p' AND B.number BETWEEN 2 AND SQRT(A.number) AND A.number % B.number = 0 ) ORDER BY A.number
最后附上C#解决办法:用控制台程序解决
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ch11Ex03 { class Program { public class Primes { private long min; private long max; public Primes(): this(2, 100) { } public Primes(long minimum, long maximum) { if (min < 2) min = 2; else min = minimum; max = maximum; } public IEnumerator GetEnumerator() { for (long possiblePrime = min; possiblePrime <= max; possiblePrime++) { bool isPrime = true; for (long possibleFactor = 2; possibleFactor <= (long)Math.Floor(Math.Sqrt(possiblePrime)); possibleFactor++) { long remainderAfterDivision = possiblePrime % possibleFactor; if (remainderAfterDivision == 0) { isPrime = false; break; } } if (isPrime) { yield return possiblePrime; } } } } static void Main(string[] args) { Primes primesFrom2To100 = new Primes(2, 100); foreach (long i in primesFrom2To100) Console.Write("{0}\n", i); Console.ReadKey(); } } }