Printing prime number in python - python

I am trying to print prime numbers in python in the range 3-50. Here is the code:
for i in range(3,51):
flag=0
for j in range(3,i):
if(i%j==0):
flag=1
if(flag==0):
print(i)
The code is running correctly except THAT IT IS ALSO PRINTING 4. Please tell if there is anything wrong with the logic of the code (ignore the efficiency issues).

print(2)
for i in range(3,51):
flag=0
for j in range(2,int(i/2)):
if(i%j==0):
flag=1
if(flag==0):
print(i)
When i = 4, the range will be range(2,2) which is 0. It will not enter the if(i%j == 0): block. Thus your flag would always be 0 when i = 4.
One way to solve it would be to just add a check if i is 4.
if(flag==0 and i != 4):
Edit : As commented by others, by incrementing the range by 1 would be a better fix than checking if the value is 4.
for j in range(2,int(i/2)+1)

change range(3,i) to range(2,i) because if we use range(3,i), 4 is not checked with division by 2. As a result 4 is returned as prime.
for i in range(3,51):
flag=0
for j in range(2,i):
if(i%j==0):
flag=1
if(flag==0):
print(i)
However, a more structural and efficient way is to use the following:-
def isPrime(num):
for i in range(2,num/2+1):
if (num%i==0):
return False
return True
for i in range(3,51):
if isPrime(i):
print i
We don't need to check the division by all numbers till the number itself for prime. Because if we can check till the half of the given number only for increased efficiency.

start = 3
end = 50
for val in range(start, end + 1):
# If num is divisible by any number
# between 2 and val, it is not prime
if val > 1:
for n in range(2, val):
if (val % n) == 0:
break
else:
print(val)

a = int(input("enter smaller no."))
b = int(input("enter larger no."))
for i in range (a,b+1):
if i>1:
for c in range(2,i):
if i%c == 0:
break
else:
print(i)
In the code above we ran a for loop from minimum to the maximum number and storing the value in i
for i in range (a,b+1):
then we check that the number stored in i is greater than 1 or not as all numbers are divisible by 1 and we don not want to consider it.
if i>1:
after this we run another loop, this time from 2 to 1 less then the number stored in i
for c in range(2,i):
Now we check that the number stored in i is divisible by any of the number from 2 to 1 number less then itself.
if i%c == 0:
If yes then clearly it is not a prime number and we break the loop.
break
And if no we print the number.
else:
print(i)

For 4 it probably does not go inside the if loop. So I increased the range for i.
print(2)
for i in range(3,51):
flag=0
for j in range(2,int(i/2)+1):
if(i%j==0):
flag=1
if(flag==0):
print(i)

for i in range(3,51):
flag=0
for j in range(2,i):
if(i%j==0):
flag=1
if(flag==0):
print(i)
This prints
3
5
7
11
13
17
19
23
29
31
37
41
43
47
4%2 = 0
4%3 = 1
So if you start from 3 you will miss out that 4%2 is = 0

If your list would have bigger numbers, you should change
range(2,int(i/2)+1)
for
range(2,math.floor(math.sqrt(n)+1))
For instance, 400 will try numbers until 20 instead of 200.

tryfor j in range(2,i):the numbers 4 is divisible is 1,2,4 if you start from 3 and continue until 4 but not four you can't find any divisors that is why it is considering 4 as a prime

import math
for num in range(1,50):
if num>1:
if num==2:
print(num)
elif num%2==0:
continue
else:
for i in range(3,math.ceil(math.sqrt(num)),2):
if num%i==0:
break
else:
print(num)
It is more efficient as it avoids even numbers and also check for the odd divisors up-to square root of the number which is more efficient than checking up-to only half of the given numbers

Related

Write a python script to print all Prime numbers between two given numbers (both values inclusive)

