Range function in prime numbers program - python

this is a program for printing prime numbers from 2 and 11.
for num in range(2,12):
prime = True
for i in range(2,num):
if (num%i==0):
prime = False
if prime:
print num
In the second for-loop during the last iteration the value of the num=11 .. so the range should take num as 10 i.e (n-1) but in this program value 11 is still getting printed .. how is that?

num is indeed 11, and it is num that is being printed:
if prime:
print num
The range(2, num) range goes from 2 through to 10, inclusive, but the for loop over that range uses i as the target, not num:
for i in range(2, num):
# ^ the target of the for loop
So it is the value of i, not num that goes from 2 through to 10, and i is never printed. The value of num is not changed by the inner loop, it remains set to 11 all the way through. So yes, it'd be surprising if 10 was printed instead.
Note that the print num line is only ever executed if prime is still set to True. It would be set to False if num was divisible by any of the i values. For 11, there is no value between 2 and 10 (inclusive) that can divide 11, so prime remains set to True and num is printed.

Related

Problem with finding 10,001th prime number: 1 off

"""7. By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?"""
countprime=0
n=2
def prime(number):
for factors in range(2, number):
if number%factors==0:
return False
break
return True
while countprime!=10001:
if prime(n)==True:
countprime+=1
n+=1
print(n)
The answer is supposed to be 104743, but for some reason my brute force program gets 104744, 1 more. Does anyone know why it is one off?
while countprime != 10001:
if prime(n)==True:
countprime+=1
n+=1
When you find a prime number, you always move on to the next number. So, after finding the correct answer, you add up 1 and get 104744.
Try to firstly add 1, and then check if it's prime.
Here is an example:
n = 1
while countprime != 10001:
n += 1
if prime(n):
countprime += 1
You need to break your loop immediately when countprime == 10001 to leave your variable n untouched. A possible way:
while True:
countprime += prime(n)
if countprime == 10001:
break
n += 1
After your program finds the 10001th prime, the value of n is increased by 1 therefore your output is 1 more than the expected answer.
If you use print(n-1), your program will behave as expected.
You're increasing n one last time before your loop exits. If you increase n before checking if it's prime then your countPrime counter and the corresponding prime number will stay in sync (but you'll have to start n at 1 instead of 2):
n = 1
while countprime != 10001:
n += 1
if prime(n):
countprime += 1

How the Prime number code in python works?

def is_prime(num):
for i in range(2,num):
if (num % i) == 0:
return False
return True
def all_primes(num):
primes = []
for n in range(2,num+1):
if is_prime(n) is True:
primes.append(n)
return primes
num = int(input("Enter upper limit: "))
primes = all_primes(num)
print(primes)
How does it happens...
What understand is if I enter 10
It will be 10%2= 5...the remainder is 0 so it skip to the next one 9%2 = True there is remainder.
It moves to the next one 9%3 remainder is 0 so it skips to 8% ...,then 7 .......but what I dont understand is 7 if it's check until 7%7 ==0 then how did it add 7 as Prime number???
I'm so confused.
Thank you for any comment
but what I dont understand is 7 if it's check until 7%7 ==0
The range function from the following line:
for i in range(2, num):
goes from 2 to num - 1.
So, the range() function doesn't include the last (stop) number in the result.
You got it wrong. If you enter 10, it wouln't check 10%2 and then 9%2...
It would check 10%2, then 10%3, then 10%4... i.e. it would check 10%i, for i ranging from 2 to 9. However, note that execution in is_prime stops as soon as the remainder is 0:
for i in range(2,num):
if (num % i) == 0:
return False
So if num is 10, only 10%2 would be checked, and since it's 0, it would immediately return false.
If num is 9, for example, it would check 9%2. Since the remainder is not 0, it would move up to checking 9%3. The remainder is 0 there, so it would return false in that case.
If num was 7, it would check 7%2. The remainder is not 0 so it checks 7%3, which is also different from 0, and so on. The last check performed would be 7%6, because for i in range(2,num) means that it will iterate with i ranging from 2 to num-1. In this case, is_prime(7) would return true because 7%i, with i ranging from 2 to 6 is different than 0.
when is_prime is called for number 7, the loop will run from 2 to 6 only. Hence 7%7 will never be checked , returning True for such case.
A prime number, by definition, is a number that is divisible only by itself and 1.
Therefore, your function is_prime gets the number you want to check if it is prime, and try to find any other number that can divide it inside the interval [2, num), this interval is implemented using the function range(2,num) inside the for loop.
If it finds any case, i.e., if the if (num % i) == 0 is satisfied, we know that there is a number which divides it, therefore, by definition it is not a prime number.
After checking the whole list, if you cannot find a divisor, we can say that the number is prime, i.e., the return True on your function.
Example:
You want to check 9
(1st step) num = 9, i = 2. 9%2 != 0, we continue in the loop with next value of i.
(2nd step) num = 9, i = 3. 9%3 == 0, we return False. As we know, 9 can divide by 3.
Another example:
You want to check 7
num = 7, i = 2 7%2 != 0, so we continue in the loop with the next value of i
num = 7, i = 3 7%3 != 0, so we continue in the loop with the next value of i
num = 7, i = 4 7%4 != 0, so we continue in the loop with the next value of i
num = 7, i = 5 7%5 != 0, so we continue in the loop with the next value of i
num = 7, i = 6 7%6 != 0, so we continue in the loop with the next value of i
The if was never fulfilled, therefore we reach the end of the loop and
call the next command, which is return True.
Let's consider the two function separately:
def is_prime(num):
for i in range(2,num):
if (num % i) == 0:
return False
return True
This works like this:
let's consider a number num
get a variable i to assume the value 2
evaluate the condition num % i == 0
if the condition is met, then exit from the function and return False
otherwise increment i by 1 and repeat the last two steps until i is equal to num - 1
exit the function and return True
So, this never gets to evaluate 7 % 7: when num is 7 the last value of i is 6.
def all_primes(num):
primes = []
for n in range(2,num+1):
if is_prime(n) is True:
primes.append(n)
return primes
This gets a number num which is the upper limit of the numbers to consider, then:
it creates an empty list named primes
it loops n from 2 until num + 1 excluded (or num included)
if the result of is_prime(n) is True, it appends the number to the list.
finally, return the list in primes.
Finally the main body of the script:
num = int(input("Enter upper limit: "))
primes = all_primes(num)
print(primes)
gets you a string from the keyboard, convert it to int and assign to num, then call all_primes(num) and assign its result to primes and print the list to screen.
So, when you input 10 from the keyboard, it will check the values from 2 to 10 for being prime with is_prime(), and not from 10 and reducing them, as you seems to suggest.

Verify which numbers are prime in the list

I am trying to verify which numbers in the list are primes.
vetor = [2,3,4,5,11,15,20]
divisions_list = []
def isprime():
divisions = 0
i = 0
for i in range(1, vetor[i+1]):
if i % i == 0:
divisions = divisions + 1
divisions_list.append(divisions)
if divisions == 2:
print('The number {} is prime'.format(vetor[i]))
else:
print('The number {} is not prime'.format(vetor[i]))
print(isprime())
But this doesn't work, I'm only receiving:
The number 3 is not prime The number 4 is prime None
How can I fix this?
You already had a piece of code that takes a number and checks if it is a prime or not, then instead of using it you reinvented the wheel and broke it in the process (for example, you re-used i which caused a division by zero and tried to check if a list is equal to 2 instead of checking if its length is 2).
Use a function to reuse the working code with some improvements:
You don't really care how many numbers divide the number you check. It is enough that one number divides it in order for that number to not be prime
We can start the division check from 2, and it is proven mathematically that it is enough to go up to the square root of the number
from math import sqrt
def is_prime(n):
for i in range(2, int(sqrt(n)) + 1):
if n % i == 0:
return False
return True
Then use it with the list of numbers:
vector= [2, 3, 4, 5, 11, 15, 20]
for n in vector:
if is_prime(n):
print(n, 'is a prime')
else:
print(n, 'is not a prime')
Outputs
2 is a prime
3 is a prime
4 is not a prime
5 is a prime
11 is a prime
15 is not a prime
20 is not a prime
max divisor of an integer x, is sure x//2 and not sqr(x) and not sqrt(x)+1 , this is mathematics
For example x=16, sqrt(x)=4, sqr(x)+1=5
But max divisor of 16 is 8 (really 16//2)
"""
verify prime or not in a list of number
"""
# my function :)
def isPrime(x):
"""
function get an integer as argument, and return True if this argument is prime and False if not
"""
i = 2
while i<=x//2 :
if x%i != 0:
i += 1
else:
return False
return True
# your code :)
vetor = [2,3,4,5,11,15,20]
# for all elements e in vetor
for e in vetor:
# test the return of isPrime function applied to arg e
if isPrime(e):
print("{} is prime number".format(e))
else:
print("{} is not prime number".format(e))
I believe the problem is simpler than you're trying to make it. You have most of the pieces you need but we need to add a couple of things, toss a bunch of stuff, and rearrange a bit:
vetor = [2, 3, 4, 5, 11, 15, 20]
def isprime():
for number in vetor:
if number < 2:
print('The number {} is not prime'.format(number))
continue
i = 2
while i * i <= number:
if number % i == 0:
print('The number {} is not prime'.format(number))
break
i += 1
else: # no break
print('The number {} is prime'.format(number))
isprime()
Much of the additional code that other answers include is about efficiency and there's lots to be learned. But the above is sufficient for the code to work.
OUTPUT
> python3 test.py
The number 2 is prime
The number 3 is prime
The number 4 is not prime
The number 5 is prime
The number 11 is prime
The number 15 is not prime
The number 20 is not prime
>
My favorite number to include in a prime test is 25 as using < instead of <= tends to turn it into a prime!

listing prime numbers from 3 to 21 in python 3

for x in range (3,21):
if(x%2==0):
print (x,'is a not a prime number')
else:
print (x,'is a prime number')
This is my code but when it prints it says 9 is a prime number and 15 is a prime number.
Which is wrong because they aren't so how do I fix that?
.
def isPrime(N):
i = 2
while i**2 <= N:
if N % i == 0:
return False
i+=1
return True
for i in range(3, 21 + 1):
if isPrime(i):
print(i, 'is prime')
else:
print(i, 'is not a prime number')
First of all, create a function for determining whether or not a given number is prime (this is not a requirement but just a good practice). That function is not that hard: it just starts at i = 2 (starting at 1 makes no sense because every number can be divided by it) and check if N can be divided by it. If that is the case, we have found a divisor of N and thus, it isnt prime. Otherwise, continue with the next number: i += 1. The most tricky part of the loop is the stoping condition: i**2 <= N: we dont have to look further, because if some j > i is a divisor of N, then there is some other k < i that is also a divisor of N: k * j == N. If such k exists, we will find it before getting to the point where i * i == N. Thats all. After that, just iterate over each number you want to check for primality.
Btw, the best way to check for the primality of a set of number is using the Sieve of Eratosthenes
Your code only checks if a number is even. All odd numbers are not prime. So write a for-loop that checks if a odd number is divisible by any of the odd number less than that. Sometying like:
For i in (3 to n): If n mod i == 0, n is not prime.

Python - prime numbers

I am creating a program in python which adds up the total of all the prime numbrs up to 10. My code so far is:
total = 0
for i in range (10):
for a in range (2,i):
if i % a == 0:
break
else:
total += i
break
print total
My code does not include 2 as a prime number but does include 9. Can anybody spot the error?
Your else: clause needs to be with the for loop not if statement and no break.
As pointed out 2 drops through immediately, which is perfectly okay as it is prime and the else clause is executed:
total = 0
for num in range(2, 10): # Start from 2
for i in range(2, num):
if num%i==0:
break # Not prime, break causes else clause not to be executed
else:
total += num
print total
17
For very low numbers this will be fine, though you really only need to check to the sqrt of num.

Categories

Resources