【问题标题】:python - sieve of Eratosthenes when number is prime print "1" when not print "0"python - 当数字是素数时,Eratosthenes 的筛子打印“1”,而不是打印“0”
【发布时间】:2015-04-22 14:54:56
【问题描述】:

我必须创建一个函数f(n),当数字是素数时它的值是1,或者当不是素数时它的值是0。 代码正在运行,但以相反的顺序打印。 例如:f(6)= 0 0 1 1 0 1 0

def prime(n):
    if n<2: return False
    for i in range(2,n):
        if n%i == 0:
            return False
    return True

def f(n):
    print('0', end=' ')
    a=1
    while a<=n:
        n=n-1
        print('1' if prime(n) else '0', end=' ')

f(6)

【问题讨论】:

  • 不是 sieve。这只是一个循环计数数字并天真地测试它们是否是素数。但是如果你想反转输出的顺序,只需反转循环即可。
  • 我不知道怎么做:while n>=a?
  • 检查 this post 以获取筛子示例。你所拥有的只是一个非常低效的质数检查。
  • 我也会用 sqrt(n) 切换出 n。它会节省一些时间:)
  • 误导性标题和标签。

标签: python function sieve-of-eratosthenes


【解决方案1】:

像这样反转循环:

def f(n):
  print('0')
  for a in range(1, n+1):
    print('1' if prime(a) else '0')

PS 我在 Stack Overflow 上看到了如何实际在 python 中实现 Eratosthenes 筛子的好例子,值得寻找更好的解决方案。

【讨论】:

    猜你喜欢
    • 2017-08-29
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-11
    • 1970-01-01
    相关资源
    最近更新 更多