Write a python script to print all Prime numbers between two given numbers (both values inclusive)
can anyone please tell what am I doing wrong here ?
a = int(input("Enter the value of a : "))
b = int(input("Enter the value of b : "))
for k in range(a,b):
for i in range(2,k):
if k%i!=0:
if k!=i:
continue
elif k==i:
print(k)
break
elif k!=i:
break
you are checking if a number is prime the wrong way there are many
unhandled cases in your code for example if a is larger than b
you will start looping from "a" anyway
and even if the values are sat up correctly the algorithm is not right
here is my optimal solution hope it will help
a = int(input("Enter the value of a : "))
b = int(input("Enter the value of b : "))
def is_prime(n):
# negative numbers cannot be primes 1 and 0 are also not primes
if n <= 1:
return False
# since 2 is the first prime we will start looping from it
# until n since you mentioned that n is included
for i in range(2, n + 1):
# if n is cleanly divisible by any number less than n
# that means that n is not prime
if n % i == 0 and n != i:
return False
return True
for k in range(a,b):
if a > b:
print ("a cannot be bigger than b")
if is_prime(k):
print(k)
Here's the solution. I added some comments to explain what the code does.
a = int(input("Enter the value of a : "))
b = int(input("Enter the value of b : "))
# Include b in the range by adding 1
for num in range(a, b + 1):
# Prime numbers are greater than 1
if num > 1:
for i in range(2, num):
# If the number is divisible, it is not prime
if num % i == 0:
# Check if the number is equal to the number itself
if num != i:
break
else:
# If the loop was not broken, the number isn't divisible
# by other numbers except itself and 1, so it's prime
print(num)
Well, a prime is "a number that is divisible only by itself and 1", so to actually first I would go only to range(2, k-1). This approach you have is one of the most straightforward ways of doing it, and is not computationally friendly. There are algorithms that specialize in this kind of prime number finding.
I have fixed the code, simplifying the expressions and adding like already mentioned +1 for inclusivity.
a = int(input("Enter the value of a : "))
b = int(input("Enter the value of b : "))
for k in range(a,b+1):
for i in range(2,k+1):
if k==i:
print(k)
elif k%i!=0:
continue
else: # is divisible and isn't 1 or the number
break
I encourage you to see this post, how they do it.
An other way of doing it would be:
#Check only 1 number at time:
def check_prime(check):
if check > 1:
for i in range(2, check):
if check % i == 0:
return False
return True
return False
#then check your numbers in a loop
list_prime = []
for i in range(50, 250):
if check_prime(i):
list_prime.append(i)
print(list_prime)
That way you can check 1 possible prime number at time.
If you need numbers in between just put it in loop.
Usually, when generating prime numbers utilizing some form of the "Sieve of Erotosthenes" algorithm, it is only necessary to check for denominator values up to the square root of the number being evaluated. With that in mind, here is one more possible take on your prime number loop test.
import math
a = int(input("Enter the value of a : "))
b = int(input("Enter the value of b : "))
for k in range(a,b):
if k == 2 or k == 3: # Pick up the prime numbers whose square root value is less than 2
print(k)
x = int(math.sqrt(k) + 1) # Need only check up to the square root of your test number
for i in range(2,x):
if k%i!=0:
if x-1 > i:
continue
else:
print(k)
else: # If the remainder is zero, this is not a prime number
break
Another version to try.

Python prime list

integer = int(input("Enter an integer: "))
if integer >= 2:
print(2)
for i in range(2, integer + 1): # range 2,3,...,integer (excludes 1)
for j in range(2, i): # we are going to try dividing by these
if i % j == 0: # not prime
break
else: # is prime
print(i)
input:
7
output:
2
3
5
5
5
7
7
7
7
7
output I want:
2
3
5
7
adding more detail to get past error:
It looks like your post is mostly code; please add some more details.
You're printing i for every value of j that doesn't divide it, until you get a value that does divide it and you execute break.
You should only print i when you don't break out of the loop. Put the else: statement on the for loop, not if. This else: statement is executed when the loop finishes normally instead of breaking.
for i in range(2, integer + 1): # range 2,3,...,integer (excludes 1)
for j in range(2, i): # we are going to try dividing by these
if i % j == 0: # not prime
break
else: # is prime
print(i)
Put the print(i) in the outer for loop with a flag that keeps track of the result.
for i in range(2, integer + 1): # range 2,3,...,integer (excludes 1)
isPrime = True
for j in range(2, i): # we are going to try dividing by these
if i % j == 0:
isPrime = False
break
if isPrime:
print(i)
Your logic is slightly wrong. I have added the correct code below with comments :
integer = int(input("Enter an integer: "))
if integer >= 2:
print(2)
for i in range(2, integer + 1): # range 2,3,...,integer (excludes 1)
prime=true #assume that i is prime
for j in range(2, i): # we are going to try dividing by these
if i % j == 0: # not prime
prime=false # we now know it is not prime
break
if prime==true: # if we didn't do prime=0, then it's a prime
print(i)
What you were doing is printing i for every j from 2 to i that did not divide i. But instead, what had to be done is print i only once when none of the j from 2 to i divided i.
Hope you understand the mistake and this clears your doubt !

While loop doesn't read condition

I'm trying to make a program that will stop when it gets 5 prime numbers from a range.
I've completed most of the program except the part where it is supposed to stop after it gets 5 numbers.
I've added a condition for it to stop, once the counter reaches 5 but it does not stop and continues to list all the numbers in the range.
Here is code I have:
condition = 0
while condition < 5:
for numbers in range(2,20):
for divisor in range(2,numbers):
if (numbers % divisor) == 0:
break
else:
print(numbers)
condition +=1
The condition+=1 never goes through and it lists all the prime numbers from 1 to 20 even though I just want the first 5.
I've tried spacing options with the "condition +=1" but it still does not work
Any help would be appreciated
While is out of for loop, so cannot work obviously. A simple solution is to check required condition later:
for numbers in range(2,20):
for divisor in range(2,numbers):
if (numbers % divisor) == 0:
break
else:
print(numbers)
condition +=1
if condition >=5:
break
I think the real problem you are having is that you have written bad code. A much better approach to this problem is to isolate as many pieces as possible.
for example:
def is_prime(x):
"return true if x is prime, otherwise false"
# implement me!
return True
def get_first_n_primes_less_than_y(n, y):
number = 2
condition = 0
while condition != n and number < y:
if is_prime(number):
print(number)
condition += 1
number += 1
get_first_n_primes(5, 20)
The above code, with some tweaking can perform the same task. However, code like this is much simpler to debug and reason about because we have isolated chunks of code (is_prime, has nothing to do with the while loop)
num_results = 5
counter = 0
range_start = 2
range_end = 20
# iterate range
for number in range (range_start, range_end):
# iterate divisors
for divisor in range (2, number):
# check division
if (number % divisor) == 0:
break
else:
print ("%s is a prime number" % number)
counter += 1
break
# check if number of results has been reached
if counter == num_results:
break
# check if number of results has been reached
if counter == num_results:
break
The problem is that you need to run the entire content of the while block before you test the condition again.
Here is a way around
condition = 0
numbers=2
while condition < 5 and numbers < 20:
for divisor in range(2,numbers):
if (numbers % divisor) == 0:
break
else:
print(numbers)
condition +=1
numbers+=1

can I get the for loop to run the whole range?

