📌  相关文章
📜  打印所有不能被 2 或 3 整除的整数的Python程序

📅  最后修改于: 2022-05-13 01:54:47.890000             🧑  作者: Mango

打印所有不能被 2 或 3 整除的整数的Python程序

我们可以输入一组整数,并通过检查整数的余数与2和3来检查该范围内以1开头的哪些整数不能被2或3整除。

例子:

Input: 10
Output: Numbers not divisible by 2 and 3
1
5
7

方法一:我们用and子句检查这个数是否不能被2和3整除,然后输出这个数。

Python3
# input the maximum number to
# which you want to send
max_num = 20
  
# starting numbers from 0
n = 1
  
# run until it reaches maximum number
print("Numbers not divisible by 2 and 3")
while n <= max_num:
      
    # check if number is divisible by 2 and 3
    if n % 2 != 0 and n % 3 != 0:
        print(n)
      
    # incrementing the counter
    n = n+1


Python3
# input the maximum number to
# which you want to send
max_num = 40
print("Numbers not divisible by 2 or 3 : ")
  
# run until it reaches maximum number
# we increment the loop by +2 each time,
# since odd numbers are not divisible by 2
for i in range(1, max_num, 2):
      
    # check if number is not divisible by  3
    if i % 3 != 0:
        print(i)


输出:

Numbers not divisible by 2 and 3
1
5
7
11
13
17
19

方法二:我们从 1 开始遍历奇数,因为偶数可以被 2 整除。因此,我们将 for 循环增加 2,只遍历奇数并检查其中一个不能被 3 整除。这种方法是比前一个更好,因为它只迭代指定范围内元素数量的一半。

以下Python代码说明了这一点:

蟒蛇3

# input the maximum number to
# which you want to send
max_num = 40
print("Numbers not divisible by 2 or 3 : ")
  
# run until it reaches maximum number
# we increment the loop by +2 each time,
# since odd numbers are not divisible by 2
for i in range(1, max_num, 2):
      
    # check if number is not divisible by  3
    if i % 3 != 0:
        print(i)

输出:

Numbers not divisible by 2 or 3 : 
1
5
7
11
13
17
19
23
25
29
31
35
37