【问题标题】:How can I count numbers in the given range?如何计算给定范围内的数字?
【发布时间】:2019-03-29 16:43:08
【问题描述】:

所以我写了一个代码,列出了所有不能被 2 和 3 整除的数字。现在我想知道这些数字中有多少是 1000。在谷歌搜索了一下之后,我没有找到任何可以帮我处理我的案子。

你们能给我一些建议吗?将不胜感激!

for i in range(1, 1000):

    if i%2 != 0 and i%3 != 0:

        print(i)

【问题讨论】:

  • 输入一个简单的count 并增加 if 块。
  • @DirtyBit 抱歉,您能解释一下吗?我不明白 count 是如何工作的

标签: python loops math


【解决方案1】:

范围已经定义,放一个count

count = 0
for i in range(1, 1000):
    if i%2 != 0 and i%3 != 0:
        count += 1
        print("The number is {}".format(i))   
print("Count: {}".format(count))

输出

The number is 1
The number is 5
The number is 7
The number is 11
The number is 13
.
.
.
The number is 991
The number is 995
The number is 997
Count: 333

编辑

单行

print("Count: {}".format(sum(1 for i in range(1000) if i%2 != 0 and i%3 != 0)))

【讨论】:

  • 或直接:sum(1 for i in range(n) if i%2 != 0 and i%3 != 0) 甚至sum(1 for i in range(0, n, 2) if i%3 != 0))
  • @hiroprotagonist 确实,添加了。谢谢!
  • 在数学上它只是(n-1 - n//2) + (n-1 - n//3) - (n-1 - n//(2*3))(可以简化,但我认为他的意思在这种形式下更清楚)......
【解决方案2】:
count=0

for i in range(1, 1000):

if i%2 != 0 and i%3 != 0:
    count=count+1
    print(i)

只需在 IF 块内进行计数

【讨论】:

    【解决方案3】:

    能被 2 整除的数有 1000/2 = 500 个,能被 3 整除的数有 1000/3 = 333 个。其中,6 的倍数出现两次,有 1000/6 = 165 个。

    因此 1000 - (500 + 333 - 166) = 333。

    最多可达到1,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000-333,333,333,333,33,3333333333333-1666666666666666666666666666666)

    【讨论】:

      【解决方案4】:

      最简单的解决方案是在循环中放入一个count 变量并递增它。

      count = 0
      for i in range(1, 1000):
      if i%2 != 0 and i%3 != 0:
          count+=1
          print(i)
      print(count)
      

      另一种解决方案可能是:

      count = len([x for x in range(1,1000) if x%2!=0 and x%3!=0])
      

      【讨论】:

        【解决方案5】:
        def number_of_not_divisible(a, b, myrange):
        result = 0
        least_common_multiple = a * b
        while myrange % least_common_multiple != 0:
            if myrange % a != 0 and myrange % b != 0:
                result += 1
            myrange -= 1
        partial_result_inside_one_range = 0
        for i in range(least_common_multiple):
            if i % a != 0 and i % b != 0:
                partial_result_inside_one_range += 1
        
        result += partial_result_inside_one_range * (myrange / least_common_multiple)
        print(result)
        

        number_of_not_divisible(2, 3, 1000)

        您可以使其更简单、更通用。可以看到,在每个大小为两个数的最小公倍数的区间内,搜索到的元素个数都是相同的。所以你只需要在第一个间隔中计数,并且必须对其进行倍数,并且在计数之后,范围内的数字%最小公倍数。我认为它必须通用,但是如果您弄错了,请告诉我。

        【讨论】:

        • 大迭代速度更快。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-11-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-11
        • 2013-02-15
        • 2019-05-22
        相关资源
        最近更新 更多