Home > Software design >  please explain me how this program works?
please explain me how this program works?

Time:10-30

def print_prime_1_n(n):
  for i in range(1, n 1):
    prime = True
    for j in range(2, i):
      if i % j == 0:
        prime = False
        break
    if prime:
      print(i)

print_prime_1_n(10)

I spent 2 days to figure out this code but i coudn't find a way to figout it out. please explain to me?

CodePudding user response:

I hope this helps:

def print_prime_1_n(n):
    # For all numbers from 1 to n 1
    for i in range(1, n 1):
        # Assume i is prime until proven otherwise
        prime = True
        # For all numbers from 2 to i (second number used to check if i is prime)
        for j in range(2, i):
            # If i is divisible by j, then i is not prime because it is divisible by a number other than 1 and itself
            if i % j == 0:
                # Set prime to False
                prime = False
                # Short circuit the loop because we know i is not prime
                break

        # If prime is still True, then i is prime and we can print it
        if prime:
            print(i)

print_prime_1_n(10)

CodePudding user response:

This function is a naive (or brute force) algorithm that prints all prime numbers between 1 and n

From the wiki: A prime number (or a prime) is a natural number greater than 1 that is not a product of two smaller natural numbers

How does this function works?

  1. We're looping through all natural numbers between 1 and n that we want to check (is it a prime?)
    for i in range(1, n 1):

  2. By default at the beginning we think that this number is prime

prime = True

And if this variable stays true after checking, we're printing current number

if prime:
  print(i)
  1. And the final step is to check for prime
for j in range(2, i):
  if i % j == 0:
    prime = False
    break

i % j means remainder of division of i by j
i - our current number we're checking
j - the number less than i by which we are trying to divide

If the i % j equals to 0, then i is divisible without a remainder by j, so our number is composite, not prime, as it has a divisor

Therefore we set prime = False and exiting our inner loop with break (we don't have to check further)

Note that we loop from 2 to i because upper bound i is not included, so we're looping between 2 and i - 1

CodePudding user response:

def is_prime(i):
    
    # if I is divisible by any number smaller than it, it is not prime

    prime = True
    for j in range(2, i):
      if i % j == 0: # divisibility check
        prime = False
        break
    return prime

def print_prime_1_n(n):
  for i in range(1, n 1):
    if is_prime(i):
      print(i)

print_prime_1_n(10)
  • Related