Prime numbers in Python

Prime numbers are having only two factors, one is 1 and other one is the number itself.
These are the first 5 prime numbers 2, 3, 5, 7, 11
Prime numbers are divisible by exactly two natural numbers.

Prime numbers up to some value or fixed numbers by using for and while loop in Python


Here is the code to get prime numbers up to some value.
#n=int(input("Enter a number : "))
n=50 # change this value
for i in range(2,n+1):
    flag=0
    for j in range(2,int(i/2)+1):
        if(i%j==0):
            flag=1
            break  
    if(flag==0):
        print(i,end=', ')
Output
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47,
In above code we can remove the comment at first line and add comment to 2nd line to ask the user to input a number. By default all inputs are string so we need to convert this to integer by using int() function.
Factors of a number

Fixed number of Prime numbers

We can generate 10 or 15 numbers of prime numbers starting from 2.
This code will generate 10 Prime numbers, you can change the value to get more prime numbers.
n=1
i=2
while ( n <= 10): # change this value for more numbers
    b=0
    for j in range(2,int(i/2)+1):
        if(i%j==0):
            b=1
            break  
    if(b==0):
        print(i,end=', ')
        n=n+1
    i=i+1
Output
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 

Check if input number is prime or not

n=int(input("Enter number :"))
for i in range(2,n):
    if(n%i==0):
        print("composite/Not a prime number")
        break
else:
 print("prime number")
One more way to generate Prime numbers
num=100 # Upper limit of prime numbers 
i=2
while i<=num-1:
  j=2 # start checking each number from 2 
  while j <= i/2 : # check upto half the number 
    if(i%j==0): # reminder of division is 0 
        break  # come out of loop without else part
    j=j+1
  else:
    print(i, " is a prime number") # if break is not encountered 
  i=i+1

All Sample codes
Fibonacci series Factors of a number Factorial of a number Armstrong Number
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer