用MySQL的存储过程来实现一些经典函数
质数判断
Java原型
boolean isPrime(int n) {
if (n<2) {return false;}
else if (n==2) {return true;}
else if (n%2==0) {return false;}
else {
for (int i=3;i<=(int)Math.sqrt(n);i+=2) {
if (n%i==0) {return false;}
}
return true;
}
}
MySQL实现
# 判断质数
delimiter //
create procedure isprime(n int)
begin
declare isprime boolean default true;
declare n_sqrt int default sqrt(n);
declare i int default 3;
declare p int default 2; # 因数
if n<2 then
set isprime = false;
elseif n=2 then
set isprime = true;
elseif n%2=0 then
set isprime = false;
else
t:while i<n_sqrt do
if n%i=0 then
set isprime = false;
set p = i;
leave t;
end if;
set i = i+2;
end while t;
end if;
if isprime then
select n,'true' as 'isPrime' from dual;
else
select n,'false' as 'isPrime', p from dual;
end if;
end //
delimiter ;
call isprime(65536); # 测试1
call isprime(2333); # 测试2
drop procedure isprime; #测试完删除存储过程
输出
MariaDB [mydb]> call isprime(65536);
+-------+---------+------+
| n | isPrime | p |
+-------+---------+------+
| 65536 | false | 2 |
+-------+---------+------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.04 sec)
MariaDB [mydb]> call isprime(2333);
+------+---------+
| n | isPrime |
+------+---------+
| 2333 | true |
+------+---------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.04 sec)
未完待续