prime numbers in python using for loop and break - python

I have written a python code to find prime numbers between 2 and 30. But my code is not evaluating for 2 and 3. Can anyone tell me what is wrong in this code?
for i in range(2, 30):
for j in range(2, i-1):
if ((i % j) == 0):
print(i, "is not a prime number")
break
else:
print(i, "is a prime number")
break

The logic of your code is wrong. The else clause should be attached to the inner for loop, so it's only executed if the loop is exhausted without finding a divisor.
for i in range(2, 30):
for j in range(2, i-1):
if ((i % j) == 0):
print(i, "is not a prime number")
break
else:
print(i, "is a prime number")
Also note that the outer loop only runs up to 29, since the upper boundary is not included in a range. The inner loop does not include i - 1, but that's totatlly fine, since any non-trivial divisor is less than i - 1.
The inner loop won't be entered at all for 2 and 3, since the range will be empty in these cases. This is fine as well, since the else clause will be immediately entered.

for i in range(2, 30):
prime = True
for j in range(2, i-1):
if ((i % j) == 0):
prime = False
# print(i, "is not a prime number")
break
# else:
# print(i, "is a prime number")
# break
if prime:
print(i, "is a prime number")
else :
print(i, "is not a prime number")
There are lot of online link to solve the prime number problem. To improve yourself search yourself and understand the. Hope this and this link help you a lot. Happy codding

It isn't working because the nested for declaration:
for i in range(2, 30):
for j in range(2, i-1):
Uses range(2, i-1) and until i is 4, range returns no value:
i = 2 --> range(2, 1) # No value
i = 3 --> range(2, 2) # No value
i = 4 --> range(2, 3) # 2
This is because the range function returns values from the first parameter (included) to the second parameter (not included).

Related

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 !

can we find prime number in a list?

I want a list of n numbers and check each item for primality and log whether the given number is prime or not. Unfortunately my below shown code is working incorrectly and I need help finding out why is it happening.
My code snippet:
l1 = []
num = int(input("Enter a range of numbers :: "))
for i in range(2, num + 1):
l1.append(i)
for i in range(0, num - 1):
for j in range(2, num):
if l1[i] % j == 0:
print(f'{l1[i]} is not a prime ')
break
else:
print(f'{l1[i]} is a prime number')
The solution is to do the loop that check if the number is prime for
for j in range(2, l1[i]):
Because here num have nothing to do with the check if it's prime.
So the complete code is :
l1 = []
num = int(input("Enter a range of numbers :: "))
for i in range(2, num + 1):
l1.append(i)
for i in range(0, num - 1):
for j in range(2, l1[i]):
if l1[i] % j == 0:
print(f'{l1[i]} is not a prime ')
break
else:
print(f'{l1[i]} is a prime number')
For more info about algorithm to check if a number is prime, please refer to :
this post

Which is the most pythonic way for writing a prime number function using for and while loop?

