-2

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)
tobias_k
  • 81,265
  • 12
  • 120
  • 179
Martin
  • 1
  • 4

1 Answers1

1

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.

paddyg
  • 2,153
  • 20
  • 24