Search code examples
pythonfunctionsieve-of-eratosthenes

python - sieve of Eratosthenes when number is prime print "1" when not print "0"


I must create a function f(n) which value is 1 when the number is prime or value is 0 when isn't prime. Code is working but prints in revers order. For example: 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)

Solution

  • Reverse the loop like:

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

    PS I have seen good examples of how to actually implement a sieve of Eratosthenes in python on Stack Overflow, worth searching for a better solution.