I am about to execute a function which aim is to return a Prime/Not prime statement if its argument is or isn't a prime number. I succeeded using a for loop:
def prime1(n):
z = []
for i in range (1, n+1):
if (n/i).is_integer():
z.append(i)
i=i+1
if len(z) == 2:
print ("Prime")
else:
print ("Not prime")`
Then I tried to do the same but using the while loop:
def prime2(n):
z = []
i = 1
while i < int(len(range(1, n+1))):
if (n/i).is_integer():
z.append(i)
i=i+1
if len(z) == 2:
print ("Prime")
else:
print ("Not prime")
Unfortunately, my system continues to calculating without printing me an output.
Can you explain me where I have made a mistake?
The i = i + 1 does nothing in your for loop, since the value of i is overwritten with the next value of the iterator; effectively, the for loop is performing i = i + 1 for you on every iteration, whether or not i divides n. You need to do the same thing in your while loop:
while i < n + 1:
if (n/i).is_integer():
z.append(i)
i = i + 1
The most pythonic way I could think of is below:
def isPrime(n):
return all(n % i for i in range(2, int(n ** 0.5) + 1)) and n > 1
for i in range(1, 20):
print(isPrime(i))
Explanation:
all makes sure that every item in the given expression returns True
n % i returns True if n != 0 (even negative numbers are allowed)
int(n ** 0.5) is equivalent to sqrt(n) and as range always returns numbers up to n - 1 you must add 1
n > 1 makes sure that n is not 1
The problem in your code is that your i = i + 1 in the wrong scope
Your program checks if (n/i).is_integer() which returns False as n / 2 is not a integer
Improving your code:
Instead of (n/i).is_integer() you can use n % i == 0, which returns the remainder equals 0
Next you must place i = i + 1 in the outer scope
And personally, I was never a fan of i = i + 1. Use i += 1
I think the best way is using the code I have shown above.
Hope this helps!
Edit:
You can make it print 'Prime' or 'Not Prime' as follows:
def isPrime(n):
print('Prime' if all(n % i for i in range(2, int(n ** 0.5) + 1))
and n > 1 else 'Not Prime')
for i in range(1, 20):
isPrime(i)
You are increment the iterable variable i inside the if statement, so the variable is never incremented, stucking on an infinite loop.
When you used for it worked because the iterable changes itself after every full iteration of the block.
Moving the incremenf of i one identation block to the left (inside the while instead of for) will work just fine
Code adapted from https://www.programiz.com/python-programming/examples/prime-number
You don't need to check until num and you can go 2 by 2 if you don't have a database of prime numbers
import math
#num = 437
if num > 1:
# check for factors
for i in range(2, int(math.ceil(math.sqrt(num))), 2):
if (num % i) == 0:
print(num, "is not a prime number")
print(i, "times", num // i, "is", num)
break
else:
print(num, "is a prime number")
# if input number is less than
# or equal to 1, it is not prime
else:
print(num, "is not a prime number")
Our preferred method should not be while loops if we don't need to use them, that being said, we could use list comprehensions:
def prime(n):
z = []
[z.append(i) for i in range(1, n+1) if (n/i).is_integer()]
[print("Prime") if len(z) == 2 else print("Not Prime")]
prime(101)
But lets take a loop at what you got your for loop:
for i in range (1, n+1):
if (n/i).is_integer():
z.append(i)
i=i+1
The line i = i + doesn't serve the purpose you intend, the loop is going to iterate from 1 to n+1 no matter what
Now the while loop:
while i < int(len(range(1, n+1))):
if (n/i).is_integer():
z.append(i)
# i=i+1 does not go inside if statement
i += 1
Now you do need to increment i but if that incrementing only occurs when the if conditions are met, then if the if condition is not met you are going to be stuck at the same i looping over it.
Also try using i += 1 means the same thing

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.

Find prime numbers less than or equal to the number the user has entered with loops. How do I do that?

With this code, I only get to test if the number the user entered is prime or not.
How do I add another loop to my original code in order to find all the prime numbers less than or equal to the number the user has entered?
num = int(input("Enter a number: "))
if num > 1:
prime = True
for n in range(2, num):
if (num % n) == 0:
print ("Number", num, "is not prime")
break
else:
print("Number", num, "is prime")
You can'not print both in one loop, you can do one thing add a loop above your current loop and display each number like this :
num = int(input("Enter a number: "))
if num > 1:
prime = True
for n in range(2, num):
if (num % n) == 0:
print ("Number", num, "is not prime")
break
else:
print("Number", num, "is prime")
#your current code ends here
for j in range(2, num + 1):
# prime numbers are greater than 1
for i in range(2, j):
if (j % i) == 0:
break
else:
print(j)
Your code only check the number entered is prime or not , but you questioned about to get prime numbers from 2 to n (n = number entered by user) for this you run below code with the help of flag bit it will little bit easy for you. i hope it will help you.
Try This i run this code It will Surely help you to find your answer it work in python 3.0 or above
num = int(input("Enter The Number"))
if num > 1:
num = num+1
list = []
for j in range (2,num,1):
flag = 0
for i in range (2,int(j/2)+1,1):
if(j%i)== 0:
flag = 1
break
if flag==0:
list.append(j)
print(list)
else:
print("Enter Number Greater Than 1")
Aside from small things (unused boolean variable) your prime test is also super inefficient.
Let's go through this step by step.
First: To test if a number is prime, you don't need to check all integers up to the number for divisors. Actually, going up to sqrt(num) turns out to be sufficient. We can write a one-liner function to find out if a number is prime like so:
from numpy import sqrt
def is_prime(n):
return n > 1 and all(n%i for i in range(2,int(sqrt(n))+1))
range(2,some_num) gives an iterator through all numbers from 2 up to some_num-1and the all() function checks if the statement n%i is true everywhere in that iterator and returns a boolean. If you can guarantee to never pass even numbers you can start the range from 3 (of course with the loss of generality). Even if you don't want to use that function, it's cleaner to separate the functionality into a different function, because in a loop of numbers up to your input you will probably have to check each number for being prime separately anyways.
Second: From here, finding all primes smaller or equal than your input should be pretty easy.
num = int(input("Enter a number:"))
assert num>0, "Please provide a positive integer" # stops with an assertion error if num<=0
prime_lst = [2] if num > 1 else []
for x in range(3,num+1,2):
if is_prime(x):
prime_lst.append(x)
The list prime_lst will contain all your sought after prime numbers. I start the loop from 1 such that I can loop through only the odd numbers, even numbers are divisible by two. So this way none of the numbers will be divisible by two. Unfortunately this requires me to check if the number itself may be 2, which is a prime. By the twin-prime conjecture we can not simplify this range further without knowing about the input.
Finally: If you really want to find the primes in one loop, change your loop to something along the lines of:
prime_lst = [2] if num > 1 else []
for x in range(3,num+1,2): # outer loop
for i in range(3,int(sqrt(x))+1): # inner loop for check if x is prime
if x%i == 0:
break # breaks the inner loop, number is not prime
else:
prime_lst.append(x)
Edit: Just saw that the second answer here has a good explanation (and an even better way) of writing the one-liner for finding out if a number is prime.

Categories