Hi everyone :) (I am very new at this)
I am playing around with a simple piece of code which should print the prime numbers in a given range.
nums = range(1, 11)
for number in nums:
if number > 1:
for i in range(2, number):
if(number % i) == 0:
break
else:
print(number)
The output I get is as follows...
5
5
5
7
7
7
7
7
9
I can't understand why it is printing the prime numbers multiple times.
I expected it to print the numbers...
3,5,7,9
But cannot seem to understand why it is printing 5 3 times and 7 5 times etc.
You only need to move the print(number) statement outside of the else block,
nums = range(1, 11)
for number in nums:
if number > 1:
for i in range(2, number):
if (number % i) == 0:
break
else:
print(number)
Related
I have a piece of code here where I am creating a logic to be displaying all of the numbers from 2, to my int(input) to be converted to a list and then only display the prime numbers from 2 to my input.
Here is my code:
def display_prime_numbers(maximum):
lst = []
if maximum <= 2:
print('Enter Number Greater Than 2')
maximum = maximum + 1
rng = range(2,maximum)
for index in rng:
print(index, end=' ')
for i in rng:
if (index % i) == 0:
return False
else:
print(f'{index} is a prime number')
This is my output:
Enter Positive Integer Greater Than 2:10
2 3 4 5 6 7 8 9 10
Summary: I'm unable to display my range count loop as a list and am trying to only display my prime number pieces.
i.e. expected:
[2,3,4,5,6,7,8,9,10]
3 is a prime number
5 is a prime number
7 is a prime number
To clarify my comment, your return false statement will end the function. The first time the mod of the index is == 0, then the function will end and the rest of the list will not be evaluated for being prime.
def display_prime_numbers(maximum):
lst = []
if maximum <= 2:
print('Enter Number Greater Than 2')
maximum = maximum + 1
rng = range(2,maximum)
for index in rng:
print(index, end=' ')
for i in rng:
if (index % i) != 0: #Just print here!
print(f'{index} is a prime number')
display_prime_numbers(10)
I wanted to make a list of conditions for if. I wanted to make a program that would find very high prime numbers. I don't want to write: number % 2 == 0 or - for every number that I divide with. If you know how to make a list of conditions or know how to easier get high prime numbers using yield please give me a hint.
def very_high_prime_numbers_generator():
number = 0
while True:
number = yield
if not (number % 2 == 0 or number % 3 == 0 or number % 7 == 0 or number % 5 == 0 or number % 11 == 0 or number % 17 == 0 or number % 19 == 0 or number % 13 == 0):
print(number)
number_generator = very_high_prime_numbers_generator()
number_generator.send(None)
for i in range(1000,10000):
number_generator.send(i)
You can use a nested loop or any or all to test the divisibility of the number against all those values:
if not any(number % k == 0 for k in (2, 3, 5, 7, 11, 13, 17, 19)):
print(number)
Of course, this still tests only those values, which will not be enough for "very high prime numbers". Instead, you could keep track of the prime number generated so far an test against all of those:
def very_high_prime_numbers_generator():
primes = []
number = 2
while True:
if not any(number % p == 0 for p in primes):
yield number
primes.append(number)
number += 1
number_generator = very_high_prime_numbers_generator()
for _ in range(100):
print(next(number_generator))
(This could be further enhanced by stopping once k**2 > number, e.g. using itertools.takewhile, and only testing odd numbers above 2.)
Also note that your "generator" was rather odd. By using send to set the value of number and then printing inside the function, your "generator" behaved rather like a regular "check if this number is prime" function than a proper generator. The above also fixes that.
This seems to be what you're trying to do although as others have pointed out it's far from efficient.
def find_prime(number, previous_primes):
for value in previous_primes:
if number % value == 0:
return False
return True
known_primes = [2, 3, 5, 7]
for i in range(8, 1000):
is_prime = find_prime(i, known_primes)
if is_prime:
known_primes.append(i)
I would advise having a look here.
a possible solution (yet not that efficient) for printing primes might be as described by Eli Bendersky, in the above link:
import math
def main():
count = 3
while True:
isprime = True
for x in range(2, int(math.sqrt(count) + 1)):
if count % x == 0:
isprime = False
break
if isprime:
print count
count += 1
I am attending a course on Udemy and one of the exercises is to return all the prime numbers from a range of numbers (for example all prime numbers before 100)
This is the query that the teacher made
def count_primes2(num):
#Check for 1 or 0
if num < 2:
return 0
######################
#2 or greater
#Store our prime numbers
primes = [2] #I start my list with 2 that is a prime number
#Counter going up to the input num
x = 3 #I create a variable on which I will continue adding until I reach num
# x is going through every number up to the input num
while x <= num:
#Check if x is prime
for y in range(3,x,2): # for y in range from 3 to x in even steps, we only wantto check odd numbers there
if x%y == 0:
x += 2
break
else:
primes.append(x)
x += 2
print(primes)
return len(primes)
count_primes2(100)
However, I came up with the one below that is not working. My idea is:
Given each number i between between 3 and num+1 (for example 100 would be 101 so that 100 can be included in the calculation):
Open a for loop in which I divide i by each number g before i (including i) and I have a counter checking when this division gives no remainder. This implies that in case of prime numbers the counter should always be 2 (for example 3--> 3:1 and 3:3 would give remainder 0).
If the counter is equal to 2, then i is a prime and I want to append it to the list.
I am not using any while loop in my query. Can you help me to identify why my query is not working?
def count_prime(num):
counter=0
list_prime=[2]
if num<2:
return 0
for i in range(3,num+1):
for g in range(1,i+1):
if i%g==0:
counter+=1
if counter==2:
list_prime.append(i)
return list_prime
count_prime(100)
Kudos to Khelwood for the help. Below the working query:
def count_prime(num):
counter=0
list_prime=[2]
if num<2:
return 0
for i in range(3,num+1):
for g in range(1,i+1):
if i%g==0:
counter+=1
if counter==2:
list_prime.append(i)
counter=0
return list_prime
count_prime(100)
you may do this :
for i in range(2,num):
if (num % i) == 0:`
Instead of using two for loops, you can simply eliminate one of the for loop and do this, I hope this may work for you.
thankyou.
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 !
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