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.
  • Video Tutorial on Prime Numbers


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")

All Sample codes
Fibonacci series Factors of a number Factorial of a number Armstrong Number


plus2net.com



Post your comments , suggestion , error , requirements etc here





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-2021 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer