我有作业,让程序确定可被 3 和 2 整除的数字,但我只能尝试同时被 3 和 2 整除,就像这样
-- --------------------------------------------------------------------------------
-- Routine DDL
-- Note: comments before and after the routine body will not be stored by the server
-- --------------------------------------------------------------------------------
DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `divisible`()
BEGIN
declare str VARCHAR(255) default '';
declare x INT ;
SET x = 1;
set str = '';
while x <= 100 do
if (x mod 3=0 && x mod 2 =0) then
set str= CONCAT(str, x ,',') ;
end if;
set x=x+1;
end while;
SELECT str ;
END
上述过程的输出:'6,12,18,24,30,36,42,48,54,60,66,72,78,84,90,96,'
如何制作不同的输出,以便在 1-100 之间被 3 : 3,6,9,12 ... 和 2 : 2,4,6,8 整除。
最佳答案
首先,您只需认识到所有数字都是 6 的倍数,就可以获得可被 2 和 3 整除的数字列表:
set m = 6;
set x = m;
set str = '';
while x <= 100 do
set str = CONCAT(str, x ,',');
set x = x + m;
end while;
当然,您可以使用相同的方法通过简单地将乘数 m
更改为其他值来获取任何倍数的列表。
如果您想要可被二或三整除的数字(而不是二和三),您只需更改原始代码以使用或
代替和
:
if (x mod 3 = 0 || x mod 2 = 0) then
关于mysql - 查找 1-100 之间可被 3 和 2 整除的数字的过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40867462/