Monday, October 15, 2018

Python program to print Prime numbers

  • Python variables do not need explicit declaration to reserve memory space.
  • The declaration happens automatically when you assign a value to a variable.
  • The equal sign (=) is used to assign values to variables.
  • Statements always end in a NEWLINE.
  • A block is a group of statements in a program. code blocks are defined by their indentation in Python.

Sample Python Program with Output is given below
Print Prime numbers between 1 and 100


i=2
while i<=100:
    prime=True
    j=2
    while j<i and prime==True:
        if i % j ==0:
            prime=False
        j=j+1
    if prime==True:
        print(i)
    i=i+1


PythonSource


PythomOutputPrimeNumbers


Note

Efficient program than previous is given below
Reason for the new algorithm :
When we try to find the factors of number 20. The factors are 2,4,5,10,20. the last number is number itself. Previous number is less than half of the number. It is true for any number.

i=2
while i<=100:
    prime=True
    j=2
    while j<=int(i/2) and prime==True:
        if i % j ==0:
            prime=False
        j=j+1
    if prime==True:
        print(i)
    i=i+1

  
Click here to get the same program in Pascal




No comments:

Post a Comment