This is my code. I am trying to find the prime numbers before or equal to the integer inputted. However, it seems that the loop stops when it sees an integer in the range that fits the requirements. Unfortunately, this is not I wanted it to do. I would like to make it run through all the tests in the range before making the judgement. Is this possible? If so, how do I do this? Thank you.
def getNumber(main):
n = int(input())
return n
def isPrime(n):
list=[2]
if n > 1:
for i in range(2, n+1):
for a in range (2, n):
if i*a != i and i%a != 0 and i%2 != 0:
list.append(i)
break
return "\n".join(map(str, list))`
def main():
n = getNumber(main)
print(isPrime(n))
main()
You've got your logic a bit wrong. Here's what your code is doing:
Examine numbers in increasing order from 2 to the inputted n.
For each number i, check if any number a between 2 and n divides i
If a divides i, add i to the list, and then move to the next i
This isn't going to get you a prime number. In fact, I'm having trouble figuring out what it will give you, but a prime number probably isn't it. Look at this function instead, which will return all the prime numbers less than or equal to the given number - you can compare it to your code to figure out where you went wrong:
def getPrimesLessThanOrEqualTo(n):
if n <= 1: # Anything 1 or less has no primes less than it.
return "" # So, return nothing.
list = [2] # 2 is the lowest prime number <= n
for i in range(3, n+1): # We start at 3 because there's no need to re-check 2
for a in list: # Instead of iterating through everything less than
# i, we can just see if i is divisible by any of
# the primes we've already found
if i % a == 0: # If one of the primes we've found divides i evenly...
break # then go ahead and try the next i
list.append(i) # Now, if we got through that last bit without
# hitting the break statement, we add i to our list
return "\n".join(list) # Finally, return our list of primes <= i
If you wanted to be more efficient, you could even use range(3, n+1, 2) to count by twos - thus avoiding looking at even numbers at all.
You can use a if/else block if your break is never executed by any item in the iterable the else statement will triggered. https://docs.python.org/3/tutorial/controlflow.html 4.4 demonstrates this accomplishing this almost exact task.
n = int(input('Enter number: '))
if n <= 1:
print('No primes')
else:
primes = []
for i in range(2, n +1):
for k in range(2, i):
if not i % k:
break
else:
primes.append(i)
print(*primes)
# Enter number: 50
# 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47

How do you find the first N prime numbers in python?

I am pretty new to python, so I don't fully understand how to use loops. I am currently working on a piece of code that I have to find the first N prime numbers.
The result that is desired is if you input 5, it outputs 2, 3, 5, 7, and 11, but no matter what I input for 'max', the output always ends up being 2 and 3. Is there a way to improve this?
max=int(input("How many prime numbers do you want: "))
min=2
while(min<=(max)):
for c in range(2, min):
if min%c==0:
break
else:
print min
min=min+1
You only increment min in the else block, i.e., if min % c is nonzero for all c, i.e., if min is prime. This means that the code won't be able to move past any composite numbers. You can fix this by unindenting min=min+1 one level so that it lines up with the for and else.
number = int(input("Prime numbers between 2 and "))
for num in range(2,number + 1):
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num)
Solution: Get the nth prime number entry. Iterate through each natural numbers for prime number and append the prime number to a list. Terminate the program when length of a list satisfies the user nth prime number entry.
# Get the number of prime numbers entry.
try:
enterNumber = int(input("List of nth prime numbers: "))
except:
print("The entry MUST be an integer.")
exit()
startNumber = 1
primeList = []
while True:
# Check for the entry to greater than zero.
if enterNumber <= 0:
print("The entry MUST be greater than zero.")
break
# Check each number from 1 for prime unless prime number entry is satisfied.
if startNumber > 1:
for i in range(2,startNumber):
if (startNumber % i) == 0:
break
else:
primeList.append(startNumber)
if (len(primeList) == enterNumber):
print(primeList)
break
else:
startNumber = startNumber + 1
continue
Try that :
n = int(input("First N prime number, N ? "))
p = [2]
c = 2
while len(p) < n:
j = 0
c += 1
while j < len(p):
if c % p[j] == 0:
break
elif j == len(p) - 1:
p.append(c)
j += 1
print(p)
Its simple. Check the below code, am sure it works!
N = int(input('Enter the number: ')
i=1
count=0
while(count<N):
for x in range(i,i+1):
c=0
for y in range(1,x+1):
if(x%y==0):
c=c+1
if(c==2):
print(x)
count=count+1
i=i+1
The following code will give you prime numbers between 3 to N, where N is the input from user:
number = int(input("Prime numbers between 2, 3 and "))
for i in range(2,number):
for j in range(2,int(i/2)+1):
if i%j==0:
break
elif j==int(i/2):
print(i)
You can see to check a number i to be prime you only have to check its divisibility with numbers till n/2.

Categories